io.vertx.ext.web.RoutingContext Java Examples

The following examples show how to use io.vertx.ext.web.RoutingContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasicAuthenticationMechanism.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
    if (silent) {
        //if this is silent we only send a challenge if the request contained auth headers
        //otherwise we assume another method will send the challenge
        String authHeader = context.request().headers().get(HttpHeaderNames.AUTHORIZATION);
        if (authHeader == null) {
            return Uni.createFrom().optional(Optional.empty());
        }
    }
    ChallengeData result = new ChallengeData(
            HttpResponseStatus.UNAUTHORIZED.code(),
            HttpHeaderNames.WWW_AUTHENTICATE,
            challenge);
    return Uni.createFrom().item(result);
}
 
Example #2
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private boolean handlePreflight(RoutingContext ctx) {
  final HttpServerRequest request = ctx.request();
  // See: https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
  // Preflight requests should not be subject to security due to the reason UAs will remove the Authorization header
  if (request.method() == HttpMethod.OPTIONS) {
    // check if there is a access control request header
    final String accessControlRequestHeader = ctx.request().getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
    if (accessControlRequestHeader != null) {
      // lookup for the Authorization header
      for (String ctrlReq : accessControlRequestHeader.split(",")) {
        if (ctrlReq.equalsIgnoreCase("Authorization")) {
          // this request has auth in access control, so we can allow preflighs without authentication
          ctx.next();
          return true;
        }
      }
    }
  }

  return false;
}
 
Example #3
Source File: OidcIdentityProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
        AuthenticationRequestContext context) {
    ContextAwareTokenCredential credential = (ContextAwareTokenCredential) request.getToken();
    RoutingContext vertxContext = credential.getContext();
    return Uni.createFrom().deferred(new Supplier<Uni<SecurityIdentity>>() {
        @Override
        public Uni<SecurityIdentity> get() {
            if (tenantResolver.isBlocking(vertxContext)) {
                return context.runBlocking(new Supplier<SecurityIdentity>() {
                    @Override
                    public SecurityIdentity get() {
                        return authenticate(request, vertxContext).await().indefinitely();
                    }
                });
            }

            return authenticate(request, vertxContext);
        }
    });

}
 
Example #4
Source File: ErrorHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {

  HttpServerResponse response = context.response();

  Throwable failure = context.failure();

  int errorCode = context.statusCode();
  String errorMessage = null;
  if (errorCode != -1) {
    context.response().setStatusCode(errorCode);
    errorMessage = context.response().getStatusMessage();
  } else {
    errorCode = 500;
    if (displayExceptionDetails) {
      errorMessage = failure.getMessage();
    }
    if (errorMessage == null) {
      errorMessage = "Internal Server Error";
    }
    // no new lines are allowed in the status message
    response.setStatusMessage(errorMessage.replaceAll("\\r|\\n", " "));
  }

  answerWithError(context, errorCode, errorMessage);
}
 
Example #5
Source File: RequestHeaderAttribute.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public String readAttribute(final RoutingContext exchange) {
    List<String> header = exchange.request().headers().getAll(requestHeader);
    if (header.isEmpty()) {
        return null;
    } else if (header.size() == 1) {
        return header.get(0);
    }
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int i = 0; i < header.size(); ++i) {
        if (i != 0) {
            sb.append(", ");
        }
        sb.append(header.get(i));
    }
    sb.append("]");
    return sb.toString();
}
 
Example #6
Source File: TemplateEngineManager.java    From nubes with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  String tplDir = Utils.removeDots(config.getTplDir());
  String tplFile = Utils.normalizePath(ViewResolver.getViewName(context));

  TemplateEngine engine = fromViewName(tplDir + tplFile);
  if (engine == null) {
    LOG.error("No template handler found for " + tplDir + tplFile);
    context.fail(500);
    return;
  }

  engine.render(context, tplDir, tplFile, res -> {
    if (res.succeeded()) {
      context.response().putHeader(CONTENT_TYPE, "text/html").end(res.result());
    } else {
      context.fail(res.cause());
    }
  });
}
 
