private void genBodyBuffer() throws Exception { if (bodyBuffer != null) { return; } if (formMap == null) { return; } request.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); try (BufferOutputStream output = new BufferOutputStream()) { for (Entry<String, Object> entry : formMap.entrySet()) { output.write(entry.getKey().getBytes(StandardCharsets.UTF_8)); output.write('='); if (entry.getValue() != null) { String value = RestObjectMapper.INSTANCE.convertToString(entry.getValue()); value = URLEncoder.encode(value, StandardCharsets.UTF_8.name()); output.write(value.getBytes(StandardCharsets.UTF_8)); } output.write('&'); } bodyBuffer = output.getBuffer(); } }
@Override public void end(Buffer chunk) { checkWritten(); if (!chunked && !contentLengthSet()) { headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(chunk.length())); } body().appendBuffer(chunk); if (!headWritten) { prepareHeaders(); } outputResponse(); closed = true; written = true; if (bodyEndHandler != null) { bodyEndHandler.handle(null); } if (endHandler != null) { endHandler.handle(null); } }
default void addResponseHeaders(RouteDefinition definition, HttpServerResponse response) { if (!response.ended() && !response.headers().contains(HttpHeaders.CONTENT_TYPE)) { if (definition != null && definition.getProduces() != null) { for (MediaType produces : definition.getProduces()) { response.putHeader(HttpHeaders.CONTENT_TYPE, MediaTypeHelper.toString(produces)); } } else { response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD); } } }
@Override public void handle(final RoutingContext context) { if (LOG.isErrorEnabled()) { LOG.error("Unhandled server exception statusCode={} responseEnded={} uri={}", context.statusCode(), context.response().ended(), context.request().uri(), context.failure()); } if (!context.response().ended()) { if (context.failure() instanceof ConnectException) { context.response().setStatusCode(504) .setStatusMessage(GATEWAY_TIMEOUT) .putHeader(CONTENT_TYPE, MediaTypes.APPLICATION_JSON) .end(Errors.serverError(GATEWAY_TIMEOUT).toBuffer()); } else if (context.failure() instanceof UnknownHostException) { context.response().setStatusCode(503) .setStatusMessage(GATEWAY_ERROR) .putHeader(CONTENT_TYPE, MediaTypes.APPLICATION_JSON) .end(Errors.serverError(GATEWAY_ERROR).toBuffer()); } else { context.response().setStatusCode(context.statusCode() == -1 ? 500 : context.statusCode()) .setStatusMessage(INTERNAL_SERVER_ERROR) .putHeader(HttpHeaders.CONTENT_TYPE, MediaTypes.APPLICATION_JSON) .end(Errors.serverError(INTERNAL_SERVER_ERROR).toBuffer()); } } }
public static void reply( final RoutingContext context, final Envelop envelop) { // 1. Get response reference final HttpServerResponse response = context.response(); // 2. Set response status final HttpStatusCode code = envelop.status(); response.setStatusCode(code.code()); response.setStatusMessage(code.message()); response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); // 3. Response process if (!response.ended()) { response.end(envelop.response()); } response.close(); }
@Test public void callback_path_responds_with_302_when_no_auth_code_param_is_present(final TestContext ctx) { final Async async = ctx.async(); vertx.createHttpClient().get(PORT, HOST, "/oauth/callback", res -> { assertEquals(302, res.statusCode()); final URL redirectUrl = buildUrl(res.headers().get(HttpHeaders.LOCATION)); assertEquals("accounts.google.com", redirectUrl.getHost()); final Map<String, String> params = parseQuery(redirectUrl); assertEquals("offline", params.get("access_type")); assertEquals("force", params.get("approval_prompt")); assertEquals(System.getenv("CLIENT_ID"), params.get("client_id")); assertEquals(System.getenv("REDIRECT_URL"), params.get("redirect_uri")); assertEquals("code", params.get("response_type")); async.complete(); }).putHeader(HttpHeaders.USER_AGENT, "SomeUserAgent/1.0").end(); }
public static void ask( HttpServerResponse httpServerResponse, String conversationToken, String initialPrompt, String[] noInputPrompts) { httpServerResponse.putHeader( HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8"); httpServerResponse.putHeader("Google-Assistant-API-Version", "v1"); JsonObject responseJSON = new JsonObject(); if (conversationToken != null) { responseJSON.put("conversation_token", conversationToken); } responseJSON.put("expect_user_response", true); responseJSON.put( "expected_inputs", JsonUtil.getArray( _getExpectedInputJSON(initialPrompt, noInputPrompts))); httpServerResponse.end(responseJSON.encode()); }
@Override public JsonObject apply(RoutingContext context) throws Throwable { if (context.request().method() == HttpMethod.GET) { throw new RequestConvertersionException("Invalid HttpRequestMethod 'GET'"); } checkContentType(context.request().headers().get(HttpHeaders.CONTENT_TYPE)); final JsonObject jsonObject = context.getBodyAsJson(); checkJsonObject(jsonObject); return new JsonObject( ImmutableMap.<String, Object>builder() .putAll(jsonObject.getMap()) .putAll(pathParams(context.pathParams(), jsonObject)) .build() ); }
@Override public void handle(RoutingContext rc) { HttpServerResponse response = rc.response(); response .setChunked(true) .putHeader(HttpHeaders.CONTENT_TYPE, "text/event-stream") .putHeader(HttpHeaders.CACHE_CONTROL, "no-cache") .putHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE); rc.request().connection() .closeHandler(v -> { connections.remove(response); endQuietly(response); }) .exceptionHandler(t -> { connections.remove(response); rc.fail(t); }); connections.add(response); }
private KnotContext createSuccessResponse(KnotContext inputContext, String renderedContent) { ClientResponse clientResponse = inputContext.getClientResponse(); if (StringUtils.isBlank(renderedContent)) { clientResponse.setStatusCode(HttpResponseStatus.NO_CONTENT.code()); } else { MultiMap headers = clientResponse.getHeaders(); headers.add(HttpHeaders.CONTENT_LENGTH.toString().toLowerCase(), Integer.toString(renderedContent.length())); clientResponse.setBody(Buffer.buffer(renderedContent)).setHeaders(headers); clientResponse.setStatusCode(HttpResponseStatus.OK.code()); } return new KnotContext() .setClientRequest(inputContext.getClientRequest()) .setClientResponse(clientResponse); }
@Test public void testOkAddBodyRequiredWithXML(TestContext context) { Async async = context.async(); String bodyReqXml = "<BodyType><id>1</id><name>body 1</name></BodyType>"; HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/body/required"); req.handler(response -> { context.assertEquals(response.statusCode(), 200); response.bodyHandler(body -> { context.assertEquals(bodyReqXml, body.toString()); async.complete(); }); }) .putHeader(HttpHeaders.CONTENT_TYPE, "application/xml") .end(bodyReqXml); }
@Test public void testOkAddArrayBodyWithXML(TestContext context) { Async async = context.async(); String bodyReqXml = "<BodyType><id>1</id><name>body 1</name></BodyType><BodyType><id>2</id><name>body 2</name></BodyType>"; HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/body/array"); req.handler(response -> { context.assertEquals(response.statusCode(), 200); response.bodyHandler(body -> { context.assertEquals(bodyReqXml, body.toString()); async.complete(); }); }) .putHeader(HttpHeaders.CONTENT_TYPE, "application/xml") .end(bodyReqXml); }
@Test() public void testOkFormDataSimpleRequired(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("toto", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("formDataRequired=").append(esc.escape("toto")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataSimpleRequiredAllowEmpty(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required/allowempty"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("formDataRequired="); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataSimpleNotRequiredWithParam(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/not/required"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("toto", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("formDataNotRequired=").append(esc.escape("toto")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataArrayPipes(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/pipes"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1|2|3")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataArrayCsv(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/csv"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1,2,3")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataArraySsv(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/ssv"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1 2 3")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataArrayTsv(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/tsv"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1\t2\t3")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkQueryArrayMulti(TestContext context) throws UnsupportedEncodingException { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/multi?array_formdata=1&array_formdata=2&array_formdata=3"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1")).append("&array_formdata=").append(esc.escape("2")).append("&array_formdata=") .append(esc.escape("3")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testOkFormDataArray(TestContext context) throws UnsupportedEncodingException { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString()); async.complete(); }); }); // Construct form StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1,2,3")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); }
@Test() public void testKoFormDataSimpleFileWithoutFile(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/file"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 400); async.complete(); }); }); // Construct multipart data req.putHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=MyBoundary"); req.end(); }
@Test public void testCORS(TestContext context) { JsonObject config = TestConfig.getApiConfig(); config.getJsonObject("cors").put("enable", true).put("origin", "https://localhost:8888"); deployApiVerticle(context, config); final Async asyncClient = context.async(); String myOrigin = "https://localhost:8888"; HttpClientOptions sslOpts = new HttpClientOptions().setSsl(true) .setPemTrustOptions(TestConfig.HTTP_API_CERTIFICATE.trustOptions()); vertx.createHttpClient(sslOpts).get(port, "localhost", "/api/v1.0/pr/latest", res -> { context.assertEquals(200, res.statusCode()); context.assertEquals(myOrigin, res.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); asyncClient.complete(); }).putHeader(HttpHeaders.ORIGIN, myOrigin).end(); }
/** * Verifies that a device can be properly registered. * * @param ctx The vert.x test context */ @Test public void testAddDeviceSucceeds(final TestContext ctx) { final String requestBody = new JsonObject() .put(RequestResponseApiConstants.FIELD_DEVICE_ID, DEVICE_ID) .put("test", "test") .encode(); final Async async = ctx.async(); vertx.createHttpClient() .post(getPort(), HOST, REGISTRATION_URI) .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON) .handler(response -> { ctx.assertEquals(HttpURLConnection.HTTP_CREATED, response.statusCode()); response.bodyHandler(totalBuffer -> { ctx.assertTrue(totalBuffer.length() == 0); async.complete(); }); }).exceptionHandler(ctx::fail) .end(requestBody); }
/** * Verifies that a device cannot be registered if the request body * does not contain a device identifier. * * @param ctx The vert.x test context */ @Test public void testAddDeviceFailsWithoutDeviceId(final TestContext ctx) { final String requestBody = new JsonObject().put("test", "test").encode(); final Async async = ctx.async(); vertx.createHttpClient() .post(getPort(), HOST, REGISTRATION_URI) .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON) .handler(response -> { ctx.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.statusCode()); async.complete(); }).exceptionHandler(ctx::fail) .end(requestBody); }
private Future<Void> registerDevice(final String deviceId, final JsonObject data) { final JsonObject requestJson = data.copy(); requestJson.put(RegistrationConstants.FIELD_DEVICE_ID, deviceId); final Future<Void> result = Future.future(); vertx.createHttpClient() .post(getPort(), HOST, REGISTRATION_URI) .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON) .handler(response -> { if (response.statusCode() == HttpURLConnection.HTTP_CREATED) { result.complete(); } else { result.fail(new ServiceInvocationException(response.statusCode(), "device registration failed: " + response.statusCode())); } }).exceptionHandler(result::fail) .end(requestJson.encode()); return result; }
private Future<Void> updateDevice(final String deviceId, final JsonObject data) { final String requestUri = String.format("/%s/%s/%s", RegistrationConstants.REGISTRATION_ENDPOINT, TENANT, deviceId); final JsonObject requestJson = data.copy(); requestJson.put(RegistrationConstants.FIELD_DEVICE_ID, deviceId); final Future<Void> result = Future.future(); vertx.createHttpClient() .put(getPort(), HOST, requestUri) .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON) .handler(response -> { if (response.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) { result.complete(); } else { result.fail(new ServiceInvocationException(response.statusCode(), "device update failed: " + response.statusCode())); } }).exceptionHandler(result::fail) .end(requestJson.encode()); return result; }
private static Future<HttpClientResponse> addCredentials(final JsonObject requestPayload, final String contentType, final int expectedStatusCode) { final Future<HttpClientResponse> result = Future.future(); final HttpClientRequest req = vertx.createHttpClient().post(getPort(), HOST, URI_ADD_CREDENTIALS) .putHeader(HttpHeaders.CONTENT_TYPE, contentType) .handler(response -> { if (response.statusCode() == expectedStatusCode) { result.complete(response); } else { result.fail("add credentials failed, expected status code " + expectedStatusCode + " but got " + response.statusCode()); } }).exceptionHandler(result::fail); if (requestPayload == null) { req.end(); } else { req.end(requestPayload.encodePrettily()); } return result; }
private static final Future<HttpClientResponse> updateCredentials(final String authId, final String type, final JsonObject requestPayload, final int expectedResult) { final Future<HttpClientResponse> result = Future.future(); final String uri = String.format(TEMPLATE_URI_CREDENTIALS_INSTANCE, authId, type); final HttpClientRequest req = vertx.createHttpClient().put(getPort(), HOST, uri) .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON) .handler(response -> { if (response.statusCode() == expectedResult) { result.complete(response); } else { result.fail("update credentials failed, expected status code " + expectedResult + " but got " + response.statusCode()); } }) .exceptionHandler(result::fail); if (requestPayload == null) { req.end(); } else { req.end(requestPayload.encodePrettily()); } return result; }
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; }
private void doGetDevice(final RoutingContext ctx) { final String deviceId = getDeviceIdParam(ctx); final String tenantId = getTenantParam(ctx); final HttpServerResponse response = ctx.response(); final JsonObject requestMsg = RegistrationConstants.getServiceRequestAsJson(RegistrationConstants.ACTION_GET, tenantId, deviceId); doRegistrationAction(ctx, requestMsg, (status, registrationResult) -> { response.setStatusCode(status); switch (status) { case HttpURLConnection.HTTP_OK: final String msg = registrationResult.getJsonObject(RegistrationConstants.FIELD_PAYLOAD).encodePrettily(); response .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON_UFT8) .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(msg.length())) .write(msg); default: response.end(); } }); }
@Test public void testLocationHeader() { String name = "someUser"; UserCreateRequest request = new UserCreateRequest(); request.setUsername(name); request.setPassword("bla"); MeshResponse<UserResponse> response = client().createUser(request).invoke(); latchFor(response); assertSuccess(response); try (Tx tx = tx()) { User user = meshRoot().getUserRoot().findByUsername(name); assertNotNull("User should have been created.", user); assertEquals(CREATED.code(), response.getRawResponse().statusCode()); String location = response.getRawResponse().getHeader(HttpHeaders.LOCATION); assertEquals("Location header value did not match", "http://localhost:" + port() + "/api/v1/users/" + user.getUuid(), location); } }
@Test public void testLocationWithHostHeader() { String name = "someUser"; UserCreateRequest userRequest = new UserCreateRequest(); userRequest.setUsername(name); userRequest.setPassword("bla"); MeshRequest<UserResponse> request = client().createUser(userRequest); request.getRequest().putHeader(HttpHeaders.HOST, "jotschi.de:" + port()); MeshResponse<UserResponse> response = request.invoke(); latchFor(response); assertSuccess(response); try (Tx tx = tx()) { User user = meshRoot().getUserRoot().findByUsername(name); assertNotNull("User should have been created.", user); assertEquals(CREATED.code(), response.getRawResponse().statusCode()); String location = response.getRawResponse().getHeader(HttpHeaders.LOCATION); assertEquals("Location header value did not match", "http://jotschi.de:" + port() + "/api/v1/users/" + user.getUuid(), location); } }
/** * get address space by address space name vie rest api * * @param name name of address space * @return * @throws InterruptedException */ public JsonObject getAddressSpace(String name) throws Exception { CompletableFuture<JsonObject> responsePromise = new CompletableFuture<>(); return doRequestNTimes(initRetry, () -> { client.get(endpoint.getPort(), endpoint.getHost(), addressSpacesPath + "/" + name) .as(BodyCodec.jsonObject()) .putHeader(HttpHeaders.AUTHORIZATION.toString(), authzString) .send(ar -> { if (ar.succeeded()) { responsePromise.complete(responseHandler(ar)); } else { Logging.log.warn("Error when getting address space {}", name); responsePromise.completeExceptionally(ar.cause()); } }); return responsePromise.get(30, TimeUnit.SECONDS); }); }
@Override public void execute() { final HttpClientRequest httpClientRequest = httpClient.request(method, uriEncoder.toString()); httpClientRequest.handler(new AuthHttpHandler(this, responseHandler)); httpClientRequest.putHeader(HttpHeaders.ACCEPT, Format.JSON.getDefaultMimetype()); if (authorization == null && AuthScheme.Type.BASIC == realm.getSchemeType()) { authorize(uri, AuthSchemeFactory.newScheme(realm)); } if (authorization != null) { httpClientRequest.putHeader(HttpHeaders.AUTHORIZATION, authorization); } if (body != null) { httpClientRequest.putHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(contentLength)) .putHeader(HttpHeaders.CONTENT_TYPE, contentType) .write(body); } httpClientRequest.exceptionHandler(exception -> { responseHandler.handle(new ErrorResponse(exception)); }).end(); }
@Test public void testConfigurationOptions(TestContext testContext) throws Exception { final HttpClientOptions options = new HttpClientOptions().setTryUseCompression(false); final HttpClient httpClient = runTestOnContext.vertx().createHttpClient(options); final Async asyncOp = testContext.async(); // issue a request on the custom server bind address and port, testing for compression httpClient.get(SERVER_PORT, SERVER_BIND_ADDRESS, "/hystrix-dashboard/") .setChunked(false) .putHeader(HttpHeaders.ACCEPT_ENCODING, HttpHeaders.DEFLATE_GZIP) .handler(resp -> { testContext.assertEquals(200, resp.statusCode(), "Should have fetched the index page with status 200"); testContext.assertEquals("gzip", resp.getHeader(HttpHeaders.CONTENT_ENCODING)); }) .exceptionHandler(testContext::fail) .endHandler(event -> asyncOp.complete()) .end(); }
BHandler(RoutingContext context) { this.context = context; Set<FileUpload> fileUploads = context.fileUploads(); final String contentType = context.request().getHeader(HttpHeaders.CONTENT_TYPE); if (contentType == null) { isMultipart = false; isUrlEncoded = false; } else { final String lowerCaseContentType = contentType.toLowerCase(); isMultipart = lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()); isUrlEncoded = lowerCaseContentType.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString()); } if (isMultipart || isUrlEncoded) { makeUploadDir(context.vertx().fileSystem()); context.request().setExpectMultipart(true); context.request().uploadHandler(upload -> { // *** cse begin *** if (uploadsDir == null) { failed = true; CommonExceptionData data = new CommonExceptionData("not support file upload."); throw new ErrorDataDecoderException(ExceptionFactory.createConsumerException(data)); } // *** cse end *** // we actually upload to a file with a generated filename uploadCount.incrementAndGet(); String uploadedFileName = new File(uploadsDir, UUID.randomUUID().toString()).getPath(); upload.streamToFileSystem(uploadedFileName); FileUploadImpl fileUpload = new FileUploadImpl(uploadedFileName, upload); fileUploads.add(fileUpload); upload.exceptionHandler(context::fail); upload.endHandler(v -> uploadEnded()); }); } context.request().exceptionHandler(context::fail); }
private void writeCookies() { if (cookieMap == null) { return; } StringBuilder builder = new StringBuilder(); for (Entry<String, String> entry : cookieMap.entrySet()) { builder.append(entry.getKey()) .append('=') .append(entry.getValue()) .append("; "); } request.putHeader(HttpHeaders.COOKIE, builder.toString()); }
@Override public void write(T result, HttpServerRequest request, HttpServerResponse response) { String mediaType = response.headers().get(HttpHeaders.CONTENT_TYPE); HttpResponseWriter writer; try { writer = RestRouter.getWriters().get(mediaType); } catch (ClassFactoryException e) { // writer = RestRouter.getWriters().get(result); writer = null; } if (writer != null && !(writer instanceof GenericResponseWriter)) { writer.write(result, request, response); } else { log.warn("No writer associated with: '" + mediaType + "', defaulting to toString() as output!"); if (result != null) { response.end(result.toString()); } else { response.end(); } } }
@Override public void write(Response result, HttpServerRequest request, HttpServerResponse response) { Assert.notNull(result, "Expected result but got null!"); response.setStatusCode(result.getStatus()); addHeaders(result, response); if (result.getEntity() != null) { // try to find appropriate writer ... String mediaType = response.headers().get(HttpHeaders.CONTENT_TYPE); HttpResponseWriter writer; try { writer = RestRouter.getWriters().get(mediaType); } catch (ClassFactoryException e) { writer = null; } if (writer != null) { writer.write(result.getEntity(), request, response); } else { response.end(result.getEntity().toString()); } } else { response.end(); } }