下面列出了怎么用 io.netty.handler.codec.http.HttpHeaderNames 的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Verifies either the expected request headers are found or not found (based on the parameter passed) in the
* public access log entry
* @param logEntry the public access log entry
* @param headers expected headers
* @param httpMethod HttpMethod type
* @param expected, true if the headers are expected, false otherwise
*/
private void verifyPublicAccessLogEntryForRequestHeaders(String logEntry, HttpHeaders headers, HttpMethod httpMethod,
boolean expected) {
Iterator<Map.Entry<String, String>> itr = headers.iteratorAsString();
while (itr.hasNext()) {
Map.Entry<String, String> entry = itr.next();
if (!entry.getKey().startsWith(NOT_LOGGED_HEADER_KEY) && !entry.getKey()
.startsWith(EchoMethodHandler.RESPONSE_HEADER_KEY_PREFIX)) {
if (httpMethod == HttpMethod.GET && !entry.getKey().equalsIgnoreCase(HttpHeaderNames.CONTENT_TYPE.toString())) {
String subString = "[" + entry.getKey() + "=" + entry.getValue() + "]";
boolean actual = logEntry.contains(subString);
if (expected) {
Assert.assertTrue("Public Access log entry does not have expected header " + entry.getKey(), actual);
} else {
Assert.assertFalse("Public Access log entry has unexpected header " + entry.getKey(), actual);
}
}
}
}
}
@Test(description = "test throttling with non exist subscription policy")
public void testThrottlingWithNonExistSubscriptionPolicy() throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + noSubPolicyJWT);
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
Assert.assertNotNull(response);
Assert.assertEquals(response.getResponseCode(), 500, "Request should not successful with JWT.");
Assert.assertTrue(response.getData().contains("\"code\":900809"),
"Error response should have errorcode 900809 in JWT.");
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + noSubPolicyToken);
response = HttpClientRequest.doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
Assert.assertNotNull(response);
Assert.assertEquals(response.getResponseCode(), 500, "Request should not successful with oauth.");
Assert.assertTrue(response.getData().contains("\"code\":900809"),
"Error response should have errorcode 900809 in oauth.");
}
@Test(description = "Test JWT Generator token cache and the properties")
public void testResponseJWTGenerationToken() throws Exception {
Map<String, String> headers = new HashMap<>();
//test endpoint with token
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("petstore/v2/jwttoken"), headers);
Assert.assertNotNull(response);
Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatched");
JSONObject responseJSON = new JSONObject(response.getData());
String tokenFull = responseJSON.get("token").toString();
String strTokenBody = tokenFull.split("\\.")[1];
String decodedTokenBody = new String(Base64.getUrlDecoder().decode(strTokenBody));
JSONObject tokenBody = new JSONObject(decodedTokenBody);
Assert.assertEquals(tokenBody.get("iss"), JWT_GENERATOR_ISSUER,
"JWT generator issuer not set correctly");
Assert.assertEquals(tokenBody.get("aud"), JWT_GENERATOR_AUDIENCE,
"JWT generator audience not set correctly");
Assert.assertTrue(tokenBody.keySet().contains("claim1"), "JWT generator custom claims not set correctly");
Assert.assertFalse(tokenBody.keySet().contains("claim2"), "JWT generator restricted claims not removed");
}
private void testPredictionsNoManifest(Channel inferChannel, Channel mgmtChannel)
throws InterruptedException, NoSuchFieldException, IllegalAccessException {
setConfiguration("default_service_handler", "service:handle");
loadTests(mgmtChannel, "noop-no-manifest", "nomanifest");
result = null;
latch = new CountDownLatch(1);
DefaultFullHttpRequest req =
new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/nomanifest");
req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
HttpUtil.setContentLength(req, req.content().readableBytes());
req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
inferChannel.writeAndFlush(req);
latch.await();
Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
Assert.assertEquals(result, "OK");
unloadTests(mgmtChannel, "nomanifest");
}
@Test
public void disableChunkForced() {
AtomicReference<HttpHeaders> headers = new AtomicReference<>();
Tuple2<HttpResponseStatus, String> r =
HttpClient.newConnection()
.host("localhost")
.port(getPort())
.headers(h -> h.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED))
.wiretap(true)
.doAfterRequest((req, connection) -> headers.set(req.requestHeaders()))
.request(HttpMethod.GET)
.uri("/status/400")
.send(ByteBufFlux.fromString(Flux.just("hello")))
.responseSingle((res, conn) -> Mono.just(res.status())
.zipWith(conn.asString()))
.block(Duration.ofSeconds(30));
assertThat(r).isNotNull();
assertThat(r.getT1()).isEqualTo(HttpResponseStatus.BAD_REQUEST);
assertThat(headers.get().get("Content-Length")).isEqualTo("5");
assertThat(headers.get().get("Transfer-Encoding")).isNull();
}
WebsocketClientOperations(URI currentURI,
WebsocketClientSpec websocketClientSpec,
HttpClientOperations replaced) {
super(replaced);
this.proxyPing = websocketClientSpec.handlePing();
Channel channel = channel();
onCloseState = MonoProcessor.create();
String subprotocols = websocketClientSpec.protocols();
handshaker = WebSocketClientHandshakerFactory.newHandshaker(currentURI,
WebSocketVersion.V13,
subprotocols != null && !subprotocols.isEmpty() ? subprotocols : null,
true,
replaced.requestHeaders()
.remove(HttpHeaderNames.HOST),
websocketClientSpec.maxFramePayloadLength());
handshaker.handshake(channel)
.addListener(f -> {
markPersistent(false);
channel.read();
});
}
private void uploadsShouldWork(boolean casUpload, EmbeddedChannel ch, HttpResponseStatus status)
throws Exception {
ByteArrayInputStream data = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5});
ChannelPromise writePromise = ch.newPromise();
ch.writeOneOutbound(new UploadCommand(CACHE_URI, casUpload, "abcdef", data, 5), writePromise);
HttpRequest request = ch.readOutbound();
assertThat(request.method()).isEqualTo(HttpMethod.PUT);
assertThat(request.headers().get(HttpHeaders.CONNECTION))
.isEqualTo(HttpHeaderValues.KEEP_ALIVE.toString());
HttpChunkedInput content = ch.readOutbound();
assertThat(content.readChunk(ByteBufAllocator.DEFAULT).content().readableBytes()).isEqualTo(5);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ch.writeInbound(response);
assertThat(writePromise.isDone()).isTrue();
assertThat(ch.isOpen()).isTrue();
}
@Test
public void testShouldFetchDataWithHeaders(TestContext testContext) throws Exception {
final String fakeEurekaServerUrl = "http://localhost:" + FAKE_EUREKA_SERVER_PORT + "/eureka/v2/apps";
final String dashboardProxyUrl = DASHBOARD_EUREKA_PROXY_URL + fakeEurekaServerUrl;
final Async fetchData = testContext.async();
httpClient.getNow(dashboardProxyUrl, resp -> resp.bodyHandler(buffer -> {
final String responseData = buffer.toString(StandardCharsets.UTF_8);
if (resp.statusCode() != 200) {
testContext.fail("Response Status => " + resp.statusCode() + "\nResponse: " + responseData);
} else {
testContext.assertTrue("application/xml".equals(resp.getHeader(HttpHeaderNames.CONTENT_TYPE)));
testContext.assertTrue(responseData.contains("<apps__hashcode>UP_2_</apps__hashcode>"));
testContext.assertTrue(responseData.contains("<registrationTimestamp>1472352522224</registrationTimestamp>"));
fetchData.complete();
}
}));
fetchData.awaitSuccess(5000L);
}
@Override
protected boolean isContentAlwaysEmpty(HttpResponse msg) {
// Correctly handle special cases as stated in:
// https://tools.ietf.org/html/rfc7230#section-3.3.3
HttpResponseStatus status = msg.status();
if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {
if (status.code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
// We need special handling for WebSockets version 00 as it will include an body.
// Fortunally this version should not really be used in the wild very often.
// See https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-1.2
return msg.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
}
return true;
}
return status.code() == HttpResponseStatus.NO_CONTENT.code()
|| status.code() == HttpResponseStatus.NOT_MODIFIED.code()
|| status.code() == HttpResponseStatus.RESET_CONTENT.code();
}
@Test
public void testUserAgent() {
disposableServer =
HttpServer.create()
.port(0)
.handle((req, resp) -> {
Assert.assertTrue("" + req.requestHeaders()
.get(HttpHeaderNames.USER_AGENT),
req.requestHeaders()
.contains(HttpHeaderNames.USER_AGENT) &&
req.requestHeaders()
.get(HttpHeaderNames.USER_AGENT)
.equals(HttpClient.USER_AGENT));
return req.receive().then();
})
.wiretap(true)
.bindNow();
createHttpClientForContextWithPort()
.get()
.uri("/")
.responseContent()
.blockLast();
}
@Test
public void handledAdded_writesRequest() {
Promise<Channel> promise = GROUP.next().newPromise();
ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
handler.handlerAdded(mockCtx);
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(mockChannel).writeAndFlush(requestCaptor.capture());
String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort();
HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri,
Unpooled.EMPTY_BUFFER, false);
expectedRequest.headers().add(HttpHeaderNames.HOST, uri);
assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest);
}
private void writeResourceReport(Channel channel) {
ByteBuf content = Unpooled.buffer();
Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8);
try {
reportAdapter.toJson(resourceReport.get(), writer);
writer.close();
} catch (IOException e) {
LOG.error("error writing resource report", e);
writeAndClose(channel, new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8)));
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
HttpUtil.setContentLength(response, content.readableBytes());
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
channel.writeAndFlush(response);
}
private void testPredictions(String modelName, String expectedOutput, String version)
throws InterruptedException {
Channel channel = TestUtils.getInferenceChannel(configManager);
TestUtils.setResult(null);
TestUtils.setLatch(new CountDownLatch(1));
String requestURL = "/predictions/" + modelName;
if (version != null) {
requestURL += "/" + version;
}
DefaultFullHttpRequest req =
new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestURL);
req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
HttpUtil.setContentLength(req, req.content().readableBytes());
req.headers()
.set(
HttpHeaderNames.CONTENT_TYPE,
HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
channel.writeAndFlush(req);
TestUtils.getLatch().await();
Assert.assertEquals(TestUtils.getResult(), expectedOutput);
}
private void testPredictions(Channel channel) throws InterruptedException {
result = null;
latch = new CountDownLatch(1);
DefaultFullHttpRequest req =
new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");
req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
HttpUtil.setContentLength(req, req.content().readableBytes());
req.headers()
.set(
HttpHeaderNames.CONTENT_TYPE,
HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
channel.writeAndFlush(req);
latch.await();
Assert.assertEquals(result, "OK");
}
public static FullHttpResponse buildResponse(BidResponse bidResponse) {
String respJson = JSON.toJSONString(bidResponse, jsonSnakeConfig);
// byte[] buf = JSON.toJSONBytes(bidResponse, jsonSnakeConfig);
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(respJson.getBytes())
);
response.headers().set(
HttpHeaderNames.CONTENT_TYPE.toString(),
"application/json;charset=utf8"
);
log.info("gae_response\t{}", respJson);
return response;
}
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress raddr = destinationAddress();
final String host = NetUtil.toSocketAddressString(raddr);
FullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
host,
Unpooled.EMPTY_BUFFER, false);
req.headers().set(HttpHeaderNames.HOST, host);
if (authorization != null) {
req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
}
if (headers != null) {
req.headers().add(headers);
}
return req;
}
/**
*
* @param factory
* the factory used to create InterfaceHttpData
* @param request
* the request to decode
* @param charset
* the charset to use as default
* @throws NullPointerException
* for request or charset or factory
* @throws ErrorDataDecoderException
* if the default charset was wrong when decoding or other
* errors
*/
public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) {
this.request = checkNotNull(request, "request");
this.charset = checkNotNull(charset, "charset");
this.factory = checkNotNull(factory, "factory");
// Fill default values
setMultipart(this.request.headers().get(HttpHeaderNames.CONTENT_TYPE));
if (request instanceof HttpContent) {
// Offer automatically if the given request is als type of HttpContent
// See #1089
offer((HttpContent) request);
} else {
undecodedChunk = buffer();
parseBody();
}
}
/**
* Create a new {@link DiscordWebClient} wrapping HTTP, Discord and encoding/decoding resources.
*
* @param httpClient a Reactor Netty HTTP client
* @param exchangeStrategies a strategy to transform requests and responses
* @param authorizationScheme scheme to use with the authorization header, like "Bot" or "Bearer"
* @param token a Discord token for API authorization
* @param responseFunctions a list of {@link ResponseFunction} transformations
*/
public DiscordWebClient(HttpClient httpClient, ExchangeStrategies exchangeStrategies,
String authorizationScheme, String token,
List<ResponseFunction> responseFunctions) {
final Properties properties = GitProperties.getProperties();
final String version = properties.getProperty(GitProperties.APPLICATION_VERSION, "3");
final String url = properties.getProperty(GitProperties.APPLICATION_URL, "https://discord4j.com");
final HttpHeaders defaultHeaders = new DefaultHttpHeaders();
defaultHeaders.add(HttpHeaderNames.CONTENT_TYPE, "application/json");
defaultHeaders.add(HttpHeaderNames.AUTHORIZATION, authorizationScheme + " " + token);
defaultHeaders.add(HttpHeaderNames.USER_AGENT, "DiscordBot(" + url + ", " + version + ")");
defaultHeaders.add("X-RateLimit-Precision", "millisecond");
this.httpClient = httpClient;
this.defaultHeaders = defaultHeaders;
this.exchangeStrategies = exchangeStrategies;
this.responseFunctions = responseFunctions;
}
@Test(description = "Test Invoking the resource which endpoint defined at resource level"
+ "which has special characters in endpoint url")
public void testPerResourceEndpointWithSpecialCharacters() throws Exception {
Map<String, String> headers = new HashMap<>();
//test endpoint with token
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("petstore/v1/pet/findByStatusNew"), headers);
Assert.assertNotNull(response);
Assert.assertEquals(response.getData(), ResponseConstants.responseBodyV1);
Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatched");
}
private Http2Headers preflightHeaders(HttpMethod requestMethod) {
final Http2Headers responseHeaders = new DefaultHttp2Headers(true);
responseHeaders.set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO);
if (!setAccessAllowOriginHeader(responseHeaders)) {
return responseHeaders;
}
if (config.allowedRequestMethods().contains(requestMethod)) {
responseHeaders.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.toString());
}
if (config.isCredentialsAllowed()
&& !responseHeaders.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN).equals(ANY_ORIGIN)) {
responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
if (!config.exposedHeaders().isEmpty()) {
responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders());
}
responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, String.valueOf(config.maxAge()));
responseHeaders.set(
HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders());
return responseHeaders;
}
@Override
public HttpServerResponse addCookie(Cookie cookie) {
if (!hasSentHeaders()) {
this.responseHeaders.add(HttpHeaderNames.SET_COOKIE,
cookieEncoder.encode(cookie));
}
else {
throw new IllegalStateException("Status and headers already sent");
}
return this;
}
public static FullHttpResponse createResponse(HttpResponseStatus status, String message) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
if (message != null) {
ByteBuf buf = Unpooled.copiedBuffer(message, CharsetUtil.UTF_8);
response = response.replace(buf);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.writerIndex());
} else {
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
}
response.headers().set(HttpHeaderNames.CONTENT_TYPE, APPLICATION_JSON);
response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_STORE);
response.headers().set(HttpHeaderNames.PRAGMA, HttpHeaderValues.NO_CACHE);
return response;
}
private static URI resolveBaseUrl(HttpServerRequest request) throws URISyntaxException {
String scheme = getScheme(request);
String header = request.requestHeaders().get(HttpHeaderNames.HOST);
if (header != null) {
final int portIndex;
if (header.startsWith("[")) {
portIndex = header.indexOf(':', header.indexOf(']'));
}
else {
portIndex = header.indexOf(':');
}
if (portIndex != -1) {
try {
return new URI(scheme, null, header.substring(0, portIndex),
Integer.parseInt(header.substring(portIndex + 1)), null, null, null);
}
catch (NumberFormatException ex) {
throw new URISyntaxException(header, "Unable to parse port", portIndex);
}
}
else {
return new URI(scheme, header, null, null);
}
}
else {
InetSocketAddress localAddress = request.hostAddress();
return new URI(scheme, null, localAddress.getHostString(),
localAddress.getPort(), null, null, null);
}
}
@Test
public void testIndicatedSizeSmallerThanActualSizeSingleChunk() {
HelloRequest grpcRequest = HelloRequest.newBuilder().setName("myName").build();
byte[] dataBytes = grpcRequest.toByteArray();
byte[] lengthByteBuffer = ByteBuffer.allocate(4).putInt(2).array();
byte[] compressedByteBuffer = ByteBuffer.allocate(1).put((byte) 0).array();
int streamId = 567;
int length = dataBytes.length;
ByteBuf grpcRequestBuffer = UnpooledByteBufAllocator.DEFAULT.buffer(length + 5, length + 5);
grpcRequestBuffer.writeBytes(compressedByteBuffer);
grpcRequestBuffer.writeBytes(lengthByteBuffer);
grpcRequestBuffer.writeBytes(dataBytes);
channel.writeInbound(fullGrpcRequest(grpcRequestBuffer, streamId, true));
Response response = channel.readOutbound();
SegmentedData segmentedData = channel.readOutbound();
assertEquals(HttpResponseStatus.OK, response.status());
assertEquals(streamId, response.streamId());
assertEquals("application/grpc+proto", response.headers().get(HttpHeaderNames.CONTENT_TYPE));
assertEquals("13", Objects.requireNonNull(segmentedData.trailingHeaders()).get("grpc-status"));
String actualMessage =
grpcDecodedString(
Objects.requireNonNull(
Objects.requireNonNull(segmentedData.trailingHeaders()).get("grpc-message")));
assertEquals("indicated payload size does not match actual payload size", actualMessage);
assertEquals(streamId, segmentedData.streamId());
assertTrue(segmentedData.endOfMessage());
}
private void invoke(String token, int responseCode) throws Exception {
Map<String, String> headers = new HashMap<>();
//test endpoint with token
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + token);
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
Assert.assertNotNull(response);
Assert.assertEquals(response.getResponseCode(), responseCode, "Response code mismatched");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, MetricRequest m) throws Exception {
try {
this.dataStore.store(m.getMetric());
} catch (TimelyException e) {
LOG.error(e.getMessage(), e);
this.sendHttpError(ctx, e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.EMPTY_BUFFER);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, Constants.JSON_TYPE);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
sendResponse(ctx, response);
}
private static String getHostColonPortFromHeader(HttpRequest request) {
String hostColonPort = extractHostColonPort(request.uri());
if (StringUtils.isBlank(hostColonPort)) {
List<String> hosts = request.headers().getAll(HttpHeaderNames.HOST);
if (hosts != null && !hosts.isEmpty()) {
hostColonPort = hosts.get(0);
}
}
return hostColonPort;
}
@Test(description = "Test Invoking the fail over endpoints using references")
public void testFailOverEndpointResourceLevelOverride() throws Exception {
Map<String, String> headers = new HashMap<>();
//test endpoint with token
headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
.doGet(getServiceURLHttp("petstore/v2/store/inventory"), headers);
Assert.assertNotNull(response);
Assert.assertEquals(response.getData(), ResponseConstants.storeInventoryResponse);
Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatched");
}
protected HttpURLConnection request(String path, String method, boolean keepAlive) throws IOException {
URL url = baseURI.resolve(path).toURL();
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
urlConn.setDoOutput(true);
}
urlConn.setRequestMethod(method);
if (!keepAlive) {
urlConn.setRequestProperty(HttpHeaderNames.CONNECTION.toString(), HEADER_VAL_CLOSE);
}
return urlConn;
}
@Test
public void testImprovedUploadMethod() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
String path;
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(200, response.getStatusLine().getStatusCode());
path = TestUtil.consumeText(response);
assertNotNull(path);
assertTrue(path.startsWith("/static"));
assertTrue(path.endsWith("bin"));
}
String responseUrl = "http://127.0.0.1:18080" + path;
verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);
try (CloseableHttpResponse response = httpclient.execute(index)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
}
}