Example #7
Source File: DelegatingDeviceManagementHttpEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void doUpdateDevice(final RoutingContext ctx) {

        final Span span = TracingHelper.buildServerChildSpan(
                tracer,
                TracingHandler.serverSpanContext(ctx),
                SPAN_NAME_UPDATE_DEVICE,
                getClass().getSimpleName()
        ).start();

        final Future<String> tenantId = getRequestParameter(ctx, PARAM_TENANT_ID, getPredicate(config.getTenantIdPattern(), false));
        final Future<String> deviceId = getRequestParameter(ctx, PARAM_DEVICE_ID, getPredicate(config.getDeviceIdPattern(), false));
        final Future<Device> device = fromPayload(ctx);

        CompositeFuture.all(tenantId, deviceId, device)
            .compose(ok -> {
                logger.debug("updating device [tenant: {}, device-id: {}]", tenantId.result(), deviceId.result());
                final Optional<String> resourceVersion = Optional.ofNullable(ctx.get(KEY_RESOURCE_VERSION));
                return getService().updateDevice(tenantId.result(), deviceId.result(), device.result(), resourceVersion, span);
            })
            .onSuccess(operationResult -> writeResponse(ctx, operationResult, span))
            .onFailure(t -> failRequest(ctx, t, span))
            .onComplete(s -> span.finish());
    }
 
Example #8
Source File: ResponseHeaderAttribute.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public String readAttribute(final RoutingContext exchange) {
    List<String> header = exchange.response().headers().getAll(responseHeader);
    if (header.isEmpty()) {
        return null;
    } else if (header.size() == 1) {
        return header.get(0);
    }
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int i = 0; i < header.size(); ++i) {
        if (i != 0) {
            sb.append(", ");
        }
        sb.append(header.get(i));
    }
    sb.append("]");
    return sb.toString();
}
 
Example #9
Source File: RestDeployModuleHandler.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    context.request().bodyHandler(buffer -> {
        DeployApplicationRequest deployRequest = HttpUtils.readPostData(buffer, DeployApplicationRequest.class, LogConstants.DEPLOY_REQUEST);

        if (deployRequest == null) {
            HttpUtils.respondBadRequest(context.request());
            return;
        }

        LOG.info("[{} - {}]: Received deploy module {}", LogConstants.DEPLOY_REQUEST, deployRequest.getId().toString(), deployRequest.toString());

        service.deployAsync(deployRequest)
                .doOnCompleted(() -> HttpUtils.respondOk(context.request()))
                .doOnError(t -> HttpUtils.respondFailed(context.request()));
    });
}
 
Example #10
Source File: VertxRestInvocationTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateInvocation() {
  new MockUp<RestProducerInvocation>() {
    /**
     * Mock this method to avoid error
     */
    @Mock
    void createInvocation() {
    }
  };

  VertxRestInvocation vertxRestInvocation = new VertxRestInvocation();
  VertxServerRequestToHttpServletRequest requestEx = Mockito.mock(VertxServerRequestToHttpServletRequest.class);
  RoutingContext routingContext = Mockito.mock(RoutingContext.class);
  Invocation invocation = Mockito.mock(Invocation.class);

  Deencapsulation.setField(
      vertxRestInvocation, "requestEx", requestEx);
  Deencapsulation.setField(
      vertxRestInvocation, "invocation", invocation);
  Mockito.when(requestEx.getContext()).thenReturn(routingContext);

  Deencapsulation.invoke(vertxRestInvocation, "createInvocation");

  Mockito.verify(routingContext, Mockito.times(1)).put(RestConst.REST_INVOCATION_CONTEXT, invocation);
}
 
