当前位置: 首页>>代码示例>>Java>>正文


Java Headers类代码示例

本文整理汇总了Java中io.undertow.util.Headers的典型用法代码示例。如果您正苦于以下问题:Java Headers类的具体用法?Java Headers怎么用?Java Headers使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。

Headers类属于io.undertow.util包,在下文中一共展示了Headers类的40个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: processRequest

import io.undertow.util.Headers; //导入依赖的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: handleRequest

import io.undertow.util.Headers; //导入依赖的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


示例3: loadBalancerHttpToHttps

import io.undertow.util.Headers; //导入依赖的package包/类
public static HttpHandler loadBalancerHttpToHttps(HttpHandler next) {
    return (HttpServerExchange exchange) -> {
        HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
        String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
        if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
            log.debug("non https switching to https {}", currentUrl.host());
            HttpUrl newUrl = currentUrl.newBuilder()
               .scheme("https")
               .port(443)
               .build();
            exchange.setStatusCode(301);
            exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
            exchange.endExchange();
            return;
        }

        next.handleRequest(exchange);
    };
}
 
开发者ID:StubbornJava,项目名称:StubbornJava,代码行数:20,代码来源:CustomHandlers.java


示例4: handleRequest

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (isConfidential(exchange) || !confidentialityRequired(exchange)) {
        next.handleRequest(exchange);
    } else {
        try {
            URI redirectUri = getRedirectURI(exchange);

            exchange.setResponseCode(StatusCodes.FOUND);
            exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri.toString());
        } catch (Exception e) {
            UndertowLogger.REQUEST_LOGGER.exceptionProcessingRequest(e);
            exchange.setResponseCode(StatusCodes.INTERNAL_SERVER_ERROR);
        }
        exchange.endExchange();
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:AbstractConfidentialityHandler.java


