下面列出了javax.servlet.http.PushBuilder#io.undertow.util.HttpString 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Test of matchOrigin method, of class CorsUtil.
*/
@Test
public void testMatchOrigin() throws Exception {
HeaderMap headerMap = new HeaderMap();
headerMap.add(HOST, "localhost:80");
headerMap.add(ORIGIN, "http://localhost");
HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
exchange.setRequestScheme("http");
exchange.setRequestMethod(HttpString.EMPTY);
Collection<String> allowedOrigins = null;
assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
allowedOrigins = Collections.singletonList("http://www.example.com:9990");
//Default origin
assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
headerMap.clear();
headerMap.add(HOST, "localhost:80");
headerMap.add(ORIGIN, "http://www.example.com:9990");
assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://www.example.com:9990"));
headerMap.clear();
headerMap.add(HOST, "localhost:80");
headerMap.add(ORIGIN, "http://www.example.com");
assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is(nullValue()));
headerMap.addAll(ORIGIN, Arrays.asList("http://localhost:8080", "http://www.example.com:9990", "http://localhost"));
allowedOrigins = Arrays.asList("http://localhost", "http://www.example.com:9990");
assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
List<ServiceEndpoint> values = serviceEndpoints.get(serviceId);
if(values == null || values.size() == 0) {
setExchangeStatus(exchange, SERVICE_ENDPOINT_NOT_FOUND, serviceId);
processAudit(exchange);
return;
}
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
processAudit(exchange);
}
private void prepareResponseChannel(ClientResponse response, ClientExchange exchange) {
String encoding = response.getResponseHeaders().getLast(Headers.TRANSFER_ENCODING);
boolean chunked = encoding != null && Headers.CHUNKED.equals(new HttpString(encoding));
String length = response.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH);
if (exchange.getRequest().getMethod().equals(Methods.HEAD)) {
connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
} else if (chunked) {
connection.getSourceChannel().setConduit(new ChunkedStreamSourceConduit(connection.getSourceChannel().getConduit(), pushBackStreamSourceConduit, bufferPool, responseFinishedListener, exchange, connection));
} else if (length != null) {
try {
long contentLength = Long.parseLong(length);
connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), contentLength, responseFinishedListener));
} catch (NumberFormatException e) {
handleError(e);
throw e;
}
} else if (response.getProtocol().equals(Protocols.HTTP_1_1) && !Connectors.isEntityBodyAllowed(response.getResponseCode())) {
connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
} else {
connection.getSourceChannel().setConduit(new FinishableStreamSourceConduit(connection.getSourceChannel().getConduit(), responseFinishedListener));
state |= CLOSE_REQ;
}
}
@Test
void append() {
var headers = new HeaderMap();
HttpString name = new HttpString("client-id");
headers.put(name, "client1");
var builder = new StringBuilder();
var param = new HeaderLogParam(name, headers.get(name));
param.append(builder, Set.of(), 1000);
assertThat(builder.toString()).isEqualTo("client1");
headers.add(name, "client2");
builder = new StringBuilder();
param = new HeaderLogParam(name, headers.get(name));
param.append(builder, Set.of(), 1000);
assertThat(builder.toString()).isEqualTo("[client1, client2]");
}
/**
* Return if a given HTTP method results in a read or write request to a resource
*
* GET = read
* POST = write
* PUT = write
* DELETE = write
* PATCH = write
* OPTIONS = read
* HEAD = read
*
* @param method The HTTP method
* @return read or write if HTTP method is found, blank otherwise
*/
public static String getOperation(HttpString method) {
String operation = "";
if (Methods.POST.equals(method)) {
operation = WRITE;
} else if (Methods.PUT.equals(method)) {
operation = WRITE;
} else if (Methods.DELETE.equals(method)) {
operation = WRITE;
} else if (Methods.GET.equals(method)) {
operation = READ;
} else if (Methods.PATCH.equals(method)) {
operation = WRITE;
} else if (Methods.OPTIONS.equals(method)) {
operation = READ;
} else if (Methods.HEAD.equals(method)) {
operation = READ;
} else {
// ignore everything else
}
return operation;
}
@Override
public void sendRequest(final ClientRequest request, final ClientCallback<ClientExchange> clientCallback) {
if(http2Delegate != null) {
http2Delegate.sendRequest(request, clientCallback);
return;
}
if (anyAreSet(state, UPGRADE_REQUESTED | UPGRADED | CLOSE_REQ | CLOSED)) {
clientCallback.failed(UndertowClientMessages.MESSAGES.invalidConnectionState());
return;
}
final HttpClientExchange httpClientExchange = new HttpClientExchange(clientCallback, request, this);
boolean ssl = this.connection instanceof SslConnection;
if(!ssl && !http2Tried && options.get(UndertowOptions.ENABLE_HTTP2, false) && !request.getRequestHeaders().contains(Headers.UPGRADE)) {
//this is the first request, as we want to try a HTTP2 upgrade
request.getRequestHeaders().put(new HttpString("HTTP2-Settings"), Http2ClearClientProvider.createSettingsFrame(options, bufferPool));
request.getRequestHeaders().put(Headers.UPGRADE, Http2Channel.CLEARTEXT_UPGRADE_STRING);
request.getRequestHeaders().put(Headers.CONNECTION, "Upgrade, HTTP2-Settings");
http2Tried = true;
}
if (currentRequest == null) {
initiateRequest(httpClientExchange);
} else {
pendingQueue.add(httpClientExchange);
}
}
/**
* Add a PathChain (having a non-null path) to the handler data structures.
*/
private static void addPathChain(PathChain pathChain) {
HttpString method = new HttpString(pathChain.getMethod());
// Use a random integer as the id for a given path.
Integer randInt = new Random().nextInt();
while (handlerListById.containsKey(randInt.toString())) {
randInt = new Random().nextInt();
}
// Flatten out the execution list from a mix of middleware chains and handlers.
List<HttpHandler> handlers = getHandlersFromExecList(pathChain.getExec());
if(handlers.size() > 0) {
// If a matcher already exists for the given type, at to that instead of
// creating a new one.
PathTemplateMatcher<String> pathTemplateMatcher = methodToMatcherMap.containsKey(method)
? methodToMatcherMap.get(method)
: new PathTemplateMatcher<>();
if(pathTemplateMatcher.get(pathChain.getPath()) == null) { pathTemplateMatcher.add(pathChain.getPath(), randInt.toString()); }
methodToMatcherMap.put(method, pathTemplateMatcher);
handlerListById.put(randInt.toString(), handlers);
}
}
public boolean execute(Object ...objects) throws Exception {
Map<String, Object> inputMap = (Map<String, Object>) objects[0];
Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
String token = (String) data.get("token");
String path = null;
Map<String, Object> fileMap = ServiceLocator.getInstance().getMemoryImage("fileMap");
ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)fileMap.get("cache");
if(cache != null) {
path = (String)cache.get(token);
}
if(path == null) {
inputMap.put("result", "Token is expired.");
inputMap.put("responseCode", 400);
return false;
} else {
HttpServerExchange exchange = (HttpServerExchange)inputMap.get("exchange");
File file = new File(path);
String name = file.getName();
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/x-download");
exchange.getResponseHeaders().put(new HttpString("Content-disposition"), "attachment; filename=" + name);
writeToOutputStream(file, exchange.getOutputStream());
return true;
}
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());
if(logger.isDebugEnabled()) logger.debug("userId = " + userId + " page = " + page + " pageSize = " + pageSize);
LikePredicate likePredicate = new LikePredicate("userId", userId);
PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new RefreshTokenComparator(), pageSize);
pagingPredicate.setPage(page);
Collection<RefreshToken> values = tokens.values(pagingPredicate);
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
processAudit(exchange);
}
protected ExchangeAttribute getServerToClientElement(
PatternTokenizer tokenizer) throws IOException {
if (tokenizer.hasSubToken()) {
String token = tokenizer.getToken();
if ("status".equals(token)) {
return ResponseCodeAttribute.INSTANCE;
} else if ("comment".equals(token)) {
return new ConstantExchangeAttribute("?");
}
} else if (tokenizer.hasParameter()) {
String parameter = tokenizer.getParameter();
if (parameter == null) {
UndertowLogger.ROOT_LOGGER.extendedAccessLogMissingClosing();
return null;
}
return new QuotingExchangeAttribute(new ResponseHeaderAttribute(new HttpString(parameter)));
}
UndertowLogger.ROOT_LOGGER.extendedAccessLogCannotDecode(tokenizer.getRemains());
return null;
}
@Test
public void testWithSerializedContextData() throws Throwable {
TracingHandler handler = new TracingHandler(httpHandler);
HttpServerExchange exchange = buildExchange();
exchange.getRequestHeaders()
.put(HttpString.tryFromString(SW8CarrierItem.HEADER_NAME), "1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
handler.handleRequest(exchange);
exchange.endExchange();
assertThat(segmentStorage.getTraceSegments().size(), is(1));
TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
assertHttpSpan(spans.get(0));
assertTraceSegmentRef(traceSegment.getRefs().get(0));
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
String responseBody = null;
if(exchange.getAttachment(BodyHandler.REQUEST_BODY) != null) {
responseBody = Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY));
}
List<HttpString> headerNames = exchange.getRequestHeaders().getHeaderNames().stream()
.filter( s -> s.toString().startsWith("todo"))
.collect(Collectors.toList());
for(HttpString headerName : headerNames) {
String headerValue = exchange.getRequestHeaders().get(headerName).getFirst();
exchange.getResponseHeaders().put(headerName, headerValue);
}
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
exchange.getResponseSender().send(responseBody);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
Deque<String> clientNameDeque = exchange.getQueryParameters().get("clientName");
String clientName = clientNameDeque == null? "%" : clientNameDeque.getFirst() + "%";
int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());
LikePredicate likePredicate = new LikePredicate("clientName", clientName);
PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ClientComparator(), pageSize);
pagingPredicate.setPage(page);
Collection<Client> values = clients.values(pagingPredicate);
List results = new ArrayList();
for (Client value : values) {
Client c = Client.copyClient(value);
c.setClientSecret(null);
results.add(c);
}
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(results));
processAudit(exchange);
}
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
String clientId = exchange.getQueryParameters().get("clientId").getFirst();
IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
Client client = clients.get(clientId);
if(client == null) {
setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
processAudit(exchange);
return;
}
Client c = Client.copyClient(client);
c.setClientSecret(null);
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(c));
processAudit(exchange);
}
private void setResponseHeaders(Headers headers, HttpServerExchange exchange) {
HeaderMap map = exchange.getResponseHeaders();
headers.keySet().forEach(headerName -> headers.getList(headerName)
.forEach(v -> {
if (v instanceof String) {
map.add(HttpString.tryFromString(headerName), (String) v);
} else if (v instanceof Number) {
map.add(HttpString.tryFromString(headerName), ((Number) v).longValue());
}
}));
}
static RoutingHandler getTestHandler() {
return Handlers.routing()
.add(Methods.GET, "/v2/pet/{petId}", exchange -> {
Map<String, Object> examples = new HashMap<>();
examples.put("application/xml", StringEscapeUtils.unescapeHtml4("<Pet> <id>123456</id> <name>doggie</name> <photoUrls> <photoUrls>string</photoUrls> </photoUrls> <tags> </tags> <status>string</status></Pet>"));
examples.put("application/json", StringEscapeUtils.unescapeHtml4("{ "photoUrls" : [ "aeiou" ], "name" : "doggie", "id" : 123456789, "category" : { "name" : "aeiou", "id" : 123456789 }, "tags" : [ { "name" : "aeiou", "id" : 123456789 } ], "status" : "aeiou"}"));
if(examples.size() > 0) {
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send((String)examples.get("application/json"));
} else {
exchange.endExchange();
}
})
.add(Methods.GET, "/v2/pet", exchange -> exchange.getResponseSender().send("get"));
}
private static boolean persistentConnection(HttpServerExchange exchange, String connectionHeader) {
if (exchange.isHttp11()) {
return !(connectionHeader != null && Headers.CLOSE.equalToString(connectionHeader));
} else if (exchange.isHttp10()) {
if (connectionHeader != null) {
if (Headers.KEEP_ALIVE.equals(new HttpString(connectionHeader))) {
return true;
}
}
}
log.trace("Connection not persistent");
return false;
}
private void writeHuffmanEncodableValue(ByteBuffer target, HttpString headerName, String val) {
if (hpackHeaderFunction.shouldUseHuffman(headerName, val)) {
if (!HPackHuffman.encode(target, val, false)) {
writeValueString(target, val);
}
} else {
writeValueString(target, val);
}
}
static RoutingHandler getTestHandler() {
return Handlers.routing()
.add(Methods.GET, "/v1/pets/{petId}", exchange -> {
Map<String, Object> examples = new HashMap<>();
examples.put("application/xml", StringEscapeUtils.unescapeHtml4("<Pet> <id>123456</id> <name>doggie</name> <photoUrls> <photoUrls>string</photoUrls> </photoUrls> <tags> </tags> <status>string</status></Pet>"));
examples.put("application/json", StringEscapeUtils.unescapeHtml4("{ "photoUrls" : [ "aeiou" ], "name" : "doggie", "id" : 123456789, "category" : { "name" : "aeiou", "id" : 123456789 }, "tags" : [ { "name" : "aeiou", "id" : 123456789 } ], "status" : "aeiou"}"));
if(examples.size() > 0) {
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send((String)examples.get("application/json"));
} else {
exchange.endExchange();
}
})
.add(Methods.GET, "/v1/pets", exchange -> exchange.getResponseSender().send("get"));
}
@Override
@SuppressWarnings("unchecked")
public void handleRequest(HttpServerExchange exchange) throws Exception {
try {
ContainerRequest request = createContainerRequest(exchange);
request.setWriter(new UndertowResponseWriter(exchange, container));
container.getApplicationHandler().handle(request);
} catch (Throwable e) {
if (exchange.isResponseChannelAvailable()) {
exchange.setStatusCode(500);
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "text/plain");
exchange.getResponseSender().send(Exceptions.stackTrace(e));
}
}
}
TableEntry(HttpString name, String value, int position) {
this.name = name;
this.value = value;
this.position = position;
if (value != null) {
this.size = 32 + name.length() + value.length();
} else {
this.size = -1;
}
}
@Test
public void testNoResponseContentValidation() throws ClientException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
ClientRequest clientRequest = new ClientRequest();
clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "");
String statusCode = future.get().getStatus();
Assert.assertNotEquals("OK", statusCode);
}
private void writeHuffmanEncodableName(ByteBuffer target, HttpString headerName) {
if (hpackHeaderFunction.shouldUseHuffman(headerName)) {
if(HPackHuffman.encode(target, headerName.toString(), true)) {
return;
}
}
target.put((byte) 0); //to use encodeInteger we need to place the first byte in the buffer.
encodeInteger(target, headerName.length(), 7);
for (int j = 0; j < headerName.length(); ++j) {
target.put(Hpack.toLower(headerName.byteAt(j)));
}
}
public synchronized RoutingHandler add(HttpString method, String template, HttpHandler handler) {
PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
if (matcher == null) {
matches.put(method, matcher = new PathTemplateMatcher<>());
}
RoutingMatch res = matcher.get(template);
if (res == null) {
matcher.add(template, res = new RoutingMatch());
}
if (allMethodsMatcher.get(template) == null) {
allMethodsMatcher.add(template, res);
}
res.defaultHandler = handler;
return this;
}
@Test
public void testResponseContentValidationWithNoError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
ClientRequest clientRequest = new ClientRequest();
clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
String statusCode = future.get().getStatus();
Assert.assertEquals("OK", statusCode);
List<String> errorLines = getErrorLinesFromLogFile();
Assert.assertTrue(errorLines.size() == 0);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
SpecificationConfig config = (SpecificationConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, SpecificationConfig.class);
final String payload = Config.getInstance().getStringFromFile(config.getFileName());
exchange.getResponseHeaders().add(new HttpString("Content-Type"), config.getContentType());
exchange.getResponseSender().send(payload);
}
@Override
public ExchangeAttribute build(final String token) {
if (token.startsWith("%{o,") && token.endsWith("}")) {
final HttpString headerName = HttpString.tryFromString(token.substring(4, token.length() - 1));
return new ResponseHeaderAttribute(headerName);
}
return null;
}
/**
* Handle a management+ request.
*
* @param method the http method
* @param exchange the http server exchange
* @throws Exception
*/
protected void handleRequest(final HttpString method, HttpServerExchange exchange) throws Exception {
final RequestData requestData = parseFormData(exchange);
boolean persistent = exchange.isPersistent();
exchange.setPersistent(false); //UNDERTOW-947 MCMP should not use persistent connections
if (CONFIG.equals(method)) {
processConfig(exchange, requestData);
} else if (ENABLE_APP.equals(method)) {
processCommand(exchange, requestData, MCMPAction.ENABLE);
} else if (DISABLE_APP.equals(method)) {
processCommand(exchange, requestData, MCMPAction.DISABLE);
} else if (STOP_APP.equals(method)) {
processCommand(exchange, requestData, MCMPAction.STOP);
} else if (REMOVE_APP.equals(method)) {
processCommand(exchange, requestData, MCMPAction.REMOVE);
} else if (STATUS.equals(method)) {
processStatus(exchange, requestData);
} else if (INFO.equals(method)) {
processInfo(exchange);
} else if (DUMP.equals(method)) {
processDump(exchange);
} else if (PING.equals(method)) {
processPing(exchange, requestData);
} else {
exchange.setPersistent(persistent);
next.handleRequest(exchange);
}
}
@Override
public Enumeration<String> getHeaderNames() {
final Set<String> headers = new HashSet<>();
for (final HttpString i : exchange.getRequestHeaders().getHeaderNames()) {
headers.add(i.toString());
}
return new IteratorEnumeration<>(headers.iterator());
}
/**
* Send an error message.
*
* @param type the error type
* @param errString the error string
* @param exchange the http server exchange
*/
static void processError(String type, String errString, HttpServerExchange exchange) {
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
exchange.getResponseHeaders().add(new HttpString("Version"), VERSION_PROTOCOL);
exchange.getResponseHeaders().add(new HttpString("Type"), type);
exchange.getResponseHeaders().add(new HttpString("Mess"), errString);
exchange.endExchange();
UndertowLogger.ROOT_LOGGER.mcmpProcessingError(type, errString);
}