Example #11
Source File: RouteStateInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    RoutingContextImplBase routingContext = (RoutingContextImplBase) allArguments[0];
    List<Handler<RoutingContext>> contextHandlers = (List<Handler<RoutingContext>>) objInst.getSkyWalkingDynamicField();
    AtomicInteger currentContextIndex = (AtomicInteger) ((EnhancedInstance) routingContext).getSkyWalkingDynamicField();
    int handlerContextIndex = currentContextIndex.get();
    if (VertxContext.VERTX_VERSION >= 35 && contextHandlers.size() > 1) {
        currentContextIndex.getAndIncrement(); //3.5+ has possibility for multiple handlers
    }
    String contextName = contextHandlers.get(handlerContextIndex).getClass().getCanonicalName();
    int lambdaOffset = contextName.indexOf("$$Lambda$");
    if (lambdaOffset > 0) contextName = contextName.substring(0, lambdaOffset + 9);
    AbstractSpan span = ContextManager.createLocalSpan(String.format("%s.handle(RoutingContext)", contextName));

    Object connection = ((EnhancedInstance) routingContext.request()).getSkyWalkingDynamicField();
    VertxContext vertxContext = (VertxContext) ((EnhancedInstance) connection).getSkyWalkingDynamicField();
    ContextManager.continued(vertxContext.getContextSnapshot());
    span.setComponent(ComponentsDefine.VERTX);
    SpanLayer.asHttp(span);
}
 
Example #12
Source File: FormBodyProcessorImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public Future<RequestParameter> process(RoutingContext requestContext) {
  try {
    MultiMap multiMap = requestContext.request().formAttributes();
    JsonObject object = new JsonObject();
    for (String key : multiMap.names()) {
      List<String> serialized = multiMap.getAll(key);
      Map.Entry<String, Object> parsed = parseField(key, serialized);
      if (parsed != null) object.put(parsed.getKey(), parsed.getValue());
    }
    return valueValidator.validate(object).recover(err -> Future.failedFuture(
      BodyProcessorException.createValidationError(requestContext.parsedHeaders().contentType().value(), err)
    ));
  } catch (MalformedValueException e) {
    return Future.failedFuture(BodyProcessorException.createParsingError(requestContext.request().getHeader(HttpHeaders.CONTENT_TYPE), e));
  }
}
 
Example #13
Source File: ActionsHandler.java    From hawkular-alerts with Apache License 2.0 6 votes vote down vote up
@DocPath(method = GET,
        path = "/plugin/{actionPlugin}",
        name = "Find all action ids of an specific action plugin.")
@DocParameters(value = {
        @DocParameter(name = "actionPlugin", required = true, path = true,
                description = "Action plugin to filter query for action ids.")
})
@DocResponses(value = {
        @DocResponse(code = 200, message = "Successfully fetched list of action ids.", response = ApiDeleted.class),
        @DocResponse(code = 500, message = "Internal server error.", response = ApiError.class)
})
public void findActionIdsByPlugin(RoutingContext routing) {
    routing.vertx()
            .executeBlocking(future -> {
                String tenantId = ResponseUtil.checkTenant(routing);
                String actionPlugin = routing.request().getParam("actionPlugin");
                try {
                    Collection<String> actions = definitionsService.getActionDefinitionIds(tenantId, actionPlugin);
                    log.debugf("Actions: %s", actions);
                    future.complete(actions);
                } catch (Exception e) {
                    log.errorf("Error querying actions ids for tenantId %s and actionPlugin %s. Reason: %s", tenantId, actionPlugin, e.toString());
                    throw new ResponseUtil.InternalServerException(e.toString());
                }
            }, res -> ResponseUtil.result(routing, res));
}
 
Example #14
Source File: BaseTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
static Handler<RoutingContext> createCORSOptionsHandler(SockJSHandlerOptions options, String methods) {
  return rc -> {
    if (log.isTraceEnabled()) log.trace("In CORS options handler");
    rc.response().putHeader(CACHE_CONTROL, "public,max-age=31536000");
    long oneYearSeconds = 365 * 24 * 60 * 60;
    long oneYearms = oneYearSeconds * 1000;
    String expires = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date(System.currentTimeMillis() + oneYearms));
    rc.response()
      .putHeader(EXPIRES, expires)
      .putHeader(ACCESS_CONTROL_ALLOW_METHODS, methods)
      .putHeader(ACCESS_CONTROL_MAX_AGE, String.valueOf(oneYearSeconds));
    setCORS(rc);
    setJSESSIONID(options, rc);
    rc.response().setStatusCode(204);
    rc.response().end();
  };
}
 