示例5: sendRedirect

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void sendRedirect(final String location) throws IOException {
    if (responseStarted()) {
        throw UndertowServletMessages.MESSAGES.responseAlreadyCommited();
    }
    resetBuffer();
    setStatus(StatusCodes.FOUND);
    String realPath;
    if (location.contains("://")) {//absolute url
        exchange.getResponseHeaders().put(Headers.LOCATION, location);
    } else {
        if (location.startsWith("/")) {
            realPath = location;
        } else {
            String current = exchange.getRelativePath();
            int lastSlash = current.lastIndexOf("/");
            if (lastSlash != -1) {
                current = current.substring(0, lastSlash + 1);
            }
            realPath = CanonicalPathUtils.canonicalize(servletContext.getContextPath() + current + location);
        }
        String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + realPath;
        exchange.getResponseHeaders().put(Headers.LOCATION, loc);
    }
    responseDone();
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:27,代码来源:HttpServletResponseImpl.java


示例6: displayStackTraces

import io.undertow.util.Headers; //导入依赖的package包/类
public boolean displayStackTraces() {
    ServletStackTraces mode = deployment.getDeploymentInfo().getServletStackTraces();
    if (mode == ServletStackTraces.NONE) {
        return false;
    } else if (mode == ServletStackTraces.ALL) {
        return true;
    } else {
        InetSocketAddress localAddress = getExchange().getSourceAddress();
        if(localAddress == null) {
            return false;
        }
        InetAddress address = localAddress.getAddress();
        if(address == null) {
            return false;
        }
        if(!address.isLoopbackAddress()) {
            return false;
        }
        return !getExchange().getRequestHeaders().contains(Headers.X_FORWARDED_FOR);
    }

}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:ServletRequestContext.java


示例7: prepareResponseChannel

import io.undertow.util.Headers; //导入依赖的package包/类
private void prepareResponseChannel(ClientResponse response, ClientExchange exchange) {
    String encoding = response.getResponseHeaders().getLast(TRANSFER_ENCODING);
    boolean chunked = encoding != null && Headers.CHUNKED.equals(new HttpString(encoding));
    String length = response.getResponseHeaders().getFirst(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));
    } else if (length != null) {
        try {
            long contentLength = Long.parseLong(length);
            connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), contentLength, responseFinishedListener));
        } catch (NumberFormatException e) {
            handleError(new IOException(e));
            throw e;
        }
    } else if (response.getProtocol().equals(Protocols.HTTP_1_1)) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else {
        state |= CLOSE_REQ;
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:HttpClientConnection.java


示例8: redirector

import io.undertow.util.Headers; //导入依赖的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


示例9: handleFixedLength

import io.undertow.util.Headers; //导入依赖的package包/类
private static StreamSinkConduit handleFixedLength(HttpServerExchange exchange, boolean headRequest, StreamSinkConduit channel, HeaderMap responseHeaders, String contentLengthHeader, HttpServerConnection connection) {
    try {
        final long contentLength = parsePositiveLong(contentLengthHeader);
        if (headRequest) {
            return channel;
        }
        // fixed-length response
        ServerFixedLengthStreamSinkConduit fixed = connection.getFixedLengthStreamSinkConduit();
        fixed.reset(contentLength, exchange);
        return fixed;
    } catch (NumberFormatException e) {
        //we just fix it for them
        responseHeaders.remove(Headers.CONTENT_LENGTH);
    }
    return null;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:17,代码来源:HttpTransferEncoding.java


示例10: handleExplicitTransferEncoding

import io.undertow.util.Headers; //导入依赖的package包/类
private static StreamSinkConduit handleExplicitTransferEncoding(HttpServerExchange exchange, StreamSinkConduit channel, ConduitListener<StreamSinkConduit> finishListener, HeaderMap responseHeaders, String transferEncodingHeader, boolean headRequest) {
    HttpString transferEncoding = new HttpString(transferEncodingHeader);
    if (transferEncoding.equals(Headers.CHUNKED)) {
        if (headRequest) {
            return channel;
        }
        Boolean preChunked = exchange.getAttachment(HttpAttachments.PRE_CHUNKED_RESPONSE);
        if(preChunked != null && preChunked) {
            return new PreChunkedStreamSinkConduit(channel, finishListener, exchange);
        } else {
            return new ChunkedStreamSinkConduit(channel, exchange.getConnection().getBufferPool(), true, !exchange.isPersistent(), responseHeaders, finishListener, exchange);
        }
    } else {

        if (headRequest) {
            return channel;
        }
        log.trace("Cancelling persistence because response is identity with no content length");
        // make it not persistent - very unfortunate for the next request handler really...
        exchange.setPersistent(false);
        responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString());
        return new FinishableStreamSinkConduit(channel, terminateResponseListener(exchange));
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:HttpTransferEncoding.java


示例11: requiresContinueResponse

import io.undertow.util.Headers; //导入依赖的package包/类
/**
 * Returns true if this exchange requires the server to send a 100 (Continue) response.
 *
 * @param exchange The exchange
 * @return <code>true</code> if the server needs to send a continue response
 */
public static boolean requiresContinueResponse(final HttpServerExchange exchange) {
    if (!exchange.isHttp11() || exchange.isResponseStarted() || exchange.getAttachment(ALREADY_SENT) != null) {
        return false;
    }
    if (exchange.getConnection() instanceof HttpServerConnection) {
        if (((HttpServerConnection) exchange.getConnection()).getExtraBytes() != null) {
            //we have already received some of the request body
            //so according to the RFC we do not need to send the Continue
            return false;
        }
    }
    List<String> expect = exchange.getRequestHeaders().get(Headers.EXPECT);
    if (expect != null) {
        for (String header : expect) {
            if (header.equalsIgnoreCase(CONTINUE)) {
                return true;
            }
        }
    }
    return false;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:28,代码来源:HttpContinue.java


示例12: sendContinueResponseBlocking

import io.undertow.util.Headers; //导入依赖的package包/类
/**
 * Sends a continue response using blocking IO
 *
 * @param exchange The exchange
 */
public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException {
    if (!exchange.isResponseChannelAvailable()) {
        throw UndertowMessages.MESSAGES.cannotSendContinueResponse();
    }
    if(exchange.getAttachment(ALREADY_SENT) != null) {
        return;
    }
    HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange);
    exchange.putAttachment(ALREADY_SENT, true);
    newExchange.setResponseCode(StatusCodes.CONTINUE);
    newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
    newExchange.startBlocking();
    newExchange.getOutputStream().close();
    newExchange.getInputStream().close();
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:21,代码来源:HttpContinue.java


示例13: create

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public FormDataParser create(final HttpServerExchange exchange)  {
    String mimeType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (forceCreation || (mimeType != null && mimeType.startsWith(APPLICATION_X_WWW_FORM_URLENCODED))) {

        String charset = defaultEncoding;
        String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
        if (contentType != null) {
            String cs = Headers.extractQuotedValueFromHeader(contentType, "charset");
            if (cs != null) {
                charset = cs;
            }
        }
        return new FormEncodedDataParser(charset, exchange);
    }
    return null;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:FormEncodedDataDefinition.java


示例14: sendRequestedBlobs

import io.undertow.util.Headers; //导入依赖的package包/类
/**
 * Serve static resource for the directory listing
 *
 * @param exchange The exchange
 * @return true if resources were served
 */
public static boolean sendRequestedBlobs(HttpServerExchange exchange) {
    ByteBuffer buffer = null;
    String type = null;
    if ("css".equals(exchange.getQueryString())) {
        buffer = Blobs.FILE_CSS_BUFFER.duplicate();
        type = "text/css";
    } else if ("js".equals(exchange.getQueryString())) {
        buffer = Blobs.FILE_JS_BUFFER.duplicate();
        type = "application/javascript";
    }

    if (buffer != null) {
        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(buffer.limit()));
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, type);
        if (Methods.HEAD.equals(exchange.getRequestMethod())) {
            exchange.endExchange();
            return true;
        }
        exchange.getResponseSender().send(buffer);

        return true;
    }

    return false;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:32,代码来源:DirectoryUtils.java


示例15: handleRequest

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String hostHeader = exchange.getRequestHeaders().getFirst(Headers.HOST);
    if (hostHeader != null) {
        String host;
        if (hostHeader.contains(":")) { //header can be in host:port format
            host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
        } else {
            host = hostHeader;
        }
        final HttpHandler handler = hosts.get(host);
        if (handler != null) {
            handler.handleRequest(exchange);
            return;
        }
    }
    defaultHandler.handleRequest(exchange);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:19,代码来源:NameVirtualHostHandler.java


示例16: wrap

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) {
    if (exchange.getResponseHeaders().contains(Headers.CONTENT_ENCODING)) {
        //already encoded
        return factory.create();
    }
    //if this is a zero length response we don't want to encode
    if (exchange.getResponseContentLength() != 0
            && exchange.getResponseCode() != StatusCodes.NO_CONTENT
            && exchange.getResponseCode() != StatusCodes.NOT_MODIFIED) {
        EncodingMapping encoding = getEncoding();
        if (encoding != null) {
            exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, encoding.getName());
            if (exchange.getRequestMethod().equals(Methods.HEAD)) {
                //we don't create an actual encoder for HEAD requests, but we set the header
                return factory.create();
            } else {
                return encoding.getEncoding().getResponseWrapper().wrap(factory, exchange);
            }
        }
    }
    return factory.create();
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:24,代码来源:AllowedContentEncodings.java


示例17: CachedHttpRequest

import io.undertow.util.Headers; //导入依赖的package包/类
public CachedHttpRequest(final HttpServerExchange exchange) {
    this.path = exchange.getRequestPath();
    this.etag = ETagUtils.getETag(exchange);
    this.contentLocation = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LOCATION);
    this.language = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LANGUAGE);
    this.contentType = exchange.getResponseHeaders().getFirst(Headers.CONTENT_TYPE);
    String lmString = exchange.getResponseHeaders().getFirst(Headers.LAST_MODIFIED);
    if (lmString == null) {
        this.lastModified = null;
    } else {
        this.lastModified = DateUtils.parseDate(lmString);
    }
    //the content encoding can be decided dynamically, based on the current state of the request
    //as the decision to compress generally depends on size and mime type
    final AllowedContentEncodings encoding = exchange.getAttachment(AllowedContentEncodings.ATTACHMENT_KEY);
    if(encoding != null) {
        this.contentEncoding = encoding.getCurrentContentEncoding();
    } else {
        this.contentEncoding = exchange.getResponseHeaders().getFirst(Headers.CONTENT_ENCODING);
    }
    this.responseCode = exchange.getResponseCode();
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:CachedHttpRequest.java


示例18: handleRequest

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(exchange.getRequestMethod().equals(Methods.TRACE)) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http");
        StringBuilder body = new StringBuilder("TRACE ");
        body.append(exchange.getRequestURI());
        if(!exchange.getQueryString().isEmpty()) {
            body.append('?');
            body.append(exchange.getQueryString());
        }
        body.append(exchange.getProtocol().toString());
        body.append("\r\n");
        for(HeaderValues header : exchange.getRequestHeaders()) {
            for(String value : header) {
                body.append(header.getHeaderName());
                body.append(": ");
                body.append(value);
                body.append("\r\n");
            }
        }
        body.append("\r\n");
        exchange.getResponseSender().send(body.toString());
    } else {
        handler.handleRequest(exchange);
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:27,代码来源:HttpTraceHandler.java


示例19: getHostPort

import io.undertow.util.Headers; //导入依赖的package包/类
/**
 * Return the port that this request was sent to. In general this will be the value of the Host
 * header, minus the host name.
 *
 * @return The port part of the destination address
 */
public int getHostPort() {
    String host = requestHeaders.getFirst(Headers.HOST);
    if (host != null) {
        //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of :
        final int colonIndex;
        if (host.startsWith("[")) {
            colonIndex = host.indexOf(':', host.indexOf(']'));
        } else {
            colonIndex = host.indexOf(':');
        }
        if (colonIndex != -1) {
            return Integer.parseInt(host.substring(colonIndex + 1));
        } else {
            if (getRequestScheme().equals("https")) {
                return 443;
            } else if (getRequestScheme().equals("http")) {
                return 80;
            }
        }
    }
    return getDestinationAddress().getPort();
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:29,代码来源:HttpServerExchange.java


示例20: handshakeInternal

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
protected void handshakeInternal(final WebSocketHttpExchange exchange) {
    String origin = exchange.getRequestHeader(Headers.ORIGIN_STRING);
    if (origin != null) {
        exchange.setResponseHeader(Headers.ORIGIN_STRING, origin);
    }
    selectSubprotocol(exchange);
    selectExtensions(exchange);
    exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_LOCATION_STRING, getWebSocketLocation(exchange));

    final String key = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING);
    try {
        final String solution = solve(key);
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ACCEPT_STRING, solution);
        performUpgrade(exchange);
    } catch (NoSuchAlgorithmException e) {
        IoUtils.safeClose(exchange);
        exchange.endExchange();
        return;
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:22,代码来源:Hybi13Handshake.java


示例21: handshakeInternal

import io.undertow.util.Headers; //导入依赖的package包/类
protected void handshakeInternal(final WebSocketHttpExchange exchange) {

        String origin = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_ORIGIN_STRING);
        if (origin != null) {
            exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ORIGIN_STRING, origin);
        }
        selectSubprotocol(exchange);
        selectExtensions(exchange);
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_LOCATION_STRING, getWebSocketLocation(exchange));

        final String key = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING);
        try {
            final String solution = solve(key);
            exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ACCEPT_STRING, solution);
            performUpgrade(exchange);
        } catch (NoSuchAlgorithmException e) {
            IoUtils.safeClose(exchange);
            exchange.endExchange();
            return;
        }

    }
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:Hybi07Handshake.java


