io.undertow.util.HeaderMap Java Examples

The following examples show how to use io.undertow.util.HeaderMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CorsHttpHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void setCorsResponseHeaders(HttpServerExchange exchange) throws Exception {
    HeaderMap headers = exchange.getRequestHeaders();
    if (headers.contains(Headers.ORIGIN)) {
        if(matchOrigin(exchange, allowedOrigins) != null) {
            exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_ORIGIN, headers.get(Headers.ORIGIN));
            exchange.getResponseHeaders().add(Headers.VARY, Headers.ORIGIN_STRING);
        }
    }
    HeaderValues requestedMethods = headers.get(ACCESS_CONTROL_REQUEST_METHOD);
    if (requestedMethods != null && !requestedMethods.isEmpty()) {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, requestedMethods);
    } else {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, Arrays.asList(new String[]{Methods.GET_STRING, Methods.POST_STRING}));
    }
    HeaderValues requestedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS);
    if (requestedHeaders != null && !requestedHeaders.isEmpty()) {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
    } else {
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.CONTENT_TYPE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.WWW_AUTHENTICATE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.AUTHORIZATION_STRING);
    }
    exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    exchange.getResponseHeaders().add(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS);
}
 
Example #2
Source File: CorsUtilTest.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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");
    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"));
}
 
Example #3
Source File: CorsUtilTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #4
Source File: Http2DataStreamSinkChannel.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private HpackEncoder.State encodeContinuationFrame(HeaderMap headers, PooledByteBuffer current) {
    ByteBuffer currentBuffer;
    HpackEncoder.State result;//continuation frame
    //note that if the buffers are small we may not actually need a continuation here
    //but it greatly reduces the code complexity
    //back fill the length
    currentBuffer = current.getBuffer();
    currentBuffer.put((byte) 0);
    currentBuffer.put((byte) 0);
    currentBuffer.put((byte) 0);
    currentBuffer.put((byte) Http2Channel.FRAME_TYPE_CONTINUATION); //type
    currentBuffer.put((byte) 0); //back fill the flags
    Http2ProtocolUtils.putInt(currentBuffer, getStreamId());
    result = encoder.encode(headers, currentBuffer);
    int contFrameLength = currentBuffer.position() - 9;
    currentBuffer.put(0, (byte) ((contFrameLength >> 16) & 0xFF));
    currentBuffer.put(1, (byte) ((contFrameLength >> 8) & 0xFF));
    currentBuffer.put(2, (byte) (contFrameLength & 0xFF));
    currentBuffer.put(4, (byte) (result == HpackEncoder.State.COMPLETE ? Http2Channel.HEADERS_FLAG_END_HEADERS : 0 )); //flags
    return result;
}
 
Example #5
Source File: OpenApiHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
public static Map<String, ?> getHeaderParameters(final HttpServerExchange exchange, final boolean deserializedValueOnly){
	Map<String, Object> deserializedHeaderParamters = exchange.getAttachment(DESERIALIZED_HEADER_PARAMETERS);
	
	if (!deserializedValueOnly) {
		HeaderMap headers = exchange.getRequestHeaders();
		
		if (null==headers) {
			return Collections.emptyMap();
		}
		
		Map<String, HeaderValues> headerMap = new HashMap<>();
		
		for (HttpString headerName: headers.getHeaderNames()) {
			headerMap.put(headerName.toString(), headers.get(headerName));
		}
		
		return mergeMaps(deserializedHeaderParamters, headerMap);
	}
	
	return nonNullMap(deserializedHeaderParamters);
}
 
