Java 类io.vertx.core.http.HttpHeaders 实例源码

项目:incubator-servicecomb-java-chassis    文件:RestClientRequestImpl.java   
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();
  }
}
项目:vertx-aws-lambda    文件:HttpServerResponseImpl.java   
@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);
    }
}
项目:rest.vertx    文件:HttpResponseWriter.java   
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);
            }
        }
    }
项目:app-ms    文件:GlobalFailureHandler.java   
@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());
        }
    }

}
项目:vertx-zero    文件:Answer.java   
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();
}
项目:nexus-proxy    文件:CloudIamAuthNexusProxyVerticleTests.java   
@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();
}
项目:actions-on-google-vertx-sample    文件:ConversationUtil.java   
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());
}
项目:Elastic-Components    文件:JsonObjectRequestConverterImpl.java   
@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()
    );
}
项目:vertx-circuit-breaker    文件:HystrixMetricEventStream.java   
@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);
}
项目:knotx    文件:FragmentAssemblerKnotProxyImpl.java   
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);
}
项目:vertx-swagger    文件:BodyParameterExtractorTest.java   
@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);
}
项目:vertx-swagger    文件:BodyParameterExtractorTest.java   
@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);
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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();
}
项目:DAVe    文件:ApiVerticleTest.java   
@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();
}
项目:hono    文件:RegistrationRestServerTest.java   
/**
 * 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);
}
项目:hono    文件:RegistrationRestServerTest.java   
/**
 * 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);
}
项目:hono    文件:RegistrationRestServerTest.java   
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;
    }
项目:hono    文件:RegistrationRestServerTest.java   
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;
    }
项目:hono    文件:CredentialsRestServerTest.java   
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;
    }
项目:hono    文件:CredentialsRestServerTest.java   
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;
    }
项目:hono    文件:HonoAuthHandlerImpl.java   
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;
}
项目:hono    文件:RegistrationHttpEndpoint.java   
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();
                }
        });
    }
项目:mesh    文件:UserEndpointTest.java   
@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);
    }
}
项目:mesh    文件:UserEndpointTest.java   
@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);
    }
}
项目:enmasse    文件:AddressApiClient.java   
/**
 * 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);
    });
}
项目:vertx-marklogic    文件:DefaultMarklogicRequest.java   
@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();
}
项目:standalone-hystrix-dashboard    文件:HystrixDashboardConfigurationTest.java   
@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();
}
项目:incubator-servicecomb-java-chassis    文件:RestBodyHandler.java   
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);
}
项目:incubator-servicecomb-java-chassis    文件:RestClientRequestImpl.java   
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());
}
项目:rest.vertx    文件:GenericResponseWriter.java   
@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();
        }
    }
}
项目:rest.vertx    文件:JaxResponseWriter.java   
@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();
    }
}