io.vertx.core.http.HttpServerResponse Java Examples
The following examples show how to use
io.vertx.core.http.HttpServerResponse.
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: DefaultFailureHandlerTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the handler does not try to process a failed * context if the response is already ended. */ @Test public void testHandlerDetectsEndedResponse() { final HttpServerResponse response = mock(HttpServerResponse.class); when(response.ended()).thenReturn(true); final RoutingContext ctx = mock(RoutingContext.class); when(ctx.response()).thenReturn(response); when(ctx.failed()).thenReturn(true); final DefaultFailureHandler handler = new DefaultFailureHandler(); handler.handle(ctx); verify(response, never()).setStatusCode(anyInt()); verify(response, never()).write(any(Buffer.class)); verify(response, never()).end(); }
Example #2
Source File: UserApiHandler.java From openapi-generator with Apache License 2.0 | 6 votes |
private void deleteUser(RoutingContext routingContext) { logger.info("deleteUser()"); HttpServerResponse response = routingContext.response(); Single.defer( () -> { String username = ParameterCast.toString(routingContext.pathParams().get("username")); logger.info("Parameter username is {}", username); return apiImpl.deleteUser(username); }) .subscribe( apiResponse -> { response.setStatusCode(apiResponse.getStatusCode()) .end(Json.encodePrettily(apiResponse.getData())); }, error -> { if (error instanceof ApiException) { ApiException apiException = (ApiException) error; response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage()); } else { response.setStatusCode(500).end(error.getMessage()); } }).dispose(); }
Example #3
Source File: NexusHttpProxy.java From nexus-proxy with Apache License 2.0 | 6 votes |
/** * Proxies the specified HTTP request, enriching its headers with authentication information. * * @param userId the ID of the user making the request. * @param origReq the original request (i.e., {@link RoutingContext#request()}. * @param origRes the original response (i.e., {@link RoutingContext#request()}. */ public void proxyUserRequest(final String userId, final HttpServerRequest origReq, final HttpServerResponse origRes) { final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> { origRes.setChunked(true); origRes.setStatusCode(proxiedRes.statusCode()); origRes.headers().setAll(proxiedRes.headers()); proxiedRes.handler(origRes::write); proxiedRes.endHandler(v -> origRes.end()); }; final HttpClientRequest proxiedReq; proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler); if(origReq.method() == HttpMethod.OTHER) { proxiedReq.setRawMethod(origReq.rawMethod()); } proxiedReq.setChunked(true); proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme())); proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host())); proxiedReq.headers().addAll(origReq.headers()); injectRutHeader(proxiedReq, userId); origReq.handler(proxiedReq::write); origReq.endHandler(v -> proxiedReq.end()); }
Example #4
Source File: X509AuthHandlerTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the handler returns the status code conveyed in a * failed Tenant service invocation in the response. * * @throws SSLPeerUnverifiedException if the client certificate cannot be validated. */ @Test public void testHandleFailsWithStatusCodeFromAuthProvider() throws SSLPeerUnverifiedException { // GIVEN an auth handler configured with an auth provider that // fails with a 503 error code during authentication final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE); when(clientAuth.validateClientCertificate(any(Certificate[].class), (SpanContext) any())).thenReturn(Future.failedFuture(error)); // WHEN trying to authenticate a request that contains a client certificate final EmptyCertificate clientCert = new EmptyCertificate("CN=device", "CN=tenant"); final SSLSession sslSession = mock(SSLSession.class); when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[] { clientCert }); final HttpServerRequest req = mock(HttpServerRequest.class); when(req.isSSL()).thenReturn(true); when(req.sslSession()).thenReturn(sslSession); final HttpServerResponse resp = mock(HttpServerResponse.class); final RoutingContext ctx = mock(RoutingContext.class); when(ctx.get(TracingHandler.CURRENT_SPAN)).thenReturn(mock(Span.class)); when(ctx.request()).thenReturn(req); when(ctx.response()).thenReturn(resp); authHandler.handle(ctx); // THEN the request context is failed with the 503 error code verify(ctx).fail(error); }
Example #5
Source File: RxVertxProvider.java From redpipe with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Vertx vertx = ResteasyProviderFactory.getContextData(io.vertx.core.Vertx.class); HttpServerRequest req = ResteasyProviderFactory.getContextData(HttpServerRequest.class); HttpServerResponse resp = ResteasyProviderFactory.getContextData(HttpServerResponse.class); // rx2 ResteasyProviderFactory.pushContext(io.vertx.reactivex.core.Vertx.class, io.vertx.reactivex.core.Vertx.newInstance(vertx)); ResteasyProviderFactory.pushContext(io.vertx.reactivex.core.http.HttpServerRequest.class, io.vertx.reactivex.core.http.HttpServerRequest.newInstance(req)); ResteasyProviderFactory.pushContext(io.vertx.reactivex.core.http.HttpServerResponse.class, io.vertx.reactivex.core.http.HttpServerResponse.newInstance(resp)); // rx1 ResteasyProviderFactory.pushContext(io.vertx.rxjava.core.Vertx.class, io.vertx.rxjava.core.Vertx.newInstance(vertx)); ResteasyProviderFactory.pushContext(io.vertx.rxjava.core.http.HttpServerRequest.class, io.vertx.rxjava.core.http.HttpServerRequest.newInstance(req)); ResteasyProviderFactory.pushContext(io.vertx.rxjava.core.http.HttpServerResponse.class, io.vertx.rxjava.core.http.HttpServerResponse.newInstance(resp)); ResteasyProviderFactory.pushContext(ServletContext.class, AppGlobals.get().getGlobal(ServletContext.class)); }
Example #6
Source File: PgUtil.java From raml-module-builder with Apache License 2.0 | 6 votes |
/** * streamGet that takes CQLWrapper and FacetField List * @param <T> * @param table * @param clazz * @param filter * @param facetList * @param element * @param queryTimeout query timeout in milliseconds, or 0 for no timeout * @param okapiHeaders * @param vertxContext * @param routingContext */ @SuppressWarnings({"unchecked", "squid:S107"}) // Method has >7 parameters public static <T> void streamGet(String table, Class<T> clazz, CQLWrapper filter, List<FacetField> facetList, String element, int queryTimeout, RoutingContext routingContext, Map<String, String> okapiHeaders, Context vertxContext) { HttpServerResponse response = routingContext.response(); PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.streamGet(table, clazz, JSON_COLUMN, filter, true, null, facetList, queryTimeout, reply -> { if (reply.failed()) { String message = PgExceptionUtil.badRequestMessage(reply.cause()); if (message == null) { message = reply.cause().getMessage(); } logger.error(message, reply.cause()); response.setStatusCode(400); response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); response.end(message); return; } streamGetResult(reply.result(), element, response); }); }
Example #7
Source File: LanAccessSubRouter.java From AlipayWechatPlatform with GNU General Public License v3.0 | 6 votes |
/** * 判断当前请求是否允许,如果不允许,则将状态码设为403并结束响应 * * @return true:禁止访问 false=允许访问 * @author Leibniz.Hu */ protected boolean refuseNonLanAccess(RoutingContext rc) { HttpServerRequest req = rc.request(); HttpServerResponse resp = rc.response(); String realIp = req.getHeader("X-Real-IP"); String xforward = req.getHeader("X-Forwarded-For"); //禁止外网访问 if (realIp != null && !isLanIP(realIp)) { log.warn("检测到非法访问,来自X-Real-IP={}", realIp); resp.setStatusCode(403).end(); return true; } if (xforward != null && !isLanIP(xforward)) { log.warn("检测到非法访问,来自X-Forwarded-For={}", xforward); resp.setStatusCode(403).end(); return true; } return false; }
Example #8
Source File: KeepAliveHttpServerResponse.java From sfs with Apache License 2.0 | 6 votes |
@Override public HttpServerResponse push(HttpMethod method, String host, String path, MultiMap headers, Handler<AsyncResult<HttpServerResponse>> handler) { ObservableFuture<Void> h = RxHelper.observableFuture(); stopKeepAlive(h); h.subscribe(new Subscriber<Void>() { @Override public void onCompleted() { delegate.push(method, host, path, headers, handler); } @Override public void onError(Throwable e) { handleThrowable(e); } @Override public void onNext(Void aVoid) { } }); return this; }
Example #9
Source File: AbstractVertxBasedHttpProtocolAdapter.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Response to a request with a non-empty command response. * <p> * The default implementation sets the command headers and the status to {@link HttpURLConnection#HTTP_OK}. * * @param response The response to update. * @param commandContext The command context, will not be {@code null}. * @param currentSpan The current tracing span. */ protected void setNonEmptyResponsePayload(final HttpServerResponse response, final CommandContext commandContext, final Span currentSpan) { final Command command = commandContext.getCommand(); response.putHeader(Constants.HEADER_COMMAND, command.getName()); currentSpan.setTag(Constants.HEADER_COMMAND, command.getName()); log.debug("adding command [name: {}, request-id: {}] to response for device [tenant-id: {}, device-id: {}]", command.getName(), command.getRequestId(), command.getTenant(), command.getDeviceId()); if (!command.isOneWay()) { response.putHeader(Constants.HEADER_COMMAND_REQUEST_ID, command.getRequestId()); currentSpan.setTag(Constants.HEADER_COMMAND_REQUEST_ID, command.getRequestId()); } if (command.isTargetedAtGateway()) { response.putHeader(Constants.HEADER_COMMAND_TARGET_DEVICE, command.getOriginalDeviceId()); currentSpan.setTag(Constants.HEADER_COMMAND_TARGET_DEVICE, command.getOriginalDeviceId()); } response.setStatusCode(HttpURLConnection.HTTP_OK); HttpUtils.setResponseBody(response, command.getPayload(), command.getContentType()); }
Example #10
Source File: Jukebox.java From vertx-in-action with MIT License | 6 votes |
private void downloadFile(AsyncFile file, HttpServerRequest request) { HttpServerResponse response = request.response(); response.setStatusCode(200) .putHeader("Content-Type", "audio/mpeg") .setChunked(true); file.handler(buffer -> { response.write(buffer); if (response.writeQueueFull()) { file.pause(); response.drainHandler(v -> file.resume()); } }); file.endHandler(v -> response.end()); }
Example #11
Source File: DefaultFailureHandlerTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the handler writes the detail message of the failure * to the response. */ @Test public void testHandlerWritesDetailMessageToBody() { final String detailMessage = "detail message"; final HttpServerRequest request = mock(HttpServerRequest.class, Mockito.RETURNS_MOCKS); final HttpServerResponse response = mock(HttpServerResponse.class); when(response.ended()).thenReturn(false); final RoutingContext ctx = mock(RoutingContext.class); when(ctx.request()).thenReturn(request); when(ctx.response()).thenReturn(response); when(ctx.failed()).thenReturn(true); when(ctx.failure()).thenReturn(new IllegalStateException(detailMessage)); final DefaultFailureHandler handler = new DefaultFailureHandler(); handler.handle(ctx); final ArgumentCaptor<Buffer> bufferCaptor = ArgumentCaptor.forClass(Buffer.class); verify(response).setStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR); verify(response).write(bufferCaptor.capture()); assertThat(bufferCaptor.getValue().toString()).isEqualTo(detailMessage); verify(response).end(); }
Example #12
Source File: AbstractEventBusHttpEndpoint.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Gets a response handler that implements the default behavior for responding to an HTTP request. * <p> * The default behavior is as follows: * <ol> * <li>Set the status code on the response.</li> * <li>If the status code represents an error condition (i.e. the code is >= 400), * then the JSON object passed in to the returned handler is written to the response body.</li> * <li>Otherwise, if the given filter evaluates to {@code true} for the status code, * the JSON object is written to the response body and the given custom handler is * invoked (if not {@code null}).</li> * </ol> * * @param ctx The routing context of the request. * @param successfulOutcomeFilter A predicate that evaluates to {@code true} for the status code(s) representing a * successful outcome. * @param customHandler An (optional) handler for post processing the HTTP response, e.g. to set any additional HTTP * headers. The handler <em>must not</em> write to response body. May be {@code null}. * @return The created handler for processing responses. * @throws NullPointerException If routing context or filter is {@code null}. */ protected final BiConsumer<Integer, EventBusMessage> getDefaultResponseHandler( final RoutingContext ctx, final IntPredicate successfulOutcomeFilter, final Handler<HttpServerResponse> customHandler) { Objects.requireNonNull(successfulOutcomeFilter); final HttpServerResponse response = ctx.response(); return (status, responseMessage) -> { response.setStatusCode(status); if (status >= 400) { HttpUtils.setResponseBody(response, responseMessage.getJsonPayload()); } else if (successfulOutcomeFilter.test(status)) { HttpUtils.setResponseBody(response, responseMessage.getJsonPayload()); if (customHandler != null) { customHandler.handle(response); } } response.end(); }; }
Example #13
Source File: ApiKeysServiceHandler.java From gravitee-gateway with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext ctx) { HttpServerResponse response = ctx.response(); response.setStatusCode(HttpStatusCode.OK_200); response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); response.setChunked(true); try { Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); response.write(Json.prettyMapper.writeValueAsString(new ExecutorStatistics())); } catch (JsonProcessingException jpe) { response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500); LOGGER.error("Unable to transform data object to JSON", jpe); } response.end(); }
Example #14
Source File: DashboardVerticle.java From microtrader with MIT License | 6 votes |
private void callAuditServiceWithExceptionHandlerWithCircuitBreaker(RoutingContext context) { HttpServerResponse resp = context.response() .putHeader("content-type", "application/json") .setStatusCode(200); circuit.executeWithFallback( future -> client.get(root, response -> { response .exceptionHandler(future::fail) .bodyHandler(future::complete); }) .exceptionHandler(future::fail) .setTimeout(5000) .end(), t -> Buffer.buffer("{\"message\":\"No audit service, or unable to call it\"}") ) .setHandler(ar -> resp.end(ar.result())); }
Example #15
Source File: ClientVerticle.java From VX-API-Gateway with MIT License | 6 votes |
/** * 启动一个API * * @param rct */ public void stopAPI(RoutingContext rct) { String appName = rct.request().getParam("appName"); String apiName = rct.request().getParam("apiName"); JsonObject body = new JsonObject(); body.put("appName", appName); body.put("apiName", apiName); HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8); LOG.info(MessageFormat.format("[user : {0}] 执行暂停API-->{1}", rct.session().get("userName"), apiName)); vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.DEPLOY_API_STOP, body, reply -> { if (reply.succeeded()) { Integer result = reply.result().body(); LOG.info(MessageFormat.format("[user : {0}] 执行暂停API:{1}-->结果:{2}", rct.session().get("userName"), apiName, result)); response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, result)); if (vertx.isClustered()) { vertx.eventBus().publish(VxApiEventBusAddressConstant.DEPLOY_API_STOP, body.copy().put("thisVertxName", thisVertxName)); LOG.info("广播告诉集群环境中暂停应用:" + appName + "的" + apiName + "API"); } } else { LOG.error( MessageFormat.format("[user : {0}] 执行暂停API:{1}-->失败:{2}", rct.session().get("userName"), apiName, reply.cause().toString())); response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, reply.cause().toString())); } }); }
Example #16
Source File: RestRouter.java From rest.vertx with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static void produceResponse(Object result, RoutingContext context, RouteDefinition definition, HttpResponseWriter writer) throws Throwable { HttpServerResponse response = context.response(); HttpServerRequest request = context.request(); MediaType accept = MediaTypeHelper.valueOf(request.getHeader(HttpHeaders.ACCEPT)); // add default response headers per definition (or from writer definition) writer.addResponseHeaders(definition, accept, response); writer.write(result, request, response); // find and trigger events from // result / response eventExecutor.triggerEvents(result, response.getStatusCode(), definition, context, injectionProvider); // finish if not finished by writer // and is not an Async REST (Async RESTs must finish responses on their own) if (!definition.isAsync() && !response.ended()) { response.end(); } }
Example #17
Source File: ClientVerticle.java From VX-API-Gateway with MIT License | 6 votes |
/** * 卸载应用 * * @param rct */ public void unDeployAPP(RoutingContext rct) { String name = rct.request().getParam("name"); LOG.info("执行暂停应用-->" + name + "..."); HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8); if (StrUtil.isNullOrEmpty(name)) { response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C1404)); } else { JsonObject config = new JsonObject().put("appName", name); vertx.eventBus().<String>send(thisVertxName + VxApiEventBusAddressConstant.DEPLOY_APP_UNDEPLOY, config, deploy -> { if (deploy.succeeded()) { LOG.info("执行暂停应用-->" + name + " 成功!"); response.end(ResultFormat.formatAsOne(HTTPStatusCodeMsgEnum.C200)); if (vertx.isClustered()) { vertx.eventBus().publish(VxApiEventBusAddressConstant.DEPLOY_APP_UNDEPLOY, config.copy().put("thisVertxName", thisVertxName)); LOG.info("广播集群环境中启动应用:" + name); } } else { response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C500)); LOG.error("执行暂停应用-->" + name + " 失败:" + deploy.cause()); } }); } }
Example #18
Source File: VertxDemoApp.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 6 votes |
@Override public void start() { LogService logsService = new MockLogService(); vertx.createHttpServer() .requestHandler(request -> { ReactiveReadStream<Buffer> rrs = ReactiveReadStream.readStream(); HttpServerResponse response = request.response(); Flowable<Buffer> logs = Flowable.fromPublisher(logsService.stream()) .map(Buffer::buffer) .doOnTerminate(response::end); logs.subscribe(rrs); response.setStatusCode(200); response.setChunked(true); response.putHeader("Content-Type", "text/plain"); response.putHeader("Connection", "keep-alive"); Pump.pump(rrs, response) .start(); }) .listen(8080); System.out.println("HTTP server started on port 8080"); }
Example #19
Source File: Terminus.java From sfs with Apache License 2.0 | 5 votes |
@Override public void onCompleted() { LOGGER.debug("Ended onComplete"); try { HttpServerResponse response = httpServerRequest.response(); response.end(); } finally { try { httpServerRequest.resume(); } catch (Throwable e) { // do nothing } } }
Example #20
Source File: HttpServerResponseImplInterceptor.java From skywalking with Apache License 2.0 | 5 votes |
@Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { if ((VertxContext.VERTX_VERSION < 36 && allArguments[0] instanceof ByteBuf) || ((VertxContext.VERTX_VERSION >= 36 && VertxContext.VERTX_VERSION <= 37) || allArguments.length == 2)) { VertxContext context = (VertxContext) objInst.getSkyWalkingDynamicField(); Tags.STATUS_CODE.set(context.getSpan(), Integer.toString(((HttpServerResponse) objInst).getStatusCode())); context.getSpan().asyncFinish(); } }
Example #21
Source File: AliPayApi.java From AlipayWechatPlatform with GNU General Public License v3.0 | 5 votes |
/** * 该方法对向支付宝发送请求唤醒授权页面进行了封装; * 方法先根据调用者传来的参数拼接好发送给支付宝服务器的Url; * 然后利用响应体的重定向方法发送请求; * * @param aliAccountInfo 封装了发送给支付宝数据的对象 * @param response http响应体 * Create by quandong */ public static void auth(AliAccountInfo aliAccountInfo, HttpServerResponse response, boolean needDetail) { String authReqUrl = null; // 将参数拼接到发送给支付宝的的链接上 try { authReqUrl = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + aliAccountInfo.getAppId() + "&scope=" + (needDetail?"auth_user,auth_base":"auth_base") + "&redirect_uri=" + URLEncoder.encode(aliAccountInfo.getRedirectUrl(), AlipayConstants.CHARSET_UTF8); } catch (UnsupportedEncodingException ignore) { } response.setStatusCode(302) .putHeader("Location", authReqUrl) // 通过响应体的重定向方法,向支付宝发送请求,页面上会弹出支付宝授权页面 .end(); }
Example #22
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void handlePlainText(HttpServerRequest request) { HttpServerResponse response = request.response(); MultiMap headers = response.headers(); for (int i = 0;i < plaintextHeaders.length; i+= 2) { headers.add(plaintextHeaders[i], plaintextHeaders[i + 1]); } response.end(HELLO_WORLD_BUFFER); }
Example #23
Source File: ExecuteRSString.java From vxms with Apache License 2.0 | 5 votes |
@Override protected void respond(String result, int statuscode) { final HttpServerResponse response = context.response(); if (!response.ended()) { ResponseExecution.updateHeaderAndStatuscode(headers, statuscode, response); if (result != null) { response.end(result); } else { response.end(); } } }
Example #24
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void handle(HttpServerRequest req) { HttpServerResponse resp = req.response(); final int queries = getQueries(req); for (int i = 0; i < queries; i++) { client.preparedQuery(SELECT_WORLD, Tuple.of(randomWorld()), ar -> { if (!failed) { if (ar.failed()) { failed = true; resp.setStatusCode(500).end(ar.cause().getMessage()); return; } // we need a final reference final Tuple row = ar.result().iterator().next(); worlds.add(new JsonObject().put("id", "" + row.getInteger(0)).put("randomNumber", "" + row.getInteger(1))); // stop condition if (worlds.size() == queries) { resp .putHeader(HttpHeaders.SERVER, SERVER) .putHeader(HttpHeaders.DATE, dateString) .putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_JSON) .end(worlds.encode()); } } }); } }
Example #25
Source File: AlipayOauthSubRouter.java From AlipayWechatPlatform with GNU General Public License v3.0 | 5 votes |
/** * 解析授权前访问的地址,解析所需的json并编码,最后重定向 * * @param req HTTP请求对象 * @param resp HTTP响应对象 * @param res ALipay接口返回的响应 * @param callback 解析地址后的处理方法 * @author Leibniz.Hu */ private void oauthSuccessProcess(HttpServerRequest req, HttpServerResponse resp, AlipayResponse res, Handler<String> callback) { if (res != null) { String visitUrl = req.getParam("visitUrl");//getRedirectAddress(request, REMOVE_PARAMS); if (visitUrl.length() > 0) { visitUrl = TuringBase64Util.decode(visitUrl).replaceAll("[\\s*\t\n\r]", ""); callback.handle(visitUrl); resp.setStatusCode(302).putHeader("Location", visitUrl + (visitUrl.contains("?") ? "&rs=" : "?rs=") + TuringBase64Util.encode(getClearJson(res).toString())).end(); } else { log.error("没有找到授权后回调地址" + req.absoluteURI()); resp.end("未设置授权后回调地址"); } } }
Example #26
Source File: HonoBasicAuthHandlerTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Verifies that the handler returns the status code conveyed in a * failed {@code AuthProvider} invocation in the response. */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testHandleFailsWithStatusCodeFromAuthProvider() { // GIVEN an auth handler configured with an auth provider that // fails with a 503 error code during authentication final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE); doAnswer(invocation -> { final Handler handler = invocation.getArgument(1); handler.handle(Future.failedFuture(error)); return null; }).when(authProvider).authenticate(any(JsonObject.class), any(Handler.class)); // WHEN trying to authenticate a request using the HTTP BASIC scheme final String authorization = new StringBuffer() .append("BASIC ") .append(Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8))) .toString(); final MultiMap headers = mock(MultiMap.class); when(headers.get(eq(HttpHeaders.AUTHORIZATION))).thenReturn(authorization); final HttpServerRequest req = mock(HttpServerRequest.class); when(req.headers()).thenReturn(headers); final HttpServerResponse resp = mock(HttpServerResponse.class); final RoutingContext ctx = mock(RoutingContext.class); when(ctx.request()).thenReturn(req); when(ctx.response()).thenReturn(resp); authHandler.handle(ctx); // THEN the request context is failed with the 503 error code verify(ctx).fail(error); }
Example #27
Source File: WriteReadStreamBlobAsHttpResponseHeaders.java From sfs with Apache License 2.0 | 5 votes |
@Override public Holder2<SfsRequest, Optional<A>> call(Holder2<SfsRequest, Optional<A>> input) { HttpServerResponse httpServerResponse = input.value0().response(); Optional<A> oBlob = input.value1(); if (oBlob.isPresent()) { A blob = oBlob.get(); long offset = blob.getOffset(); httpServerResponse .putHeader(X_CONTENT_OFFSET, valueOf(offset)); } return input; }
Example #28
Source File: VertxServerHttpResponse.java From vertx-spring-boot with Apache License 2.0 | 5 votes |
@Override protected Mono<Void> writeWithInternal(Publisher<? extends DataBuffer> chunks) { return Mono.create(sink -> { logger.debug("Subscribing to body publisher"); Subscriber<DataBuffer> subscriber = new WriteStreamSubscriber.Builder<HttpServerResponse, DataBuffer>() .writeStream(delegate) .endHook(sink) .nextHandler((stream, value) -> stream.write(bufferConverter.toBuffer(value))) .build(); chunks.subscribe(subscriber); }); }
Example #29
Source File: TestContextRest.java From rest.vertx with Apache License 2.0 | 5 votes |
@GET @Path("/login") public HttpServerResponse login(@Context HttpServerResponse response) { response.setStatusCode(201); response.putHeader("X-SessionId", "session"); response.end("Hello world!"); return response; }
Example #30
Source File: AccessibleHandler.java From dfx with Apache License 2.0 | 5 votes |
private void processRequestBody(HttpServerResponse response, JsonObject body) { try { logger.debug("RequestURL is {} , RequestParams are {}", this.url, body); Utils.withCircuitBreaker(vertx, circuitBreaker, accessible, body.getMap() , result -> Utils.fireJsonResponse(response, 200, result) , throwable -> Utils.fireSingleMessageResponse(response, 500, throwable.getMessage())); } catch (Exception e) { logger.error("Caught an exception: {}", e); Utils.fireSingleMessageResponse(response, 500, e.getMessage()); } }