示例22: ban

import io.undertow.util.Headers; //导入依赖的package包/类
public void ban(HttpServerExchange exchange) {
    User user = parseUserFromForm(exchange);
    User user_perform = exchange.getAttachment(AuthReader.USER);
    if (user != null && user.getRole().lessThan(user_perform.getRole())) {
        String time = "86400";
        FormData data = exchange.getAttachment(FormDataParser.FORM_DATA);
        FormData.FormValue time_form = data.getFirst("time");
        if (time_form != null) {
            time = time_form.getValue();
        }
        if (doLog(exchange)) {
            App.getDatabase().adminLog("ban " + user.getName(), user_perform.getId());
        }
        user.ban(Integer.parseInt(time), getBanReason(exchange), getRollbackTime(exchange));
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/text");
        exchange.setStatusCode(200);
    } else {
        exchange.setStatusCode(400);
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:21,代码来源:WebHandler.java


示例23: check

import io.undertow.util.Headers; //导入依赖的package包/类
public void check(HttpServerExchange exchange) {
    User user = parseUserFromForm(exchange);
    if (user != null) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
        exchange.getResponseSender().send(App.getGson().toJson(
                new ServerUserInfo(user.getName(),
                        user.getRole().name(),
                        user.isBanned(),
                        user.getBanExpiryTime(),
                        user.getBanReason(),
                        user.getLogin().split(":")[0]
                )));
    } else {
        exchange.setStatusCode(400);
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:17,代码来源:WebHandler.java


示例24: testMultipleHttp2Get

import io.undertow.util.Headers; //导入依赖的package包/类
public void testMultipleHttp2Get(int round) throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final List<AtomicReference<ClientResponse>> references = new CopyOnWriteArrayList<>();
    final CountDownLatch latch = new CountDownLatch(round);
    final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
    try {
        connection.getIoThread().execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < round; i++) {
                    AtomicReference<ClientResponse> reference = new AtomicReference<>();
                    references.add(i, reference);
                    final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath("/get");
                    request.getRequestHeaders().put(Headers.HOST, "localhost");
                    connection.sendRequest(request, client.createClientCallback(reference, latch));
                }
            }
        });
        latch.await(10, TimeUnit.SECONDS);
        /*
        for (final AtomicReference<ClientResponse> reference : references) {
            System.out.println(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
            System.out.println(reference.get().getProtocol().toString());
        }
        */
    } finally {
        IoUtils.safeClose(connection);
    }
}
 
