當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServerExchange類代碼示例

本文整理匯總了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);
}
 
開發者ID:AidosKuneen,項目名稱:aidos-node,代碼行數:10,代碼來源:API.java

示例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);
	}
}
 
開發者ID:hank-whu,項目名稱:undertow-async,代碼行數:25,代碼來源:AsyncHttpHandler.java

示例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());
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:ServletDebugPageHandler.java

示例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;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:17,代碼來源:PathTemplatePredicate.java

示例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);
        }
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:22,代碼來源:DateUtils.java

示例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();
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:PathParameterAttribute.java

示例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);
    };
}
 
開發者ID:StubbornJava,項目名稱:StubbornJava,代碼行數:34,代碼來源:PageRoutes.java

示例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);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:11,代碼來源:PathSeparatorHandler.java

示例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;
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:SsoHandler.java

示例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();
    }
}
 
開發者ID:tnscorcoran,項目名稱:light-4-j-plugin-wrapper,代碼行數:11,代碼來源:ServerInfoGetHandler.java

示例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;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:9,代碼來源:QueryStringAttribute.java

示例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()));
}
 
開發者ID:xSke,項目名稱:Pxls,代碼行數:12,代碼來源:WebHandler.java

示例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());
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:18,代碼來源:LoggingExceptionHandler.java

示例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);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:25,代碼來源:HttpRequestParser.java

示例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);
                        }
                    }
                });
        }
    );
}
 
開發者ID:syndesisio,項目名稱:syndesis,代碼行數:18,代碼來源:EventBusToWebSocket.java


注:本文中的io.undertow.server.HttpServerExchange類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。