Example #6
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void writeResponse(final HttpServerExchange exchange, final int status, ModelNode response,
        OperationParameter operationParameter) {

    exchange.setStatusCode(status);

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    final String contentType = operationParameter.isEncode() ? Common.APPLICATION_DMR_ENCODED : Common.APPLICATION_JSON;
    responseHeaders.put(Headers.CONTENT_TYPE, contentType + "; charset=" + Common.UTF_8);

    writeCacheHeaders(exchange, status, operationParameter);

    if (operationParameter.isGet() && status == 200) {
        // For GET request the response is purely the model nodes result. The outcome
        // is not send as part of the response but expressed with the HTTP status code.
        response = response.get(RESULT);
    }
    try {
        byte[] data = getResponseBytes(response, operationParameter);
        responseHeaders.put(Headers.CONTENT_LENGTH, data.length);
        exchange.getResponseSender().send(ByteBuffer.wrap(data));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: UndertowResponseWriter.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext) throws ContainerException {
    if (error != null) {
        exchange.setStatusCode(500);
        exchange.getResponseHeaders().add(new HttpString("Content-Type"), "text/plain");
        exchange.getResponseSender().send(Exceptions.stackTrace(error));
        return null;
    } else {
        exchange.startBlocking();
        exchange.setStatusCode(responseContext.getStatus());
        HeaderMap responseHeaders = exchange.getResponseHeaders();
        responseContext.getStringHeaders().forEach((key, value) -> {
            for (String v : value) {
                responseHeaders.add(new HttpString(key), v);
            }
        });
        exchange.setResponseContentLength(contentLength);
        return exchange.getOutputStream();
    }
}
 
Example #8
Source File: CorsHttpHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
private void setCorsResponseHeaders(HttpServerExchange exchange) throws Exception {
    HeaderMap headers = exchange.getRequestHeaders();
    if (headers.contains(Headers.ORIGIN)) {
        if(matchOrigin(exchange, allowedOrigins) != null) {
            exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_ORIGIN, headers.get(Headers.ORIGIN));
            exchange.getResponseHeaders().add(Headers.VARY, Headers.ORIGIN_STRING);
        }
    }
    exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, allowedMethods);
    HeaderValues requestedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS);
    if (requestedHeaders != null && !requestedHeaders.isEmpty()) {
        exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
    } else {
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.CONTENT_TYPE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.WWW_AUTHENTICATE_STRING);
        exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.AUTHORIZATION_STRING);
    }
    exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    exchange.getResponseHeaders().add(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS);
}
 
Example #9
Source File: Http2Channel.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public synchronized Http2HeadersStreamSinkChannel sendPushPromise(int associatedStreamId, HeaderMap requestHeaders, HeaderMap responseHeaders) throws IOException {
    if (!isOpen()) {
        throw UndertowMessages.MESSAGES.channelIsClosed();
    }
    if (isClient()) {
        throw UndertowMessages.MESSAGES.pushPromiseCanOnlyBeCreatedByServer();
    }
    sendConcurrentStreamsAtomicUpdater.incrementAndGet(this);
    if(sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams) {
        throw UndertowMessages.MESSAGES.streamLimitExceeded();
    }
    int streamId = streamIdCounter;
    streamIdCounter += 2;
    Http2PushPromiseStreamSinkChannel pushPromise = new Http2PushPromiseStreamSinkChannel(this, requestHeaders, associatedStreamId, streamId);
    flushChannel(pushPromise);

    Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel(this, streamId, responseHeaders);
    currentStreams.put(streamId, new StreamHolder(http2SynStreamStreamSinkChannel));
    return http2SynStreamStreamSinkChannel;
}
 
Example #10
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: SymjaServer.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
	String jsonStr;
	HeaderMap responseHeaders = exchange.getResponseHeaders();
	responseHeaders.put(new HttpString("Access-Control-Allow-Origin"), "*");
	responseHeaders.put(Headers.CONTENT_TYPE, "application/json");

	Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();
	String appid = getAppID(queryParameters, "appid");
	if (appid != null) {
		if (appid.equals("DEMO")) {
			String inputStr = SymjaServer.getParam(queryParameters, "input", "i", "");
			String[] formformatStrs = SymjaServer.getParams(queryParameters, "format", "f", Pods.PLAIN_STR);
			int formats = Pods.internFormat(formformatStrs);
			ObjectNode messageJSON = Pods.createResult(inputStr, formats);
			jsonStr = messageJSON.toString();
		} else {
			jsonStr = Pods.errorJSONString("1", "Invalid appid");
		}
	} else {
		jsonStr = Pods.errorJSONString("2", "Appid missing");
	}
	exchange.getResponseSender().send(jsonStr);
}
 