开发者ID:networknt,项目名称:http2client-benchmark,代码行数:30,代码来源:Http2ClientExample.java


示例25: testMultipleHttp2Post

import io.undertow.util.Headers; //导入依赖的package包/类
public void testMultipleHttp2Post(int round) throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final List<AtomicReference<ClientResponse>> references = new CopyOnWriteArrayList<>();
    final CountDownLatch latch = new CountDownLatch(round);
    final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
    try {
        connection.getIoThread().execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < round; i++) {
                    AtomicReference<ClientResponse> reference = new AtomicReference<>();
                    references.add(i, reference);
                    final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
                    request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                    request.getRequestHeaders().put(Headers.HOST, "localhost");
                    connection.sendRequest(request, client.createClientCallback(reference, latch, "post"));
                }
            }
        });
        latch.await(10, TimeUnit.SECONDS);
        /*
        for (final AtomicReference<ClientResponse> reference : references) {
            System.out.println(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
            System.out.println(reference.get().getProtocol().toString());
        }
        */
    } finally {
        IoUtils.safeClose(connection);
    }
}
 
开发者ID:networknt,项目名称:http2client-benchmark,代码行数:31,代码来源:Http2ClientExample.java


示例26: handleRequest

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    // get the request parameters as a Map<String, Object>
    @SuppressWarnings("unchecked")
    Map<String, Object> requestParameters = (Map<String, Object>)exchange.getAttachment(GraphqlUtil.GRAPHQL_PARAMS);
    if(logger.isDebugEnabled()) logger.debug("requestParameters: " + requestParameters);
    GraphQL graphQL = GraphQL.newGraphQL(schema).build();
    String query = (String)requestParameters.get("query");
    if(query == null) {
        Status status = new Status(STATUS_GRAPHQL_MISSING_QUERY);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;
    }
    @SuppressWarnings("unchecked")
    Map<String, Object> variables = (Map<String, Object>)requestParameters.get("variables");
    if(variables == null) {
        variables = new HashMap<>();
    }
    String operationName = (String)requestParameters.get("operationName");
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(query).operationName(operationName).context(exchange).root(exchange).variables(variables).build();
    ExecutionResult executionResult = graphQL.execute(executionInput);
    Map<String, Object> result = new HashMap<>();
    if (executionResult.getErrors().size() > 0) {
        result.put("errors", executionResult.getErrors());
        logger.error("Errors: {}", executionResult.getErrors());
    } else {
        result.put("data", executionResult.getData());
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(result));
}
 