Example #15
Source File: WebHelper.java    From nassh-relay with GNU General Public License v2.0 6 votes vote down vote up
public static AuthSession validateCookie(final RoutingContext context) {
    final Cookie cookie = context.getCookie(Constants.SESSIONCOOKIE);
    if (cookie == null) {
        return null;
    }
    final UUID sessioncookie = UUID.fromString(cookie.getValue());
    final AuthSession session = AuthSessionManager.getSession(sessioncookie);
    if (session == null) {
        return null;
    }
    final String id = session.get("id");
    if (id != null) {
        return session;
    }
    return null;
}
 
Example #16
Source File: TenantLoadingTest.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private void fakeHttpServerHandler(RoutingContext ctx) {
  ctx.response().setChunked(true);
  Buffer buffer = Buffer.buffer();
  ctx.request().handler(buffer::appendBuffer);
  ctx.request().endHandler(x -> {
    if (ctx.request().method() == HttpMethod.PUT) {
      String path = ctx.request().path();
      int idx = path.lastIndexOf('/');
      if (idx != -1) {
        try {
          String id = URLDecoder.decode(path.substring(idx + 1), "UTF-8");
          ids.add(id);
        } catch (UnsupportedEncodingException ex) {
          ctx.response().setStatusCode(400);
          return;
        }
      }
      ctx.response().setStatusCode(putStatus);
    } else if (ctx.request().method() == HttpMethod.POST) {
      ctx.response().setStatusCode(postStatus);
    } else {
      ctx.response().setStatusCode(405);
    }
    ctx.response().end();
  });
}
 
Example #17
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that an event message is rejected due to the limit exceeded.
 *
 */