Example #12
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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().getByteBufferPool(), 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));
    }
}
 
Example #13
Source File: RequestTimeLogger.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
    try {
        long end = System.currentTimeMillis();
        long duration = end - start;
        if (duration > this.timeThreshold) {
            String method = exchange.getRequestMethod().toString();
            String query = exchange.getQueryString();
            String request_url = exchange.getRequestURI() + (query.isEmpty() ? "" : ("?" + query));
            HeaderMap headers = exchange.getRequestHeaders();
            if (headers.contains(tenantHeader)) {
                String tenantId = headers.get(tenantHeader, 0);
                log.warnf("Request %s %s took: %d ms, exceeds %d ms threshold, tenant-id: %s",
                        method, request_url, duration, timeThreshold, tenantId);
            } else {
                log.warnf("Request %s %s took: %d ms, exceeds %d ms threshold, no tenant",
                        method, request_url, duration, timeThreshold);
            }

        }
    } finally {
        if (nextListener != null) {
            nextListener.proceed();
        }
    }
}
 
Example #14
Source File: HeaderLogParamTest.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
@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]");
}
 
Example #15
Source File: MultiPartParserDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void beginPart(final HeaderMap headers) {
    this.currentFileSize = 0;
    this.headers = headers;
    final String disposition = headers.getFirst(Headers.CONTENT_DISPOSITION);
    if (disposition != null) {
        if (disposition.startsWith("form-data")) {
            currentName = Headers.extractQuotedValueFromHeader(disposition, "name");
            fileName = Headers.extractQuotedValueFromHeaderWithEncoding(disposition, "filename");
            if (fileName != null) {
                try {
                    if (tempFileLocation != null) {
                        file = Files.createTempFile(tempFileLocation, "undertow", "upload");
                    } else {
                        file = Files.createTempFile("undertow", "upload");
                    }
                    createdFiles.add(file);
                    fileChannel = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
 
Example #16
Source File: Http2Channel.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a strema using a HEADERS frame
 *
 * @param requestHeaders
 * @return
 * @throws IOException
 */
public synchronized Http2HeadersStreamSinkChannel createStream(HeaderMap requestHeaders) throws IOException {
    if (!isClient()) {
        throw UndertowMessages.MESSAGES.headersStreamCanOnlyBeCreatedByClient();
    }
    if (!isOpen()) {
        throw UndertowMessages.MESSAGES.channelIsClosed();
    }
    sendConcurrentStreamsAtomicUpdater.incrementAndGet(this);
    if(sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams) {
        throw UndertowMessages.MESSAGES.streamLimitExceeded();
    }
    int streamId = streamIdCounter;
    streamIdCounter += 2;
    Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel(this, streamId, requestHeaders);
    currentStreams.put(streamId, new StreamHolder(http2SynStreamStreamSinkChannel));

    return http2SynStreamStreamSinkChannel;
}
 
Example #17
Source File: HttpServletResponseImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setTrailerFields(Supplier<Map<String, String>> supplier) {
    if(exchange.isResponseStarted()) {
        throw UndertowServletMessages.MESSAGES.responseAlreadyCommited();
    }
    if(exchange.getProtocol() == Protocols.HTTP_1_0) {
        throw UndertowServletMessages.MESSAGES.trailersNotSupported("HTTP/1.0 request");
    } else if(exchange.getProtocol() == Protocols.HTTP_1_1) {
        if(exchange.getResponseHeaders().contains(Headers.CONTENT_LENGTH)) {
            throw UndertowServletMessages.MESSAGES.trailersNotSupported("not chunked");
        }
    }
    this.trailerSupplier = supplier;
    exchange.putAttachment(HttpAttachments.RESPONSE_TRAILER_SUPPLIER, () -> {
        HeaderMap trailers = new HeaderMap();
        Map<String, String> map = supplier.get();
        for(Map.Entry<String, String> e : map.entrySet()) {
            trailers.put(new HttpString(e.getKey()), e.getValue());
        }
        return trailers;
    });
}
 
Example #18
Source File: CorsHandler.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
/** Statically allows headers used by the api */
void handlePreflight(HttpServerExchange exchange) {
  HeaderMap requestHeaders = exchange.getRequestHeaders();
  String origin = requestHeaders.getFirst(ORIGIN);
  String method = requestHeaders.getFirst(ACCESS_CONTROL_REQUEST_METHOD);
  String requestedHeaders = requestHeaders.getFirst(ACCESS_CONTROL_REQUEST_HEADERS);
  HeaderMap responseHeaders = exchange.getResponseHeaders();

  responseHeaders.put(VARY,
    "origin,access-control-request-method,access-control-request-headers");
  if (
    ("POST".equals(method) || "GET".equals(method))
      && requestedHeadersAllowed(requestedHeaders)
      && setOrigin(origin, responseHeaders)
    ) {
    responseHeaders.put(ACCESS_CONTROL_ALLOW_METHODS, method);
    if (requestedHeaders != null) {
      responseHeaders.put(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
    }
  }
}
 
Example #19
Source File: TracingHandlerTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private HttpServerExchange buildExchange() {
    HeaderMap requestHeaders = new HeaderMap();
    HeaderMap responseHeaders = new HeaderMap();
    HttpServerExchange exchange = new HttpServerExchange(serverConnection, requestHeaders, responseHeaders, 0);
    exchange.setRequestURI(uri);
    exchange.setRequestPath(uri);
    exchange.setDestinationAddress(new InetSocketAddress("localhost", 8080));
    exchange.setRequestScheme("http");
    exchange.setRequestMethod(Methods.GET);
    return exchange;
}
 
Example #20
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static void writeCacheHeaders(final HttpServerExchange exchange, final int status, final OperationParameter operationParameter) {
    final HeaderMap responseHeaders = exchange.getResponseHeaders();

    // No need to send this in a 304
    // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
    if (operationParameter.getMaxAge() > 0 && status != 304) {
        responseHeaders.put(Headers.CACHE_CONTROL, "max-age=" + operationParameter.getMaxAge() + ", private, must-revalidate");
    }
    if (operationParameter.getEtag() != null) {
        responseHeaders.put(Headers.ETAG, operationParameter.getEtag().toString());
    }
}
 
Example #21
Source File: AjpClientRequestClientStreamSinkChannel.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
AjpClientRequestClientStreamSinkChannel(AjpClientChannel channel, ChannelListener<AjpClientRequestClientStreamSinkChannel> finishListener, HeaderMap headers, String path, HttpString method, HttpString protocol, Attachable attachable) {
    super(channel);
    this.finishListener = finishListener;
    this.headers = headers;
    this.path = path;
    this.method = method;
    this.protocol = protocol;
    this.attachable = attachable;
}
 
Example #22
Source File: StaticHeadersHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void apply(HttpServerExchange exchange, Predicate<String> putHeader) {
    HeaderMap headers = exchange.getResponseHeaders();
    if (putHeader.test(headerName.toString())) {
        headers.put(headerName, value);
    } else {
        headers.add(headerName, value);
    }
}
 
Example #23
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static void copyHeaders(final HeaderMap to, final HeaderMap from) {
    long f = from.fastIterateNonEmpty();
    HeaderValues values;
    while (f != -1L) {
        values = from.fiCurrent(f);
        if(!to.contains(values.getHeaderName())) {
            //don't over write existing headers, normally the map will be empty, if it is not we assume it is not for a reason
            to.putAll(values.getHeaderName(), values);
        }
        f = from.fiNextNonEmpty(f);
    }
}
 
Example #24
Source File: RequestUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsJsonRequest() {
    // given
    HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);
    HeaderMap headerMap = new HeaderMap();
    headerMap.put(Header.CONTENT_TYPE.toHttpString(), MediaType.JSON_UTF_8.withoutParameters().toString());

    // when
    when(mockedExchange.getRequestHeaders()).thenReturn(headerMap);
    boolean isJson = RequestUtils.isJsonRequest(mockedExchange);

    // then
    assertThat(isJson, equalTo(true));
}
 
Example #25
Source File: ChunkedStreamSinkConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a new instance.
 *
 * @param next            the channel to wrap
 * @param configurable    {@code true} to allow configuration of the next channel, {@code false} otherwise
 * @param passClose       {@code true} to close the underlying channel when this channel is closed, {@code false} otherwise
 * @param responseHeaders The response headers
 * @param finishListener  The finish listener
 * @param attachable      The attachable
 */
public ChunkedStreamSinkConduit(final StreamSinkConduit next, final ByteBufferPool bufferPool, final boolean configurable, final boolean passClose, HeaderMap responseHeaders, final ConduitListener<? super ChunkedStreamSinkConduit> finishListener, final Attachable attachable) {
    super(next);
    this.bufferPool = bufferPool;
    this.responseHeaders = responseHeaders;
    this.finishListener = finishListener;
    this.attachable = attachable;
    config = (configurable ? CONF_FLAG_CONFIGURABLE : 0) | (passClose ? CONF_FLAG_PASS_CLOSE : 0);
    chunkingSepBuffer = ByteBuffer.allocate(2);
    chunkingSepBuffer.flip();
}
 
Example #26
Source File: FormData.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void put(String name, String value, final HeaderMap headers) {
    Deque<FormValue> values = new ArrayDeque<>(1);
    Deque<FormValue> old = this.values.put(name, values);
    if (old != null) {
        valueCount -= old.size();
    }
    values.add(new FormValueImpl(value, headers));

    if (++valueCount > maxValues) {
        throw new RuntimeException(UndertowMessages.MESSAGES.tooManyParameters(maxValues));
    }
}
 
Example #27
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private void logHeaders(HeaderMap headers) {
    for (HeaderValues header : headers) {
        HttpString name = header.getHeaderName();
        if (!Headers.COOKIE.equals(name)) {
            logger.debug("[request:header] {}={}", name, new HeaderLogParam(name, header));
        }
    }
}
 
Example #28
Source File: LearningPushHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
    if (exchange.getStatusCode() == 200 && referer != null) {
        //for now only cache 200 response codes
        String lmString = exchange.getResponseHeaders().getFirst(Headers.LAST_MODIFIED);
        String etag = exchange.getResponseHeaders().getFirst(Headers.ETAG);
        long lastModified = -1;
        if(lmString != null) {
            Date dt = DateUtils.parseDate(lmString);
            if(dt != null) {
                lastModified = dt.getTime();
            }
        }
        Map<String, PushedRequest> pushes = cache.get(referer);
        if(pushes == null) {
            synchronized (cache) {
                pushes = cache.get(referer);
                if(pushes == null) {
                    cache.add(referer, pushes = Collections.synchronizedMap(new HashMap<String, PushedRequest>()));
                }
            }
        }
        pushes.put(fullPath, new PushedRequest(new HeaderMap(), requestPath, etag, lastModified));
    }

    nextListener.proceed();
}
 
Example #29
Source File: OpenApiHttpHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private static void addCorsResponseHeaders(HttpServerExchange exchange) {
    HeaderMap headerMap = exchange.getResponseHeaders();
    headerMap.put(new HttpString("Access-Control-Allow-Origin"), "*");
    headerMap.put(new HttpString("Access-Control-Allow-Credentials"), "true");
    headerMap.put(new HttpString("Access-Control-Allow-Methods"), ALLOWED_METHODS);
    headerMap.put(new HttpString("Access-Control-Allow-Headers"), "Content-Type, Authorization");
    headerMap.put(new HttpString("Access-Control-Max-Age"), "86400");
}
 
Example #30
Source File: GZipPredicateTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void skipIfContentLengthIsTooSmall() {
    var headers = new HeaderMap();
    headers.put(Headers.CONTENT_TYPE, ContentType.TEXT_PLAIN.toString());
    headers.put(Headers.CONTENT_LENGTH, 10);
    assertThat(predicate.resolve(headers)).isFalse();
}