开发者ID:networknt,项目名称:light-graphql-4j,代码行数:33,代码来源:GraphqlPostHandler.java


示例27: handleRequest

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void handleRequest(HttpServerExchange exchange) {
    @SuppressWarnings("unchecked")
    Map<String, Object> requestParameters = (Map<String, Object>)exchange.getAttachment(GraphqlUtil.GRAPHQL_PARAMS);
    if(logger.isDebugEnabled()) logger.debug("requestParameters: " + requestParameters);
    String graphiql = RenderGraphiQL.render(requestParameters, null);
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html; charset=UTF-8");
    exchange.getResponseSender().send(graphiql);
}
 
开发者ID:networknt,项目名称:light-graphql-4j,代码行数:10,代码来源:GraphqlGetHandler.java


示例28: invokePathTemplateHandler

import io.undertow.util.Headers; //导入依赖的package包/类
private void invokePathTemplateHandler(SpurOptions options, Map<HttpString, Endpoint> methodEndpointsMap, HttpServerExchange exchange) {

        HttpString requestMethod = exchange.getRequestMethod();
        String requestAccessControlRequestMethod = getRequestHeader(exchange, ACCESS_CONTROL_REQUEST_METHOD);
        String requestOrigin = getRequestHeader(exchange, Headers.ORIGIN);
        if (requestMethod.equals(HEAD)) {
            requestMethod = GET;
        } else if (requestMethod.equals(OPTIONS) && requestAccessControlRequestMethod != null && methodEndpointsMap.containsKey(
                new HttpString(requestAccessControlRequestMethod)) && isValidCorsOrigin(options, requestOrigin)) {
            setCorsMethodHeader(options, methodEndpointsMap, exchange);
            exchange.endExchange();
            return;
        }

        Endpoint endpoint = methodEndpointsMap.get(requestMethod);
        if (endpoint == null) {
            exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
            exchange.getResponseHeaders()
                    .put(Headers.ALLOW, getAllowedMethods(methodEndpointsMap, options));
            exchange.endExchange();
            return;
        }

        Req req = new Req(exchange, endpoint.getBodyClassType());
        req.parseBody((newExchange, body) -> endpoint.getReqResBiConsumer()
                .accept(req, new Res(newExchange)));
    }
 