@Test
public void testMessageLimitExceededForAnEventMessage() {

    // GIVEN an adapter with a downstream event consumer attached
    final Future<ProtonDelivery> outcome = Future.succeededFuture(mock(ProtonDelivery.class));
    givenAnEventSenderForOutcome(outcome);

    final HttpServer server = getHttpServer(false);
    final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null);

    final Buffer payload = Buffer.buffer("some payload");
    final RoutingContext routingContext = newRoutingContext(payload);

    // WHEN the message limit exceeds
    when(resourceLimitChecks.isMessageLimitReached(any(TenantObject.class), anyLong(), any(SpanContext.class)))
            .thenReturn(Future.succeededFuture(Boolean.TRUE));
    // WHEN a device that belongs to "my-tenant" publishes an event message
    adapter.uploadEventMessage(routingContext, "my-tenant", "the-device", payload, "application/text");

    // THEN the device gets a 429
    assertContextFailedWithClientError(routingContext, HttpUtils.HTTP_TOO_MANY_REQUESTS);
    // the message has been reported
    verify(metrics).reportTelemetry(
            eq(EndpointType.EVENT),
            eq("my-tenant"),
            any(),
            eq(ProcessingOutcome.UNPROCESSABLE),
            eq(QoS.AT_LEAST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #18
Source File: OfficialAccountSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 将有效的信息塞入JSON并响应
 * 不是将查询到的json直接返回,是为了避免多余的敏感信息泄露
 */
private void responseOneAccount(RoutingContext rc, JsonObject offAcc) {
    JsonObject result = new JsonObject()
            .put("id", offAcc.getInteger(ID))
            .put("name", offAcc.getString(NAME))
            .put("appid", offAcc.getString(WXAPPID))
            .put("appsecret", offAcc.getString(WXAPPSECRET))
            .put("verify", offAcc.getString(VERIFY))
            .put("role", offAcc.getInteger(ROLE))
            .put("projUrl", Constants.PROJ_URL);
    rc.response().putHeader("content-type", "application/json; charset=utf-8").end(result.toString());
}
 
Example #19
Source File: LocalMapParamInjector.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolve(RoutingContext context, VertxLocalMap annotation, String paramName, Class<?> resultClass) {
  SharedData sd = context.vertx().sharedData();
  String mapName = annotation.value();
  if ("".equals(mapName)) {
    mapName = paramName;
  }
  return sd.getLocalMap(mapName);
}
 
Example #20
Source File: LoraProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private LoraProvider getLoraProviderMock(final LoraMessage message) {
    final LoraProvider provider = mock(LoraProvider.class);
    when(provider.getProviderName()).thenReturn(TEST_PROVIDER);
    when(provider.pathPrefix()).thenReturn("/bumlux");
    when(provider.getMessage(any(RoutingContext.class))).thenReturn(message);

    return provider;
}
 
Example #21
Source File: RouteToEBServiceHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private JsonObject buildPayload(RoutingContext context) {
  JsonObject params = context.get("parsedParameters") != null ? ((RequestParameters)context.get("parsedParameters")).toJson() : null;
  return new JsonObject().put("context", new ServiceRequest(
    params,
    context.request().headers(),
    (context.user() != null) ? context.user().principal() : null,
    (this.extraPayloadMapper != null) ? this.extraPayloadMapper.apply(context) : null
  ).toJson());
}
 
Example #22
Source File: ArbiterModule.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
private void setSession(String newSessionID, RoutingContext rc) {
    log.debug("Arbiter UI: Set to session {}", newSessionID);

    if (knownSessionIDs.containsKey(newSessionID)) {
        currentSessionID = newSessionID;
        rc.response().end();
    } else {
        rc.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end("Unknown session ID: " + newSessionID);
    }
}
 
Example #23
Source File: SkLearnPmmlHandler.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Override
public Buffer getPmmlBuffer(RoutingContext routingContext, Object... otherInputs) throws Exception {
    File tmpFile = (File) otherInputs[0];
    Object object = ConverterPickle.unpickle(tmpFile);
    Buffer writeBuffer = ConverterPickle.writePmml(object);
    return writeBuffer;
}
 
Example #24
Source File: PrimitiveParameterResolver.java    From festival with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doResolve(Parameter parameter, RoutingContext routingContext) {
    if (!AnnotationUtils.isAnnotationPresent(parameter, Param.class)) {
        return null;
    }

    Param param = AnnotationUtils.getMergedAnnotation(parameter, Param.class);

    String name = Objects.requireNonNull(param).value();

    Class<?> parameterType = parameter.getType();

    MultiMap params = resolveParams(routingContext);

    if (params.contains(name)) {
        return StringUtils.castToPrimitive(params.get(name), parameterType);
    }

    if (param.required()) {
        throw new IllegalStateException(String.format("%s %s param %s is required but not received !",
                routingContext.request().method(),
                routingContext.request().path(), name));

    }

    if ("null".equals(param.defaultValue()) || StringUtils.isEmpty(param.defaultValue())) {
        return null;
    }

    return StringUtils.castToPrimitive(param.defaultValue(), parameterType);
}
 
Example #25
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handleJsonRpcUnauthorizedError(
    final RoutingContext routingContext, final Object id, final JsonRpcError error) {
  final HttpServerResponse response = routingContext.response();
  if (!response.closed()) {
    response
        .setStatusCode(HttpResponseStatus.UNAUTHORIZED.code())
        .end(Json.encode(new JsonRpcErrorResponse(id, error)));
  }
}
 
Example #26
Source File: YOLOOutputAdapter.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, BatchOutput> adapt(INDArray[] input, List<String> outputNames, RoutingContext routingContext) {
    int originalHeight = (int) routingContext.data().get(VerticleConstants.ORIGINAL_IMAGE_HEIGHT);
    int originalWidth = (int) routingContext.data().get(VerticleConstants.ORIGINAL_IMAGE_WIDTH);

    DetectedObjectsBatch[] detectedObjects = getPredictedObjects(input, threshold, outputNames.toArray(new String[outputNames.size()]), originalHeight, originalWidth);
    Map<String, BatchOutput> ret = new HashMap<>();
    ret.put(outputNames.get(0), ManyDetectedObjects.builder().detectedObjectsBatches(detectedObjects).build());
    return ret;
}
 
Example #27
Source File: WechatPaySubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 微信支付回调接口
 * 更新订单状态(更新shop_order,已支付,商城订单号,支付类型,支付时间)
 *
 * 异步返回 成功则返回微信接口规定的信息,失败则返回“下单失败”
 *
 * @author Leibniz
 */
private void wechatNotify(RoutingContext rc) {
    String param = rc.getBody().toString();
    log.info("接收到微信支付回调请求,请求数据: " + param);
    //将解析后的数据传入map
    Map<String, String> payReturnParam = XmlUtils.xmltoMap(param);
    //TODO 完善其他返回状态的处理
    HttpServerResponse response = rc.response();
    if ("SUCCESS".equals(payReturnParam.get("return_code"))) {
        String localOrderId = payReturnParam.get("out_trade_no"); //本地订单ID
        String wechatOrderId = payReturnParam.get("transaction_id"); //微信订单ID
        //调用callback 更新订单数据,已支付,商城订单号,支付类型,支付时间
        JsonObject updateOrder = new JsonObject().put(PLATORDERID, wechatOrderId).put(ORDERID, localOrderId).put(TYPE, 0);
        vertx.eventBus().<Integer>send(ADDR_ORDER_DB.get(), makeMessage(COMMAND_UPDATE_PAID_ORDER, updateOrder), ebar -> {
            if (ebar.succeeded()) {
                int rows = ebar.result().body();
                log.info("微信支付回调更新数据库,影响行数={}", rows);
            } else {
                log.error("EventBus消息响应错误", ebar.cause());
                response.setStatusCode(500).end("EventBus error!");
            }
        });
        response.putHeader("content-type", "application/xml; charset=utf-8").end(WECHAT_CALLBACK_SUCCESS_RETURN);
    } else {
        response.end("下单失败");
    }
}
 
Example #28
Source File: HttpResponse.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Produce HTTP response with status code and application/json header.
 * @param ctx routing context from where HTTP response is generated
 * @param code status code
 * @return HTTP server response
 */
public static HttpServerResponse responseJson(RoutingContext ctx, int code) {
  HttpServerResponse res = ctx.response();
  if (!res.closed()) {
    res.setStatusCode(code).putHeader("Content-Type", "application/json");
  }
  return res;
}
 
Example #29
Source File: VertxWebController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void handleWebCase(RoutingContext routingContext) {
    WebClient.create(vertx).head(8080, "localhost", "/vertx-web-3_6plus-scenario/case/healthCheck")
            .send(healthCheck -> {
                if (healthCheck.succeeded()) {
                    WebClient.create(vertx).get(8080, "localhost", "/vertx-web-3_6plus-scenario/case/web-case/withBodyHandler")
                            .send(it -> routingContext.response().setStatusCode(it.result().statusCode()).end());
                } else {
                    healthCheck.cause().printStackTrace();
                    routingContext.response().setStatusCode(500).end();
                }
            });
}
 
Example #30
Source File: RestProductAPIVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
private void apiAdd(RoutingContext context) {
  try {
    Product product = new Product(new JsonObject(context.getBodyAsString()));
    service.addProduct(product, resultHandler(context, r -> {
      String result = new JsonObject().put("message", "product_added")
        .put("productId", product.getProductId())
        .encodePrettily();
      context.response().setStatusCode(201)
        .putHeader("content-type", "application/json")
        .end(result);
    }));
  } catch (DecodeException e) {
    badRequest(context, e);
  }
}