本文整理汇总了Java中io.undertow.server.HttpServerExchange类的典型用法代码示例。如果您正苦于以下问题:Java HttpServerExchange类的具体用法?Java HttpServerExchange怎么用?Java HttpServerExchange使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpServerExchange类属于io.undertow.server包,在下文中一共展示了HttpServerExchange类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processRequest
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
private void processRequest(final HttpServerExchange exchange) throws IOException {
final ChannelInputStream cis = new ChannelInputStream(exchange.getRequestChannel());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
final long beginningTime = System.currentTimeMillis();
final String body = IOUtils.toString(cis, StandardCharsets.UTF_8);
final AbstractResponse response = process(body, exchange.getSourceAddress());
sendResponse(exchange, response, beginningTime);
}
示例2: send
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
/**
* response
*
* @param exchange
* @param statusCode
* @param output
* auto release
*/
protected final void send(HttpServerExchange exchange, int statusCode, PooledByteBufferOutputStream output) {
try {
output.flip();
StreamSinkChannel channel = getResponseChannel(exchange);
Sender sender = exchange.getResponseSender();
setStatusCode(exchange, statusCode);
setResponseChannel(sender, channel);
setPooledBuffers(sender, output.getPooledByteBuffers());
sender.send(output.getByteBuffers());
} catch (Throwable t) {
UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
}
}
示例3: handleRequest
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
public static void handleRequest(HttpServerExchange exchange, final ServletRequestContext servletRequestContext, final Throwable exception) throws IOException {
HttpServletRequestImpl req = servletRequestContext.getOriginalRequest();
StringBuilder sb = new StringBuilder();
//todo: make this good
sb.append("<html><head><title>ERROR</title>");
sb.append(ERROR_CSS);
sb.append("</head><body><div class=\"header\"><div class=\"error-div\"></div><div class=\"error-text-div\">Error processing request</div></div>");
writeLabel(sb, "Context Path", req.getContextPath());
writeLabel(sb, "Servlet Path", req.getServletPath());
writeLabel(sb, "Path Info", req.getPathInfo());
writeLabel(sb, "Query String", req.getQueryString());
sb.append("<b>Stack Trace</b><br/>");
sb.append(escapeBodyText(exception.toString()));
sb.append("<br/>");
for(StackTraceElement element : exception.getStackTrace()) {
sb.append(escapeBodyText(element.toString()));
sb.append("<br/>");
}
sb.append("</body></html>");
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html; charset=UTF-8");
exchange.getResponseSender().send(sb.toString());
}
示例4: resolve
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
@Override
public boolean resolve(final HttpServerExchange exchange) {
final Map<String, String> params = new HashMap<>();
String path = attribute.readAttribute(exchange);
if(path == null) {
return false;
}
boolean result = this.value.matches(path, params);
if (result) {
Map<String, Object> context = exchange.getAttachment(PREDICATE_CONTEXT);
if (context != null) {
context.putAll(params);
}
}
return result;
}
示例5: addDateHeaderIfRequired
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
public static void addDateHeaderIfRequired(HttpServerExchange exchange) {
HeaderMap responseHeaders = exchange.getResponseHeaders();
if (exchange.getConnection().getUndertowOptions().get(UndertowOptions.ALWAYS_SET_DATE, true) && !responseHeaders.contains(Headers.DATE)) {
String dateString = cachedDateString.get();
if (dateString != null) {
responseHeaders.put(Headers.DATE, dateString);
} else {
//set the time and register a timer to invalidate it
//note that this is racey, it does not matter if multiple threads do this
//the perf cost of synchronizing would be more than the perf cost of multiple threads running it
long realTime = System.currentTimeMillis();
long mod = realTime % 1000;
long toGo = 1000 - mod;
dateString = DateUtils.toDateString(new Date(realTime));
if (cachedDateString.compareAndSet(null, dateString)) {
exchange.getConnection().getIoThread().executeAfter(INVALIDATE_TASK, toGo, TimeUnit.MILLISECONDS);
}
responseHeaders.put(Headers.DATE, dateString);
}
}
}
示例6: readAttribute
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
@Override
public String readAttribute(final HttpServerExchange exchange) {
Deque<String> res = exchange.getPathParameters().get(parameter);
if(res == null) {
return null;
}else if(res.isEmpty()) {
return "";
} else if(res.size() ==1) {
return res.getFirst();
} else {
StringBuilder sb = new StringBuilder("[");
int i = 0;
for(String s : res) {
sb.append(s);
if(++i != res.size()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
示例7: redirector
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
public static HttpHandler redirector(HttpHandler next) {
return (HttpServerExchange exchange) -> {
HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
String host = currentUrl.host();
boolean redirect = false;
Builder newUrlBuilder = currentUrl.newBuilder();
if (host.equals("stubbornjava.com")) {
host = "www." + host;
newUrlBuilder.host(host);
redirect = true;
logger.debug("Host {} does not start with www redirecting to {}", currentUrl.host(), host);
}
if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
logger.debug("non https switching to https", currentUrl.host(), host);
newUrlBuilder.scheme("https")
.port(443);
redirect = true;
}
if (redirect) {
HttpUrl newUrl = newUrlBuilder.build();
exchange.setStatusCode(301);
exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
exchange.endExchange();
return;
}
next.handleRequest(exchange);
};
}
示例8: handleRequest
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
boolean handlingRequired = File.separatorChar != '/';
if (handlingRequired) {
exchange.setRequestPath(canonicalize(exchange.getRequestPath().replace(File.separatorChar, '/')));
exchange.setRelativePath(canonicalize(exchange.getRelativePath().replace(File.separatorChar, '/')));
exchange.setResolvedPath(canonicalize(exchange.getResolvedPath().replace(File.separatorChar, '/')));
}
next.handleRequest(exchange);
}
示例9: serveLoginPage
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
/**
* Forward to the login page with a specific error message. Avoids a redirect. Based on the
* ServletFormAuthenticationMechanism method. The location should be relative to the current
* context and start with "/" e.g. /login.jsp
*
* @throws IOException
* @throws ServletException
*/
protected Integer serveLoginPage(final HttpServerExchange exchange, final String location) throws ServletException,
IOException {
ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequest request = (HttpServletRequest) context.getServletRequest();
HttpServletResponse response = (HttpServletResponse) context.getServletResponse();
exchange.getResponseHeaders().add(Headers.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
exchange.getResponseHeaders().add(Headers.PRAGMA, "no-cache");
exchange.getResponseHeaders().add(Headers.EXPIRES, "0");
request.getRequestDispatcher(location).forward(request, response);
return null;
}
示例10: handleRequest
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
Map<String, Object> examples = new HashMap<>();
if(examples.size() > 0) {
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send((String)examples.get("application/json"));
} else {
exchange.endExchange();
}
}
示例11: readAttribute
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
@Override
public String readAttribute(final HttpServerExchange exchange) {
String qs = exchange.getQueryString();
if(qs.isEmpty()) {
return qs;
}
return '?' + qs;
}
示例12: data
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
public void data(HttpServerExchange exchange) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/binary");
// let's also update the cookie, if present. This place will get called frequent enough
Cookie tokenCookie = exchange.getRequestCookies().get("pxls-token");
if (tokenCookie != null) {
setAuthCookie(exchange, tokenCookie.getValue(), 24);
}
exchange.getResponseSender().send(ByteBuffer.wrap(App.getBoardData()));
}
示例13: handleCustomLog
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
private void handleCustomLog(HttpServerExchange exchange, Throwable t, Logger.Level level, Logger.Level stackTraceLevel, String category) {
BasicLogger logger = UndertowLogger.REQUEST_LOGGER;
if (!category.isEmpty()) {
logger = Logger.getLogger(category);
}
boolean stackTrace = true;
if (stackTraceLevel.ordinal() > level.ordinal()) {
if (!logger.isEnabled(stackTraceLevel)) {
stackTrace = false;
}
}
if (stackTrace) {
logger.logf(level, t, "Exception handling request to %s", exchange.getRequestURI());
} else {
logger.logf(level, "Exception handling request to %s: %s", exchange.getRequestURI(), t.getMessage());
}
}
示例14: handleHeaderValue
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
/**
* Parses a header value. This is called from the generated bytecode.
*
* @param buffer The buffer
* @param state The current state
* @param builder The exchange builder
* @return The number of bytes remaining
*/
@SuppressWarnings("unused")
final void handleHeaderValue(ByteBuffer buffer, ParseState state, HttpServerExchange builder) {
HttpString headerName = state.nextHeader;
StringBuilder stringBuilder = state.stringBuilder;
HashMap<HttpString, String> headerValuesCache = state.headerValuesCache;
if (stringBuilder.length() == 0) {
String existing = headerValuesCache.get(headerName);
if (existing != null) {
if (handleCachedHeader(existing, buffer, state, builder)) {
return;
}
}
}
handleHeaderValueCacheMiss(buffer, state, builder, headerName, headerValuesCache, stringBuilder);
}
示例15: customize
import io.undertow.server.HttpServerExchange; //导入依赖的package包/类
@Override
public void customize(DeploymentInfo deploymentInfo) {
deploymentInfo.addInitialHandlerChainWrapper(handler -> {
return Handlers.path()
.addPrefixPath("/", handler)
.addPrefixPath(path, new WebSocketProtocolHandshakeHandler(new WSHandler()) {
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (reservationCheck(exchange)) {
super.handleRequest(exchange);
}
}
});
}
);
}