开发者ID:icha024,项目名称:spur,代码行数:28,代码来源:SpurServer.java


示例29: send

import io.undertow.util.Headers; //导入依赖的package包/类
public void send(Object obj) {
    if (httpServerExchange.getRequestMethod()
            .equals(HEAD)) {
        httpServerExchange.endExchange();
        return;
    }
    httpServerExchange.getResponseHeaders()
            .put(Headers.CONTENT_TYPE, JSON_CONTENT_TYPE);

    ObjectMapper objectMapper = LOCAL_MAPPER.get();
    if (objectMapper == null) {
        LOGGER.info("Creating new parser.........");
        objectMapper = JsonFactory.createUseJSONDates();
        LOCAL_MAPPER.set(objectMapper);
    }

    String jsonStr = objectMapper
            .toJson(obj);
    ByteBuffer byteBuffer = ByteBuffer.wrap(jsonStr.getBytes(StandardCharsets.UTF_8));
    StreamSinkChannel responseChannel = httpServerExchange.getResponseChannel();
    int written;
    try {
        do {
            written = responseChannel.write(byteBuffer);
        } while (byteBuffer.hasRemaining() && written > 0);
    } catch (IOException e) {
        LOGGER.error("Can not write response: " + e.getMessage(), e);
    }
}
 
开发者ID:icha024,项目名称:spur,代码行数:30,代码来源:Res.java


示例30: init

