use of io.undertow.util.HttpString in project undertow by undertow-io.
the class HTTP2ViaUpgradeTestCase method setup.
@BeforeClass
public static void setup() throws URISyntaxException {
final SessionCookieConfig sessionConfig = new SessionCookieConfig();
int port = DefaultServer.getHostPort("default");
server = Undertow.builder().addHttpListener(port + 1, DefaultServer.getHostAddress("default")).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(Handlers.header(new Http2UpgradeHandler(new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (!(exchange.getConnection() instanceof Http2ServerConnection)) {
throw new RuntimeException("Not HTTP2");
}
exchange.getResponseHeaders().add(new HttpString("X-Custom-Header"), "foo");
exchange.getResponseSender().send(message);
}
}, "h2c", "h2c-17"), Headers.SEC_WEB_SOCKET_ACCEPT_STRING, //work around Netty bug, it assumes that every upgrade request that does not have this header is an old style websocket upgrade
"fake")).build();
server.start();
}
use of io.undertow.util.HttpString in project undertow by undertow-io.
the class URLRewritingSessionTestCase method setup.
@BeforeClass
public static void setup() {
final PathParameterSessionConfig sessionConfig = new PathParameterSessionConfig();
final SessionAttachmentHandler handler = new SessionAttachmentHandler(new InMemorySessionManager(""), sessionConfig);
handler.setNext(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
Session session = manager.getSession(exchange, sessionConfig);
if (session == null) {
session = manager.createSession(exchange, sessionConfig);
session.setAttribute(COUNT, 0);
} else {
Assert.assertEquals("/notamatchingpath;jsessionid=" + session.getId(), exchange.getRequestURI());
}
Integer count = (Integer) session.getAttribute(COUNT);
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
for (Map.Entry<String, Deque<String>> qp : exchange.getQueryParameters().entrySet()) {
exchange.getResponseHeaders().add(new HttpString(qp.getKey()), qp.getValue().getFirst());
}
if (exchange.getQueryString().isEmpty()) {
exchange.getResponseSender().send(sessionConfig.rewriteUrl(DefaultServer.getDefaultServerURL() + "/notamatchingpath", session.getId()));
} else {
exchange.getResponseSender().send(sessionConfig.rewriteUrl(DefaultServer.getDefaultServerURL() + "/notamatchingpath?" + exchange.getQueryString(), session.getId()));
}
}
});
DefaultServer.setRootHandler(handler);
}
use of io.undertow.util.HttpString in project undertow by undertow-io.
the class MCMPHandler method handleRequest.
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
final HttpString method = exchange.getRequestMethod();
if (!handlesMethod(method)) {
next.handleRequest(exchange);
return;
}
/*
* Proxy the request that needs to be proxied and process others
*/
// TODO maybe this should be handled outside here?
final InetSocketAddress addr = exchange.getConnection().getLocalAddress(InetSocketAddress.class);
if (!addr.isUnresolved() && addr.getPort() != config.getManagementSocketAddress().getPort() || !Arrays.equals(addr.getAddress().getAddress(), config.getManagementSocketAddress().getAddress().getAddress())) {
next.handleRequest(exchange);
return;
}
if (exchange.isInIoThread()) {
//for now just do all the management stuff in a worker, as it uses blocking IO
exchange.dispatch(this);
return;
}
try {
handleRequest(method, exchange);
} catch (Exception e) {
UndertowLogger.ROOT_LOGGER.failedToProcessManagementReq(e);
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
final Sender sender = exchange.getResponseSender();
sender.send("failed to process management request");
}
}
use of io.undertow.util.HttpString in project undertow by undertow-io.
the class SavedRequest method tryRestoreRequest.
public static void tryRestoreRequest(final HttpServerExchange exchange, HttpSession session) {
if (session instanceof HttpSessionImpl) {
Session underlyingSession;
if (System.getSecurityManager() == null) {
underlyingSession = ((HttpSessionImpl) session).getSession();
} else {
underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
}
SavedRequest request = (SavedRequest) underlyingSession.getAttribute(SESSION_KEY);
if (request != null) {
if (request.requestPath.equals(exchange.getRelativePath()) && exchange.isRequestComplete()) {
UndertowLogger.REQUEST_LOGGER.debugf("restoring request body for request to %s", request.requestPath);
exchange.setRequestMethod(request.method);
Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(request.data, 0, request.dataLength)));
underlyingSession.removeAttribute(SESSION_KEY);
//clear the existing header map of everything except the connection header
//TODO: are there other headers we should preserve?
Iterator<HeaderValues> headerIterator = exchange.getRequestHeaders().iterator();
while (headerIterator.hasNext()) {
HeaderValues header = headerIterator.next();
if (!header.getHeaderName().equals(Headers.CONNECTION)) {
headerIterator.remove();
}
}
for (Map.Entry<HttpString, List<String>> header : request.headerMap.entrySet()) {
exchange.getRequestHeaders().putAll(header.getKey(), header.getValue());
}
}
}
}
}
use of io.undertow.util.HttpString in project undertow by undertow-io.
the class HttpClientConnection method initiateRequest.
private void initiateRequest(HttpClientExchange httpClientExchange) {
this.requestCount++;
currentRequest = httpClientExchange;
pendingResponse = new HttpResponseBuilder();
ClientRequest request = httpClientExchange.getRequest();
String connectionString = request.getRequestHeaders().getFirst(CONNECTION);
if (connectionString != null) {
HttpString connectionHttpString = new HttpString(connectionString);
if (connectionHttpString.equals(CLOSE)) {
state |= CLOSE_REQ;
} else if (connectionHttpString.equals(UPGRADE)) {
state |= UPGRADE_REQUESTED;
}
} else if (request.getProtocol() != Protocols.HTTP_1_1) {
state |= CLOSE_REQ;
}
if (request.getRequestHeaders().contains(UPGRADE)) {
state |= UPGRADE_REQUESTED;
}
if (request.getMethod().equals(Methods.CONNECT)) {
//we treat CONNECT like upgrade requests
state |= UPGRADE_REQUESTED;
}
//setup the client request conduits
final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel();
sourceChannel.setReadListener(clientReadListener);
sourceChannel.resumeReads();
ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel();
StreamSinkConduit conduit = originalSinkConduit;
conduit = new HttpRequestConduit(conduit, bufferPool, request);
String fixedLengthString = request.getRequestHeaders().getFirst(CONTENT_LENGTH);
String transferEncodingString = request.getRequestHeaders().getLast(TRANSFER_ENCODING);
boolean hasContent = true;
if (fixedLengthString != null) {
try {
long length = Long.parseLong(fixedLengthString);
conduit = new ClientFixedLengthStreamSinkConduit(conduit, length, false, false, currentRequest);
hasContent = length != 0;
} catch (NumberFormatException e) {
handleError(new IOException(e));
return;
}
} else if (transferEncodingString != null) {
if (!transferEncodingString.toLowerCase(Locale.ENGLISH).contains(Headers.CHUNKED.toString())) {
handleError(UndertowClientMessages.MESSAGES.unknownTransferEncoding(transferEncodingString));
return;
}
conduit = new ChunkedStreamSinkConduit(conduit, httpClientExchange.getConnection().getBufferPool(), false, false, httpClientExchange.getRequest().getRequestHeaders(), requestFinishListener, httpClientExchange);
} else {
conduit = new ClientFixedLengthStreamSinkConduit(conduit, 0, false, false, currentRequest);
hasContent = false;
}
sinkChannel.setConduit(conduit);
httpClientExchange.invokeReadReadyCallback();
if (!hasContent) {
//otherwise it is up to the user
try {
sinkChannel.shutdownWrites();
if (!sinkChannel.flush()) {
sinkChannel.setWriteListener(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<ConduitStreamSinkChannel>() {
@Override
public void handleException(ConduitStreamSinkChannel channel, IOException exception) {
handleError(exception);
}
}));
sinkChannel.resumeWrites();
}
} catch (IOException e) {
handleError(e);
}
}
}
Aggregations