import io.undertow.util.Headers; //导入依赖的package包/类
public void init() throws IOException {
	final int apiPort = Configuration.integer(DefaultConfSettings.API_PORT);
	final String apiHost = Configuration.string(DefaultConfSettings.API_HOST);

	log.debug("Binding JSON-REST API Undertown server on {}:{}", apiHost, apiPort);

	server = Undertow.builder().addHttpListener(apiPort, apiHost)
			.setHandler(path().addPrefixPath("/", new HttpHandler() {
				@Override
				public void handleRequest(final HttpServerExchange exchange) throws Exception {
					HttpString requestMethod = exchange.getRequestMethod();
					if (Methods.OPTIONS.equals(requestMethod)) {
						String allowedMethods = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
						// return list of allowed methods in response headers
						exchange.setStatusCode(StatusCodes.OK);
						exchange.getResponseHeaders().put(Headers.CONTENT_TYPE,
								MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt"));
						exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
						exchange.getResponseHeaders().put(Headers.ALLOW, allowedMethods);
						exchange.getResponseHeaders().put(new HttpString("Access-Control-Allow-Origin"), "*");
						exchange.getResponseHeaders().put(new HttpString("Access-Control-Allow-Headers"),
								"Origin, X-Requested-With, Content-Type, Accept");
						exchange.getResponseSender().close();
						return;
					}

					if (exchange.isInIoThread()) {
						exchange.dispatch(this);
						return;
					}
					processRequest(exchange);
				}
			})).build();
	server.start();
}
 
开发者ID:AidosKuneen,项目名称:aidos-node,代码行数:36,代码来源:API.java


示例31: sendChallenge

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public ChallengeResult sendChallenge(final HttpServerExchange exchange, final SecurityContext securityContext) {
    DigestContext context = exchange.getAttachment(DigestContext.ATTACHMENT_KEY);
    boolean stale = context == null ? false : context.isStale();

    StringBuilder rb = new StringBuilder(DIGEST_PREFIX);
    rb.append(Headers.REALM.toString()).append("=\"").append(realmName).append("\",");
    rb.append(Headers.DOMAIN.toString()).append("=\"").append(domain).append("\",");
    // based on security constraints.
    rb.append(Headers.NONCE.toString()).append("=\"").append(nonceManager.nextNonce(null, exchange)).append("\",");
    // Not currently using OPAQUE as it offers no integrity, used for session data leaves it vulnerable to
    // session fixation type issues as well.
    rb.append(Headers.OPAQUE.toString()).append("=\"00000000000000000000000000000000\"");
    if (stale) {
        rb.append(",stale=true");
    }
    if (supportedAlgorithms.size() > 0) {
        // This header will need to be repeated once for each algorithm.
        rb.append(",").append(Headers.ALGORITHM.toString()).append("=%s");
    }
    if (qopString != null) {
        rb.append(",").append(Headers.QOP.toString()).append("=\"").append(qopString).append("\"");
    }

    String theChallenge = rb.toString();
    HeaderMap responseHeader = exchange.getResponseHeaders();
    if (supportedAlgorithms.isEmpty()) {
        responseHeader.add(WWW_AUTHENTICATE, theChallenge);
    } else {
        for (DigestAlgorithm current : supportedAlgorithms) {
            responseHeader.add(WWW_AUTHENTICATE, String.format(theChallenge, current.getToken()));
        }
    }

    return new ChallengeResult(true, UNAUTHORIZED);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:37,代码来源:DigestAuthenticationMechanism.java


示例32: sendAuthenticationInfoHeader

import io.undertow.util.Headers; //导入依赖的package包/类
public void sendAuthenticationInfoHeader(final HttpServerExchange exchange) {
    DigestContext context = exchange.getAttachment(DigestContext.ATTACHMENT_KEY);
    DigestQop qop = context.getQop();
    String currentNonce = context.getNonce();
    String nextNonce = nonceManager.nextNonce(currentNonce, exchange);
    if (qop != null || !nextNonce.equals(currentNonce)) {
        StringBuilder sb = new StringBuilder();
        sb.append(NEXT_NONCE).append("=\"").append(nextNonce).append("\"");
        if (qop != null) {
            Map<DigestAuthorizationToken, String> parsedHeader = context.getParsedHeader();
            sb.append(",").append(Headers.QOP.toString()).append("=\"").append(qop.getToken()).append("\"");
            byte[] ha1 = context.getHa1();
            byte[] ha2;

            if (qop == DigestQop.AUTH) {
                ha2 = createHA2Auth(context);
            } else {
                ha2 = createHA2AuthInt();
            }
            String rspauth = new String(createRFC2617RequestDigest(ha1, ha2, context), UTF_8);
            sb.append(",").append(Headers.RESPONSE_AUTH.toString()).append("=\"").append(rspauth).append("\"");
            sb.append(",").append(Headers.CNONCE.toString()).append("=\"").append(parsedHeader.get(DigestAuthorizationToken.CNONCE)).append("\"");
            sb.append(",").append(Headers.NONCE_COUNT.toString()).append("=").append(parsedHeader.get(DigestAuthorizationToken.NONCE_COUNT));
        }

        HeaderMap responseHeader = exchange.getResponseHeaders();
        responseHeader.add(AUTHENTICATION_INFO, sb.toString());
    }

    exchange.removeAttachment(DigestContext.ATTACHMENT_KEY);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:32,代码来源:DigestAuthenticationMechanism.java


示例33: resolve

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public boolean resolve(final HttpServerExchange value) {
    final String length = value.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH);
    if (length == null) {
        return false;
    }
    return Long.parseLong(length) > maxSize;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:9,代码来源:MaxContentSizePredicate.java


示例34: getCharacterEncoding

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public String getCharacterEncoding() {
    if (characterEncoding != null) {
        return characterEncoding.name();
    }
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType == null) {
        return null;
    }
    return Headers.extractQuotedValueFromHeader(contentType, "charset");
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:12,代码来源:HttpServletRequestImpl.java


示例35: getContentLengthLong

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public long getContentLengthLong() {
    final String contentLength = getHeader(Headers.CONTENT_LENGTH);
    if (contentLength == null || contentLength.isEmpty()) {
        return -1;
    }
    return Long.parseLong(contentLength);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:9,代码来源:HttpServletRequestImpl.java


示例36: getLocales

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public Enumeration<Locale> getLocales() {
    final List<String> acceptLanguage = exchange.getRequestHeaders().get(Headers.ACCEPT_LANGUAGE);
    List<Locale> ret = LocaleUtils.getLocalesFromHeader(acceptLanguage);
    if(ret.isEmpty()) {
        return new IteratorEnumeration<>(Collections.singletonList(Locale.getDefault()).iterator());
    }
    return new IteratorEnumeration<>(ret.iterator());
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:10,代码来源:HttpServletRequestImpl.java


示例37: addHeader

import io.undertow.util.Headers; //导入依赖的package包/类
public void addHeader(final HttpString name, final String value) {
    if(name == null) {
        throw UndertowServletMessages.MESSAGES.headerNameWasNull();
    }
    if (insideInclude || ignoredFlushPerformed || treatAsCommitted) {
        return;
    }
    if(name.equals(Headers.CONTENT_TYPE) && !exchange.getResponseHeaders().contains(Headers.CONTENT_TYPE)) {
        setContentType(value);
    } else {
        exchange.getResponseHeaders().add(name, value);
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:14,代码来源:HttpServletResponseImpl.java


示例38: setCharacterEncoding

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void setCharacterEncoding(final String charset) {
    if (insideInclude || responseStarted() || writer != null || isCommitted()) {
        return;
    }
    charsetSet = true;
    this.charset = charset;
    if (contentType != null) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, getContentType());
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:12,代码来源:HttpServletResponseImpl.java


示例39: setContentLength

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void setContentLength(final int len) {
    if (insideInclude || responseStarted()) {
        return;
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, Integer.toString(len));
    this.contentLength = (long) len;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:9,代码来源:HttpServletResponseImpl.java


示例40: setContentLengthLong

import io.undertow.util.Headers; //导入依赖的package包/类
@Override
public void setContentLengthLong(final long len) {
    if (insideInclude || responseStarted()) {
        return;
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, Long.toString(len));
    this.contentLength = len;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:9,代码来源:HttpServletResponseImpl.java



注:本文中的io.undertow.util.Headers类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。