repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/Http1xResponseHandler.java
http/src/main/java/io/hyperfoil/http/connection/Http1xResponseHandler.java
package io.hyperfoil.http.connection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.HttpResponseHandlers; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.AsciiString; import io.netty.util.ByteProcessor; import io.netty.util.CharsetUtil; public class Http1xResponseHandler extends BaseResponseHandler { private static final Logger log = LogManager.getLogger(Http1xResponseHandler.class); private static final boolean trace = log.isTraceEnabled(); private static final byte CR = 13; private static final byte LF = 10; private static final int MAX_LINE_LENGTH = 4096; private State state = State.STATUS; private boolean crRead = false; private int contentLength = -1; private ByteBuf lastLine; private int status = 0; private boolean chunked = false; private int skipChunkBytes; private enum State { STATUS, HEADERS, BODY, TRAILERS } Http1xResponseHandler(HttpConnection connection) { super(connection); } @Override protected boolean isRequestStream(int streamId) { return true; } @Override public void handlerAdded(ChannelHandlerContext ctx) { if (lastLine == null) { lastLine = ctx.alloc().buffer(MAX_LINE_LENGTH); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (lastLine != null) { lastLine.release(); lastLine = null; } super.channelInactive(ctx); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (lastLine != null) { lastLine.release(); lastLine = null; } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; int readerIndex = buf.readerIndex(); while (true) { switch (state) { case STATUS: readerIndex = readStatus(ctx, buf, readerIndex); break; case HEADERS: readerIndex = readHeaders(ctx, buf, readerIndex); break; case BODY: readerIndex = readBody(ctx, buf, readerIndex); break; case TRAILERS: readerIndex = readTrailers(ctx, buf, readerIndex); break; } if (readerIndex < 0) { return; } } } else { log.error("Unexpected message type: {}", msg); super.channelRead(ctx, msg); } } private int readStatus(ChannelHandlerContext ctx, ByteBuf buf, int readerIndex) { int lineStartIndex = buf.readerIndex(); for (; readerIndex < buf.writerIndex(); ++readerIndex) { byte val = buf.getByte(readerIndex); if (val == CR) { crRead = true; } else if (val == LF && crRead) { crRead = false; ByteBuf lineBuf = buf; if (lastLine.isReadable()) { assert lineStartIndex == buf.readerIndex(); copyLastLine(buf, lineStartIndex, readerIndex); lineBuf = lastLine; lineStartIndex = 0; } // skip HTTP version int j = lineStartIndex; for (; j < lineBuf.writerIndex(); ++j) { if (lineBuf.getByte(j) == ' ') { break; } } status = readDecNumber(lineBuf, j); if (status >= 100 && status < 200 || status == 204 || status == 304) { contentLength = 0; } onStatus(status); state = State.HEADERS; lastLine.writerIndex(0); return readerIndex + 1; } else { crRead = false; } } copyLastLine(buf, lineStartIndex, readerIndex); passFullBuffer(ctx, buf); return -1; } private int readHeaders(ChannelHandlerContext ctx, ByteBuf buf, int readerIndex) throws Exception { int lineStartIndex = readerIndex; int lineEndIndex; for (; readerIndex < buf.writerIndex();) { if (!crRead) { final int indexOfCr = buf.indexOf(readerIndex, buf.writerIndex(), CR); if (indexOfCr == -1) { readerIndex = buf.writerIndex(); break; } crRead = true; readerIndex = indexOfCr + 1; } else { byte val = buf.getByte(readerIndex); if (val == LF) { crRead = false; ByteBuf lineBuf; // lineStartIndex is valid only if lastLine is empty - otherwise we would ignore an incomplete line // in the buffer if (readerIndex - lineStartIndex == 1 && lastLine.writerIndex() == 0 || lastLine.writerIndex() == 1 && readerIndex == buf.readerIndex()) { // empty line ends the headers HttpRequest httpRequest = connection.peekRequest(0); // Unsolicited response 408 may not have a matching request if (httpRequest != null) { switch (httpRequest.method) { case HEAD: case CONNECT: contentLength = 0; chunked = false; } } state = State.BODY; lastLine.writerIndex(0); if (contentLength >= 0) { responseBytes = readerIndex - buf.readerIndex() + contentLength + 1; } return readerIndex + 1; } else if (lastLine.isReadable()) { copyLastLine(buf, lineStartIndex, readerIndex); lineBuf = lastLine; lineEndIndex = lastLine.readableBytes() + readerIndex - lineStartIndex - 1; // account the CR lineStartIndex = 0; } else { lineBuf = buf; lineEndIndex = readerIndex - 1; // account the CR } int endOfNameIndex = lineEndIndex, startOfValueIndex = lineStartIndex; final int indexOfColon = lineBuf.indexOf(lineStartIndex, lineEndIndex, (byte) ':'); if (indexOfColon != -1) { final int i = indexOfColon; // skip the trailing whitespaces of the header name for (endOfNameIndex = i - 1; endOfNameIndex >= lineStartIndex && lineBuf.getByte(endOfNameIndex) == ' '; --endOfNameIndex) ; // skip the leading whitespaces of the header value for (startOfValueIndex = i + 1; startOfValueIndex < lineEndIndex && lineBuf.getByte(startOfValueIndex) == ' '; ++startOfValueIndex) ; int nameLength = (endOfNameIndex + 1) - lineStartIndex; switch (nameLength) { case 14: if (equalsIgnoreMatches(lineBuf, lineStartIndex, HttpHeaderNames.CONTENT_LENGTH)) { contentLength = readDecNumber(lineBuf, startOfValueIndex); } break; case 17: if (equalsIgnoreMatches(lineBuf, lineStartIndex, HttpHeaderNames.TRANSFER_ENCODING)) { chunked = equalsIgnoreMatches(lineBuf, startOfValueIndex, HttpHeaderValues.CHUNKED); skipChunkBytes = 0; } break; } } onHeaderRead(lineBuf, lineStartIndex, endOfNameIndex + 1, startOfValueIndex, lineEndIndex); lastLine.writerIndex(0); lineStartIndex = readerIndex + 1; } else if (val != CR) { crRead = false; } ++readerIndex; } } copyLastLine(buf, lineStartIndex, readerIndex); passFullBuffer(ctx, buf); return -1; } private int readBody(ChannelHandlerContext ctx, ByteBuf buf, int readerIndex) throws Exception { if (chunked) { int readable = buf.writerIndex() - readerIndex; if (skipChunkBytes > readable) { int readableBody = Math.min(skipChunkBytes - 2, readable); skipChunkBytes -= readable; onBodyPart(buf, readerIndex, readableBody, false); passFullBuffer(ctx, buf); return -1; } else { // skipChunkBytes includes the CRLF onBodyPart(buf, readerIndex, skipChunkBytes - 2, false); readerIndex += skipChunkBytes; skipChunkBytes = 0; return readChunks(ctx, buf, readerIndex); } } else if (responseBytes > 0) { boolean isLastPart = buf.readableBytes() >= responseBytes; onBodyPart(buf, readerIndex, Math.min(buf.writerIndex(), buf.readerIndex() + responseBytes) - readerIndex, isLastPart); if (isLastPart) { reset(); } return handleBuffer(ctx, buf, 0) ? buf.readerIndex() : -1; } else { // Body length is unknown and it is not chunked => the request is delimited by connection close // TODO: make sure we invoke this with isLastPart=true once onBodyPart(buf, readerIndex, buf.writerIndex() - readerIndex, false); passFullBuffer(ctx, buf); return -1; } } private int readChunks(ChannelHandlerContext ctx, ByteBuf buf, int readerIndex) { int lineStartOffset = readerIndex; for (; readerIndex < buf.writerIndex(); ++readerIndex) { byte val = buf.getByte(readerIndex); if (val == CR) { crRead = true; } else if (val == LF && crRead) { try { ByteBuf lineBuf = buf; if (lastLine.isReadable()) { copyLastLine(buf, lineStartOffset, readerIndex); lineBuf = lastLine; lineStartOffset = 0; } int partSize = readHexNumber(lineBuf, lineStartOffset); if (partSize == 0) { onBodyPart(Unpooled.EMPTY_BUFFER, 0, 0, true); chunked = false; state = State.TRAILERS; return readerIndex + 1; } else if (readerIndex + 3 + partSize < buf.writerIndex()) { onBodyPart(buf, readerIndex + 1, partSize, false); readerIndex += partSize; // + 1 from for loop, +2 below if (buf.getByte(++readerIndex) != CR || buf.getByte(++readerIndex) != LF) { throw new IllegalStateException("Chunk must end with CRLF!"); } lineStartOffset = readerIndex + 1; assert skipChunkBytes == 0; } else { onBodyPart(buf, readerIndex + 1, Math.min(buf.writerIndex() - readerIndex - 1, partSize), false); skipChunkBytes = readerIndex + 3 + partSize - buf.writerIndex(); passFullBuffer(ctx, buf); return -1; } } finally { crRead = false; lastLine.writerIndex(0); } } else { crRead = false; } } copyLastLine(buf, lineStartOffset, buf.writerIndex()); passFullBuffer(ctx, buf); return -1; } private int readTrailers(ChannelHandlerContext ctx, ByteBuf buf, int readerIndex) throws Exception { int lineStartIndex = readerIndex; for (; readerIndex < buf.writerIndex(); ++readerIndex) { byte val = buf.getByte(readerIndex); if (val == CR) { crRead = true; } else if (val == LF && crRead) { if (readerIndex - lineStartIndex == 1 || lastLine.writerIndex() == 1 && readerIndex == buf.readerIndex()) { // empty line ends the trailers and whole message responseBytes = readerIndex + 1 - buf.readerIndex(); reset(); return handleBuffer(ctx, buf, 0) ? buf.readerIndex() : -1; } lineStartIndex = readerIndex + 1; } else { crRead = false; } } copyLastLine(buf, lineStartIndex, readerIndex); passFullBuffer(ctx, buf); return -1; } private void reset() { state = State.STATUS; status = 0; chunked = false; skipChunkBytes = 0; contentLength = -1; lastLine.writerIndex(0); crRead = false; } private void copyLastLine(ByteBuf buf, int lineStartOffset, int readerIndex) { // copy last line (incomplete) to lastLine int lineBytes = readerIndex - lineStartOffset; if (lastLine.writerIndex() + lineBytes > lastLine.capacity()) { throw new IllegalStateException("Too long header line."); } else if (lineBytes > 0) { buf.getBytes(lineStartOffset, lastLine, lastLine.writerIndex(), lineBytes); lastLine.writerIndex(lastLine.writerIndex() + lineBytes); } } private void passFullBuffer(ChannelHandlerContext ctx, ByteBuf buf) { HttpRequest request = connection.peekRequest(0); // Note: we cannot reliably know if this is the last part as the body might be delimited by closing the connection. onRawData(request, buf, false); onData(ctx, buf); } private static boolean equalsIgnoreMatches(ByteBuf buf, int bufOffset, AsciiString string) { if (bufOffset + string.length() > buf.writerIndex()) { return false; } for (int i = 0; i < string.length(); ++i) { if (!Util.compareIgnoreCase(buf.getByte(bufOffset + i), string.byteAt(i))) { return false; } } return true; } private int readHexNumber(ByteBuf buf, int index) { index = skipWhitespaces(buf, index); int value = 0; for (; index < buf.writerIndex(); ++index) { byte b = buf.getByte(index); int v = toHex((char) b); if (v < 0) { if (b != CR) { log.error("Error reading buffer, starting from {}, current index {} (char: {}), status {}:\n{}", buf.readerIndex(), index, b, this, ByteBufUtil.prettyHexDump(buf, buf.readerIndex(), buf.readableBytes())); throw new IllegalStateException("Part size must be followed by CRLF!"); } return value; } value = value * 16 + v; } // we expect that we've read the <CR><LF> and we should see them throw new IllegalStateException(); } private int toHex(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } else { return -1; } } private static int readDecNumber(ByteBuf buf, int index) { index = skipWhitespaces(buf, index); int value = 0; for (; index < buf.writerIndex(); ++index) { byte b = buf.getByte(index); if (b < '0' || b > '9') { return value; } value = value * 10 + (b - '0'); } // we expect that we've read the <CR><LF> and we should see them throw new IllegalStateException(); } private static int skipWhitespaces(ByteBuf buf, int index) { final int i = buf.forEachByte(index, buf.writerIndex() - index, ByteProcessor.FIND_NON_LINEAR_WHITESPACE); if (i != -1) { return i; } return buf.writerIndex(); } @Override public String toString() { return "Http1xRawBytesHandler{" + "state=" + state + ", crRead=" + crRead + ", contentLength=" + contentLength + ", status=" + status + ", chunked=" + chunked + ", skipChunkBytes=" + skipChunkBytes + '}'; } @Override protected void onData(ChannelHandlerContext ctx, ByteBuf buf) { // noop - do not send to upper layers buf.release(); } @Override protected void onStatus(int status) { HttpRequest request = connection.peekRequest(0); if (request == null) { if (HttpResponseStatus.REQUEST_TIMEOUT.code() == status) { // HAProxy sends 408 when we allocate the connection but do not use it within 10 seconds. log.debug("Closing connection {} as server timed out waiting for our first request.", connection); } else { log.error("Received unsolicited response (status {}) on {}", status, connection); } return; } if (request.isCompleted()) { log.trace("Request on connection {} has been already completed (error in handlers?), ignoring", connection); } else { HttpResponseHandlers handlers = request.handlers(); request.enter(); try { handlers.handleStatus(request, status, null); // TODO parse reason } finally { request.exit(); } request.session.proceed(); } } @Override protected void onHeaderRead(ByteBuf buf, int startOfName, int endOfName, int startOfValue, int endOfValue) { HttpRequest request = connection.peekRequest(0); if (request == null) { if (trace) { AsciiString name = Util.toAsciiString(buf, startOfName, endOfName - startOfName); String value = Util.toString(buf, startOfValue, endOfValue - startOfValue); log.trace("No request, received headers: {}: {}", name, value); } } else if (request.isCompleted()) { log.trace("Request on connection {} has been already completed (error in handlers?), ignoring", connection); } else { HttpResponseHandlers handlers = request.handlers(); if (handlers.requiresHandlingHeaders(request)) { handleHeader(buf, startOfName, endOfName, startOfValue, endOfValue, request, handlers); } request.session.proceed(); } } private static void handleHeader(ByteBuf buf, int startOfName, int endOfName, int startOfValue, int endOfValue, HttpRequest request, HttpResponseHandlers handlers) { request.enter(); try { AsciiString name = Util.toAsciiString(buf, startOfName, endOfName - startOfName); final int valueLen = endOfValue - startOfValue; // HTTP 1.1 RFC admit just latin header values, but still; better be safe and check it final CharSequence value; // Java Compact strings already perform this check, why doing it again? // AsciiString allocate the backed byte[] just once, saving to create/cache // a tmp one just to read buf content, if it won't be backed by a byte[] as well. if (Util.isAscii(buf, startOfValue, valueLen)) { value = Util.toAsciiString(buf, startOfValue, valueLen); } else { // the built-in method has the advantage vs Util.toString that the backing byte[] is cached, if ever happen value = buf.toString(startOfName, valueLen, CharsetUtil.UTF_8); } handlers.handleHeader(request, name, value); } finally { request.exit(); } } @Override protected void onBodyPart(ByteBuf buf, int startOffset, int length, boolean isLastPart) { if (length < 0 || length == 0 && !isLastPart) { return; } HttpRequest request = connection.peekRequest(0); // When previous handlers throw an error the request is already completed if (request != null && !request.isCompleted()) { HttpResponseHandlers handlers = request.handlers(); request.enter(); try { handlers.handleBodyPart(request, buf, startOffset, length, isLastPart); } finally { request.exit(); } request.session.proceed(); } } @Override protected void onCompletion(HttpRequest request) { boolean removed = false; // When previous handlers throw an error the request is already completed if (!request.isCompleted()) { request.enter(); try { request.handlers().handleEnd(request, true); if (trace) { log.trace("Completed response on {}", this); } } catch (SessionStopException e) { if (connection.removeRequest(0, request)) { ((Http1xConnection) connection).releasePoolAndPulse(); } throw e; } finally { request.exit(); } removed = connection.removeRequest(0, request); request.session.proceed(); } assert request.isCompleted(); request.release(); if (trace) { log.trace("Releasing request"); } if (removed) { ((Http1xConnection) connection).releasePoolAndPulse(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/ConnectionAllocator.java
http/src/main/java/io/hyperfoil/http/connection/ConnectionAllocator.java
package io.hyperfoil.http.connection; import java.util.Collection; import java.util.Collections; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.http.api.ConnectionConsumer; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpConnectionPool; import io.netty.channel.EventLoop; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; class ConnectionAllocator extends ConnectionPoolStats implements HttpConnectionPool { private static final Logger log = LogManager.getLogger(ConnectionAllocator.class); private final HttpClientPoolImpl clientPool; private final EventLoop eventLoop; ConnectionAllocator(HttpClientPoolImpl clientPool, EventLoop eventLoop) { super(clientPool.authority); this.clientPool = clientPool; this.eventLoop = eventLoop; } @Override public HttpClientPool clientPool() { return clientPool; } @Override public void acquire(boolean exclusiveConnection, ConnectionConsumer consumer) { log.trace("Creating connection to {}", authority); blockedSessions.incrementUsed(); clientPool.connect(this, (conn, err) -> { if (err != null) { log.error("Cannot create connection to " + authority, err); // TODO retry couple of times? blockedSessions.decrementUsed(); consumer.accept(null); } else { log.debug("Created {} to {}", conn, authority); blockedSessions.decrementUsed(); inFlight.incrementUsed(); usedConnections.incrementUsed(); incrementTypeStats(conn); conn.onAcquire(); conn.context().channel().closeFuture().addListener(v -> { conn.setClosed(); log.debug("Closed {} to {}", conn, authority); typeStats.get(tagConnection(conn)).decrementUsed(); usedConnections.decrementUsed(); }); consumer.accept(conn); } }); } @Override public void afterRequestSent(HttpConnection connection) { } @Override public int waitingSessions() { return blockedSessions.current(); } @Override public EventLoop executor() { return eventLoop; } @Override public void pulse() { } @Override public Collection<? extends HttpConnection> connections() { return Collections.emptyList(); } @Override public void release(HttpConnection connection, boolean becameAvailable, boolean afterRequest) { if (afterRequest) { decrementInFlight(); } connection.close(); } @Override public void onSessionReset() { } @Override public void start(Handler<AsyncResult<Void>> handler) { handler.handle(Future.succeededFuture()); } @Override public void shutdown() { // noop } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/SessionConnectionPool.java
http/src/main/java/io/hyperfoil/http/connection/SessionConnectionPool.java
package io.hyperfoil.http.connection; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.core.impl.ConnectionStatsConsumer; import io.hyperfoil.http.api.ConnectionConsumer; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpConnectionPool; import io.netty.channel.EventLoop; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; public class SessionConnectionPool implements HttpConnectionPool { private static final Logger log = LogManager.getLogger(SessionConnectionPool.class); private static final boolean trace = log.isTraceEnabled(); private final HttpConnectionPool shared; private final ArrayDeque<HttpConnection> available; private final ArrayList<HttpConnection> owned; public SessionConnectionPool(HttpConnectionPool shared, int capacity) { this.shared = shared; this.available = new ArrayDeque<>(capacity); this.owned = new ArrayList<>(capacity); } @Override public HttpClientPool clientPool() { return shared.clientPool(); } @Override public void acquire(boolean exclusiveConnection, ConnectionConsumer consumer) { assert !exclusiveConnection; for (;;) { HttpConnection connection = available.pollFirst(); if (connection == null) { shared.acquire(true, consumer); return; } else if (!connection.isClosed()) { shared.incrementInFlight(); connection.onAcquire(); consumer.accept(connection); return; } } } @Override public void afterRequestSent(HttpConnection connection) { // Move it to the back of the queue if it is still available (do not prefer it for subsequent requests) if (connection.isAvailable()) { log.trace("Keeping connection in session-local pool {}.", connection); available.addLast(connection); } // HashSet would be probably allocating if (!owned.contains(connection)) { owned.add(connection); } } @Override public int waitingSessions() { return shared.waitingSessions(); } @Override public EventLoop executor() { return shared.executor(); } @Override public void pulse() { shared.pulse(); } @Override public Collection<? extends HttpConnection> connections() { return available; } @Override public void release(HttpConnection connection, boolean becameAvailable, boolean afterRequest) { if (trace) { log.trace("Releasing to session-local pool {} ({}, {})", connection, becameAvailable, afterRequest); } if (becameAvailable) { log.trace("Added connection to session-local pool."); available.addLast(connection); } if (afterRequest) { if (connection.isOpen()) { shared.decrementInFlight(); } else { shared.release(connection, becameAvailable, true); owned.remove(connection); } } } @Override public void onSessionReset() { for (int i = owned.size() - 1; i >= 0; --i) { HttpConnection connection = owned.get(i); if (connection.inFlight() == 0) { shared.release(connection, !connection.isClosed(), false); } else { connection.close(); } } owned.clear(); available.clear(); } @Override public void incrementInFlight() { // noone should delegate to SessionConnectionPool throw new UnsupportedOperationException(); } @Override public void decrementInFlight() { // noone should delegate to SessionConnectionPool throw new UnsupportedOperationException(); } @Override public void visitConnectionStats(ConnectionStatsConsumer consumer) { // This should be never invoked because we're monitoring the shared pools only throw new UnsupportedOperationException(); } @Override public void start(Handler<AsyncResult<Void>> handler) { throw new UnsupportedOperationException(); } @Override public void shutdown() { throw new UnsupportedOperationException(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/RawRequestHandler.java
http/src/main/java/io/hyperfoil/http/connection/RawRequestHandler.java
package io.hyperfoil.http.connection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpRequest; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; public class RawRequestHandler extends ChannelOutboundHandlerAdapter { private static final Logger log = LogManager.getLogger(RawRequestHandler.class); private final HttpConnection connection; public RawRequestHandler(HttpConnection connection) { this.connection = connection; } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; HttpRequest request = connection.dispatchedRequest(); if (request != null) { if (request.handlers != null) { int readerIndex = buf.readerIndex(); request.handlers.handleRawRequest(request, buf, readerIndex, buf.readableBytes()); if (readerIndex != buf.readerIndex()) { throw new IllegalStateException("Handler has changed readerIndex on the buffer!"); } } } // non-request related data (SSL handshake, HTTP2 service messages...) will be ignored } else { log.warn("Unknown message being sent: {}", msg); } ctx.write(msg, promise); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/CustomHttp2ConnectionHandler.java
http/src/main/java/io/hyperfoil/http/connection/CustomHttp2ConnectionHandler.java
package io.hyperfoil.http.connection; import static io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception; import java.io.IOException; import java.util.function.BiConsumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnection; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpClientUpgradeHandler; import io.netty.handler.codec.http2.Http2ConnectionDecoder; import io.netty.handler.codec.http2.Http2ConnectionEncoder; import io.netty.handler.codec.http2.Http2Settings; import io.netty.util.internal.StringUtil; class CustomHttp2ConnectionHandler extends io.netty.handler.codec.http2.Http2ConnectionHandler { private static final Logger log = LogManager.getLogger(CustomHttp2ConnectionHandler.class); private final BiConsumer<HttpConnection, Throwable> activationHandler; private final HttpClientPool clientPool; private final boolean isUpgrade; private Http2Connection connection; CustomHttp2ConnectionHandler( HttpClientPool clientPool, BiConsumer<HttpConnection, Throwable> activationHandler, Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings, boolean isUpgrade) { super(decoder, encoder, initialSettings); this.clientPool = clientPool; this.activationHandler = activationHandler; this.isUpgrade = isUpgrade; } private static String generateName(Class<? extends ChannelHandler> handlerType) { return StringUtil.simpleClassName(handlerType) + "#0"; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { super.handlerAdded(ctx); if (ctx.channel().isActive() && !isUpgrade) { checkActivated(ctx); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_SUCCESSFUL) { checkActivated(ctx); } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_REJECTED) { activationHandler.accept(null, new IOException("H2C upgrade was rejected by server.")); } super.userEventTriggered(ctx, evt); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); checkActivated(ctx); } private void checkActivated(ChannelHandlerContext ctx) { if (connection == null) { connection = new Http2Connection(ctx, connection(), encoder(), decoder(), clientPool); // Use a very large stream window size connection.incrementConnectionWindowSize(1073676288 - 65535); if (clientPool.config().rawBytesHandlers()) { String customeHandlerName = generateName(CustomHttp2ConnectionHandler.class); ctx.pipeline().addBefore(customeHandlerName, null, new Http2RawResponseHandler(connection)); ctx.pipeline().addBefore(customeHandlerName, null, new RawRequestHandler(connection)); } activationHandler.accept(connection, null); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause != SessionStopException.INSTANCE) { log.warn("Exception in {}", this, cause); } try { if (getEmbeddedHttp2Exception(cause) != null) { onError(ctx, false, cause); } else { if (connection != null) { connection.cancelRequests(cause); } ctx.close(); } } catch (Throwable t) { log.error("Handling exception resulted in another exception", t); } } @Override public void channelInactive(ChannelHandlerContext ctx) { connection.cancelRequests(Connection.CLOSED_EXCEPTION); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/Http2Connection.java
http/src/main/java/io/hyperfoil/http/connection/Http2Connection.java
package io.hyperfoil.http.connection; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.BiFunction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.http.api.HttpCache; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpConnectionPool; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.HttpRequestWriter; import io.hyperfoil.http.api.HttpResponseHandlers; import io.hyperfoil.http.api.HttpVersion; import io.hyperfoil.http.config.Http; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2ConnectionDecoder; import io.netty.handler.codec.http2.Http2ConnectionEncoder; import io.netty.handler.codec.http2.Http2EventAdapter; import io.netty.handler.codec.http2.Http2Exception; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2Settings; import io.netty.util.collection.IntObjectHashMap; import io.netty.util.collection.IntObjectMap; import io.netty.util.internal.AppendableCharSequence; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ class Http2Connection extends Http2EventAdapter implements HttpConnection { private static final Logger log = LogManager.getLogger(Http2Connection.class); private static final boolean trace = log.isTraceEnabled(); private final ChannelHandlerContext context; private final io.netty.handler.codec.http2.Http2Connection connection; private final Http2ConnectionEncoder encoder; private final IntObjectMap<HttpRequest> streams = new IntObjectHashMap<>(); private final long clientMaxStreams; private final boolean secure; private HttpConnectionPool pool; private int aboutToSend; private long maxStreams; private Status status = Status.OPEN; private HttpRequest dispatchedRequest; private long lastUsed = System.nanoTime(); Http2Connection(ChannelHandlerContext context, io.netty.handler.codec.http2.Http2Connection connection, Http2ConnectionEncoder encoder, Http2ConnectionDecoder decoder, HttpClientPool clientPool) { this.context = context; this.connection = connection; this.encoder = encoder; this.clientMaxStreams = this.maxStreams = clientPool.config().maxHttp2Streams(); this.secure = clientPool.isSecure(); Http2EventAdapter listener = new EventAdapter(); connection.addListener(listener); decoder.frameListener(listener); } @Override public ChannelHandlerContext context() { return context; } @Override public void onAcquire() { assert aboutToSend >= 0; aboutToSend++; } @Override public boolean isAvailable() { return inFlight() < maxStreams; } @Override public int inFlight() { return streams.size() + aboutToSend; } public void incrementConnectionWindowSize(int increment) { try { io.netty.handler.codec.http2.Http2Stream stream = connection.connectionStream(); connection.local().flowController().incrementWindowSize(stream, increment); } catch (Http2Exception e) { e.printStackTrace(); } } @Override public void close() { if (status == Status.OPEN) { status = Status.CLOSING; cancelRequests(Connection.SELF_CLOSED_EXCEPTION); } context.close(); } @Override public String host() { return pool.clientPool().host(); } @Override public void attach(HttpConnectionPool pool) { this.pool = pool; } public void request(HttpRequest request, BiConsumer<Session, HttpRequestWriter>[] headerAppenders, boolean injectHostHeader, BiFunction<Session, Connection, ByteBuf> bodyGenerator) { assert aboutToSend > 0; aboutToSend--; HttpClientPool httpClientPool = pool.clientPool(); ByteBuf buf = bodyGenerator != null ? bodyGenerator.apply(request.session, this) : null; if (request.path.contains(" ")) { int length = request.path.length(); AppendableCharSequence temp = new AppendableCharSequence(length); boolean beforeQuestion = true; for (int i = 0; i < length; ++i) { if (request.path.charAt(i) == ' ') { if (beforeQuestion) { temp.append('%'); temp.append('2'); temp.append('0'); } else { temp.append('+'); } } else { if (request.path.charAt(i) == '?') { beforeQuestion = false; } temp.append(request.path.charAt(i)); } } request.path = temp.toString(); } Http2Headers headers = new DefaultHttp2Headers().method(request.method.name()).scheme(httpClientPool.scheme()) .path(request.path).authority(httpClientPool.authority()); // HTTPS selects host via SNI headers, duplicate Host header could confuse the server/proxy if (injectHostHeader && !pool.clientPool().config().protocol().secure()) { // https://www.rfc-editor.org/rfc/rfc9113#section-8.3.1-2.3.3 // Clients MUST NOT generate a request with a Host header field that differs // from the ":authority" pseudo-header field. headers.add(HttpHeaderNames.HOST, httpClientPool.authority()); } if (buf != null && buf.readableBytes() > 0) { headers.add(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); } HttpRequestWriterImpl writer = new HttpRequestWriterImpl(request, headers); if (headerAppenders != null) { for (BiConsumer<Session, HttpRequestWriter> headerAppender : headerAppenders) { headerAppender.accept(request.session, writer); } } if (request.hasCacheControl()) { HttpCache httpCache = HttpCache.get(request.session); if (httpCache.isCached(request, writer)) { if (trace) { log.trace("#{} Request is completed from cache", request.session.uniqueId()); } // prevent adding to available list twice if (streams.size() != maxStreams - 1) { pool.afterRequestSent(this); } request.handleCached(); tryReleaseToPool(); return; } } assert context.executor().inEventLoop(); int id = nextStreamId(); streams.put(id, request); dispatchedRequest = request; ChannelPromise writePromise = context.newPromise(); encoder.writeHeaders(context, id, headers, 0, buf == null, writePromise); if (buf != null) { if (trace) { log.trace("Sending HTTP request body: {}\n", Util.toString(buf, buf.readerIndex(), buf.readableBytes())); } writePromise = context.newPromise(); encoder.writeData(context, id, buf, 0, true, writePromise); } writePromise.addListener(request); // We need to flush the channel - context.flush() would skip (?) the uppermost handler // and the request body would not be sent. context.channel().flush(); dispatchedRequest = null; pool.afterRequestSent(this); } @Override public HttpRequest dispatchedRequest() { return dispatchedRequest; } @Override public HttpRequest peekRequest(int streamId) { return streams.get(streamId); } @Override public boolean removeRequest(int streamId, HttpRequest request) { throw new UnsupportedOperationException(); } @Override public void setClosed() { status = Status.CLOSED; } @Override public boolean isOpen() { return status == Status.OPEN; } @Override public boolean isClosed() { return status == Status.CLOSED; } @Override public boolean isSecure() { return secure; } @Override public HttpVersion version() { return HttpVersion.HTTP_2_0; } @Override public Http config() { return pool.clientPool().config(); } @Override public HttpConnectionPool pool() { return pool; } @Override public long lastUsed() { return lastUsed; } private int nextStreamId() { return connection.local().incrementAndGetNextStreamId(); } @Override public String toString() { return "Http2Connection{" + context.channel().localAddress() + " -> " + context.channel().remoteAddress() + ", status=" + status + ", streams=" + streams.size() + "+" + aboutToSend + ":" + streams + '}'; } void cancelRequests(Throwable cause) { for (Iterator<HttpRequest> iterator = streams.values().iterator(); iterator.hasNext();) { HttpRequest request = iterator.next(); iterator.remove(); pool.release(this, false, true); request.cancel(cause); } } private class EventAdapter extends Http2EventAdapter { @Override public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) { if (settings.maxConcurrentStreams() != null) { // The settings frame may be sent at any moment, e.g. when the connection // does not have ongoing request and therefore the pool == null maxStreams = Math.min(clientMaxStreams, settings.maxConcurrentStreams()); } } @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) { HttpRequest request = streams.get(streamId); if (request != null && !request.isCompleted()) { HttpResponseHandlers handlers = request.handlers(); int code = -1; try { code = Integer.parseInt(headers.status().toString()); } catch (NumberFormatException ignore) { } request.enter(); try { handlers.handleStatus(request, code, ""); for (Map.Entry<CharSequence, CharSequence> header : headers) { handlers.handleHeader(request, header.getKey(), header.getValue()); } if (endStream) { handlers.handleBodyPart(request, Unpooled.EMPTY_BUFFER, 0, 0, true); } } finally { request.exit(); } request.session.proceed(); } if (endStream) { endStream(streamId); } } @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { int ack = super.onDataRead(ctx, streamId, data, padding, endOfStream); HttpRequest request = streams.get(streamId); if (request != null && !request.isCompleted()) { HttpResponseHandlers handlers = request.handlers(); request.enter(); try { handlers.handleBodyPart(request, data, data.readerIndex(), data.readableBytes(), endOfStream); } finally { request.exit(); } request.session.proceed(); } if (endOfStream) { endStream(streamId); } return ack; } @Override public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) { HttpRequest request = streams.get(streamId); if (request != null) { HttpResponseHandlers handlers = request.handlers(); if (!request.isCompleted()) { request.enter(); try { // TODO: maybe add a specific handler because we don't need to terminate other streams handlers.handleThrowable(request, new IOException("HTTP2 stream was reset")); } catch (SessionStopException e) { if (streams.remove(streamId) == request) { tryReleaseToPool(); } throw e; } finally { request.exit(); } request.session.proceed(); } request.release(); if (streams.remove(streamId) == request) { tryReleaseToPool(); } } } private void endStream(int streamId) { HttpRequest request = streams.get(streamId); if (request != null) { if (!request.isCompleted()) { request.enter(); try { request.handlers().handleEnd(request, true); if (trace) { log.trace("Completed response on {}", this); } } catch (SessionStopException e) { if (streams.remove(streamId) == request) { tryReleaseToPool(); } throw e; } finally { request.exit(); } request.session.proceed(); } request.release(); if (streams.remove(streamId) == request) { tryReleaseToPool(); } } } } private void tryReleaseToPool() { lastUsed = System.nanoTime(); HttpConnectionPool pool = this.pool; if (pool != null) { // If this connection was not available we make it available pool.release(Http2Connection.this, inFlight() == maxStreams - 1 && !isClosed(), true); pool.pulse(); } } private class HttpRequestWriterImpl implements HttpRequestWriter { private final HttpRequest request; private final Http2Headers headers; HttpRequestWriterImpl(HttpRequest request, Http2Headers headers) { this.request = request; this.headers = headers; } @Override public HttpConnection connection() { return Http2Connection.this; } @Override public HttpRequest request() { return request; } @Override public void putHeader(CharSequence header, CharSequence value) { headers.add(header, value); if (request.hasCacheControl()) { HttpCache.get(request.session).requestHeader(request, header, value); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/Http2ConnectionHandlerBuilder.java
http/src/main/java/io/hyperfoil/http/connection/Http2ConnectionHandlerBuilder.java
package io.hyperfoil.http.connection; import java.util.function.BiConsumer; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnection; import io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder; import io.netty.handler.codec.http2.Http2ConnectionDecoder; import io.netty.handler.codec.http2.Http2ConnectionEncoder; import io.netty.handler.codec.http2.Http2EventAdapter; import io.netty.handler.codec.http2.Http2Settings; class Http2ConnectionHandlerBuilder extends AbstractHttp2ConnectionHandlerBuilder<CustomHttp2ConnectionHandler, Http2ConnectionHandlerBuilder> { private final HttpClientPool clientPool; private final boolean isUpgrade; private final BiConsumer<HttpConnection, Throwable> requestHandler; Http2ConnectionHandlerBuilder(HttpClientPool clientPool, boolean isUpgrade, BiConsumer<HttpConnection, Throwable> requestHandler) { this.clientPool = clientPool; this.isUpgrade = isUpgrade; this.requestHandler = requestHandler; } @Override protected CustomHttp2ConnectionHandler build(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings) { return new CustomHttp2ConnectionHandler(clientPool, requestHandler, decoder, encoder, initialSettings, isUpgrade); } public CustomHttp2ConnectionHandler build(io.netty.handler.codec.http2.Http2Connection conn) { connection(conn); frameListener(new Http2EventAdapter() { /* Dunno why this is needed */}); return super.build(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/HttpClientPoolImpl.java
http/src/main/java/io/hyperfoil/http/connection/HttpClientPoolImpl.java
package io.hyperfoil.http.connection; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.core.impl.ConnectionStatsConsumer; import io.hyperfoil.core.impl.EventLoopFactory; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnectionPool; import io.hyperfoil.http.api.HttpVersion; import io.hyperfoil.http.config.ConnectionPoolConfig; import io.hyperfoil.http.config.Http; import io.hyperfoil.impl.Util; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.SupportedCipherSuiteFilter; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.util.concurrent.EventExecutor; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class HttpClientPoolImpl implements HttpClientPool { private static final Logger log = LogManager.getLogger(HttpClientPoolImpl.class); final Http http; final String[] addressHosts; final int[] addressPorts; final int port; final String host; final String scheme; final String authority; final byte[] originalDestinationBytes; final SslContext sslContext; final boolean forceH2c; private final HttpConnectionPool[] children; private final AtomicInteger idx = new AtomicInteger(); private final Supplier<HttpConnectionPool> nextSupplier; public static HttpClientPoolImpl forTesting(Http http, int threads) throws SSLException { EventLoopGroup eventLoopGroup = EventLoopFactory.INSTANCE.create(threads); EventLoop[] executors = StreamSupport.stream(eventLoopGroup.spliterator(), false) .map(EventLoop.class::cast).toArray(EventLoop[]::new); return new HttpClientPoolImpl(http, executors, Benchmark.forTesting(), 0) { @Override public void shutdown() { super.shutdown(); eventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS); } }; } public HttpClientPoolImpl(Http http, EventLoop[] executors, Benchmark benchmark, int agentId) throws SSLException { this.http = http; this.sslContext = http.protocol().secure() ? createSslContext() : null; this.host = http.host(); this.port = http.port(); this.scheme = sslContext == null ? "http" : "https"; this.authority = host + ":" + port; this.originalDestinationBytes = http.originalDestination().getBytes(StandardCharsets.UTF_8); this.forceH2c = http.versions().length == 1 && http.versions()[0] == HttpVersion.HTTP_2_0; this.children = new HttpConnectionPool[executors.length]; int coreConnections, maxConnections, bufferConnections; switch (http.connectionStrategy()) { case SHARED_POOL: case SESSION_POOLS: coreConnections = benchmark.slice(http.sharedConnections().core(), agentId); maxConnections = benchmark.slice(http.sharedConnections().max(), agentId); bufferConnections = benchmark.slice(http.sharedConnections().buffer(), agentId); boolean hadBuffer = http.sharedConnections().buffer() > 0; if (coreConnections < executors.length || maxConnections < executors.length || (hadBuffer && bufferConnections < executors.length)) { int prevCore = coreConnections; int prevMax = maxConnections; int prevBuffer = bufferConnections; coreConnections = Math.max(coreConnections, executors.length); maxConnections = Math.max(maxConnections, executors.length); bufferConnections = Math.max(bufferConnections, hadBuffer ? executors.length : 0); log.warn("Connection pool size (core {}, max {}, buffer {}) too small: the event loop has {} executors. " + "Setting connection pool size to core {}, max {}, buffer {}", prevCore, prevMax, prevBuffer, executors.length, coreConnections, maxConnections, bufferConnections); } log.info("Allocating {} connections (max {}, buffer {}) in {} executors to {}", coreConnections, maxConnections, bufferConnections, executors.length, http.protocol().scheme + "://" + authority); break; case OPEN_ON_REQUEST: case ALWAYS_NEW: coreConnections = 0; maxConnections = 0; bufferConnections = 0; break; default: throw new IllegalArgumentException("Unknow connection strategy " + http.connectionStrategy()); } // This algorithm should be the same as session -> executor assignment to prevent blocking // in always(N) scenario with N connections int coreShare = coreConnections / executors.length; int maxShare = maxConnections / executors.length; int bufferShare = bufferConnections / executors.length; int coreRemainder = coreConnections - coreShare * executors.length; int maxRemainder = maxConnections - maxShare * executors.length; int bufferRemainder = bufferConnections - bufferShare * executors.length; for (int i = 0; i < executors.length; ++i) { if (maxConnections > 0) { int core = coreShare + (i < coreRemainder ? 1 : 0); int max = maxShare + (i < maxRemainder ? 1 : 0); int buffer = bufferShare + (i < bufferRemainder ? 1 : 0); children[i] = new SharedConnectionPool(this, executors[i], new ConnectionPoolConfig(core, max, buffer, http.sharedConnections().keepAliveTime())); } else { children[i] = new ConnectionAllocator(this, executors[i]); } } if (Integer.bitCount(children.length) == 1) { int shift = 32 - Integer.numberOfLeadingZeros(children.length - 1); int mask = (1 << shift) - 1; nextSupplier = () -> children[idx.getAndIncrement() & mask]; } else { nextSupplier = () -> children[idx.getAndIncrement() % children.length]; } addressHosts = new String[http.addresses().length]; addressPorts = new int[http.addresses().length]; String[] addresses = http.addresses(); for (int i = 0; i < addresses.length; i++) { final String address = addresses[i]; // This code must handle addresses in form ipv4address, ipv4address:port, [ipv6address]:port, ipv6address int bracketIndex = address.lastIndexOf(']'); int firstColonIndex = address.indexOf(':'); int lastColonIndex = address.lastIndexOf(':'); if (lastColonIndex >= 0 && ((bracketIndex >= 0 && lastColonIndex > bracketIndex) || (bracketIndex < 0 && lastColonIndex == firstColonIndex))) { addressHosts[i] = address.substring(0, lastColonIndex); addressPorts[i] = (int) Util.parseLong(address, lastColonIndex + 1, address.length(), port); } else { addressHosts[i] = address; addressPorts[i] = port; } } } private SslContext createSslContext() throws SSLException { SslProvider provider = SslProvider.isAlpnSupported(SslProvider.OPENSSL) ? SslProvider.OPENSSL : SslProvider.JDK; TrustManagerFactory trustManagerFactory = createTrustManagerFactory(); SslContextBuilder builder = SslContextBuilder.forClient() .sslProvider(provider) /* * NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(trustManagerFactory) .keyManager(createKeyManagerFactory()); builder.applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, Stream.of(http.versions()).map(HttpVersion::protocolName).toArray(String[]::new))); return builder.build(); } private KeyManagerFactory createKeyManagerFactory() { Http.KeyManager config = http.keyManager(); if (config.storeBytes() == null && config.certBytes() == null && config.keyBytes() == null) { return null; } try { KeyStore ks = KeyStore.getInstance(config.storeType()); if (config.storeBytes() != null) { ks.load(new ByteArrayInputStream(config.storeBytes()), config.password() == null ? null : config.password().toCharArray()); if (config.alias() != null) { if (ks.containsAlias(config.alias()) && ks.isKeyEntry(config.alias())) { KeyStore.PasswordProtection password = new KeyStore.PasswordProtection(config.password().toCharArray()); KeyStore.Entry entry = ks.getEntry(config.alias(), password); ks = KeyStore.getInstance(config.storeType()); ks.load(null); ks.setEntry(config.alias(), entry, password); } else { throw new BenchmarkDefinitionException( "Store file " + config.storeBytes() + " does not contain any entry for alias " + config.alias()); } } } else { ks.load(null, null); } if (config.certBytes() != null || config.keyBytes() != null) { if (config.certBytes() == null || config.keyBytes() == null) { throw new BenchmarkDefinitionException( "You should provide both certificate and private key for " + http.host() + ":" + http.port()); } ks.setKeyEntry(config.alias() == null ? "default" : config.alias(), toPrivateKey(config.keyBytes()), config.password().toCharArray(), new Certificate[] { loadCertificate(config.certBytes()) }); } KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(ks, config.password().toCharArray()); return keyManagerFactory; } catch (IOException | GeneralSecurityException e) { throw new BenchmarkDefinitionException("Cannot create key manager for " + http.host() + ":" + http.port(), e); } } private PrivateKey toPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { int pos = 0, lastPos = bytes.length - 1; // Truncate first and last lines and any newlines. while (pos < bytes.length && isWhite(bytes[pos])) ++pos; while (pos < bytes.length && bytes[pos] != '\n') ++pos; while (lastPos >= 0 && isWhite(bytes[lastPos])) --lastPos; while (lastPos >= 0 && bytes[lastPos] != '\n') --lastPos; ByteBuffer buffer = ByteBuffer.allocate(lastPos - pos); while (pos < lastPos) { if (!isWhite(bytes[pos])) buffer.put(bytes[pos]); ++pos; } buffer.flip(); ByteBuffer rawBuffer = Base64.getDecoder().decode(buffer); byte[] decoded = new byte[rawBuffer.limit()]; rawBuffer.get(decoded); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); } private boolean isWhite(byte b) { return b == ' ' || b == '\n' || b == '\r'; } private TrustManagerFactory createTrustManagerFactory() { Http.TrustManager config = http.trustManager(); if (config.storeBytes() == null && config.certBytes() == null) { return InsecureTrustManagerFactory.INSTANCE; } try { KeyStore ks = KeyStore.getInstance(config.storeType()); if (config.storeBytes() != null) { ks.load(new ByteArrayInputStream(config.storeBytes()), config.password() == null ? null : config.password().toCharArray()); } else { ks.load(null, null); } if (config.certBytes() != null) { ks.setCertificateEntry("default", loadCertificate(config.certBytes())); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(ks); return trustManagerFactory; } catch (GeneralSecurityException | IOException e) { throw new BenchmarkDefinitionException("Cannot create trust manager for " + http.host() + ":" + http.port(), e); } } private static Certificate loadCertificate(byte[] bytes) throws CertificateException, IOException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return cf.generateCertificate(new ByteArrayInputStream(bytes)); } @Override public Http config() { return http; } @Override public void start(Handler<AsyncResult<Void>> completionHandler) { AtomicInteger countDown = new AtomicInteger(children.length); for (HttpConnectionPool child : children) { child.start(result -> { if (result.failed() || countDown.decrementAndGet() == 0) { if (result.failed()) { shutdown(); } completionHandler.handle(result); } }); } } @Override public void shutdown() { for (HttpConnectionPool child : children) { child.shutdown(); } } void connect(final HttpConnectionPool pool, ConnectionReceiver handler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(EventLoopFactory.INSTANCE.socketChannel()); bootstrap.group(pool.executor()); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.handler(new HttpChannelInitializer(this, handler)); String address = this.host; int port = this.port; if (addressHosts.length > 0) { int index = ThreadLocalRandom.current().nextInt(addressHosts.length); address = addressHosts[index]; port = addressPorts[index]; } ChannelFuture fut = bootstrap.connect(new InetSocketAddress(address, port)); fut.addListener(handler); } @Override public HttpConnectionPool next() { return nextSupplier.get(); } @Override public HttpConnectionPool connectionPool(EventExecutor executor) { for (HttpConnectionPool pool : children) { if (pool.executor() == executor) { return pool; } } throw new IllegalStateException(); } @Override public String host() { return host; } @Override public String authority() { return authority; } @Override public byte[] originalDestinationBytes() { return originalDestinationBytes; } @Override public String scheme() { return scheme; } @Override public boolean isSecure() { return sslContext != null; } @Override public void visitConnectionStats(ConnectionStatsConsumer consumer) { for (var pool : children) { pool.visitConnectionStats(consumer); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/SharedConnectionPool.java
http/src/main/java/io/hyperfoil/http/connection/SharedConnectionPool.java
package io.hyperfoil.http.connection; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.FormattedMessage; import io.hyperfoil.http.api.ConnectionConsumer; import io.hyperfoil.http.api.HttpClientPool; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpConnectionPool; import io.hyperfoil.http.config.ConnectionPoolConfig; import io.netty.buffer.Unpooled; import io.netty.channel.EventLoop; import io.netty.util.concurrent.ScheduledFuture; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; /** * This instance is not thread-safe as it should be accessed only the {@link #executor()}. */ class SharedConnectionPool extends ConnectionPoolStats implements HttpConnectionPool { private static final Logger log = LogManager.getLogger(SharedConnectionPool.class); private static final boolean trace = log.isTraceEnabled(); //TODO: configurable private static final int MAX_FAILURES = 100; private final HttpClientPoolImpl clientPool; private final ArrayList<HttpConnection> connections = new ArrayList<>(); private final ArrayDeque<HttpConnection> available; private final List<HttpConnection> temporaryInFlight; private final ConnectionReceiver handleNewConnection = this::handleNewConnection; private final Runnable checkCreateConnections = this::checkCreateConnections; private final Runnable onConnectFailure = this::onConnectFailure; private final ConnectionPoolConfig sizeConfig; private final EventLoop eventLoop; private int connecting; // number of connections being opened private int created; private int closed; // number of closed connections in #connections private int availableClosed; // connections closed but staying in available queue private int failures; private Handler<AsyncResult<Void>> startedHandler; private boolean shutdown; private final Deque<ConnectionConsumer> waiting = new ArrayDeque<>(); private ScheduledFuture<?> pulseFuture; private ScheduledFuture<?> keepAliveFuture; SharedConnectionPool(HttpClientPoolImpl clientPool, EventLoop eventLoop, ConnectionPoolConfig sizeConfig) { super(clientPool.authority); this.clientPool = clientPool; this.sizeConfig = sizeConfig; this.eventLoop = eventLoop; this.available = new ArrayDeque<>(sizeConfig.max()); this.temporaryInFlight = new ArrayList<>(sizeConfig.max()); } @Override public HttpClientPool clientPool() { return clientPool; } private HttpConnection acquireNow(boolean exclusiveConnection) { assert eventLoop.inEventLoop(); try { for (;;) { HttpConnection connection = available.pollFirst(); if (connection == null) { log.debug("No connection to {} available, currently used {}", authority, usedConnections.current()); return null; } else if (!connection.isClosed()) { if (exclusiveConnection && connection.inFlight() > 0) { temporaryInFlight.add(connection); continue; } inFlight.incrementUsed(); if (connection.inFlight() == 0) { usedConnections.incrementUsed(); } connection.onAcquire(); return connection; } else { availableClosed--; log.trace("Connection {} to {} is already closed", connection, authority); } } } finally { if (!temporaryInFlight.isEmpty()) { available.addAll(temporaryInFlight); temporaryInFlight.clear(); } } } @Override public void acquire(boolean exclusiveConnection, ConnectionConsumer consumer) { HttpConnection connection = acquireNow(exclusiveConnection); if (connection != null) { consumer.accept(connection); checkCreateConnections(); } else { if (failures > MAX_FAILURES) { log.error("The request cannot be made since the failures to connect to {} exceeded a threshold. Stopping session.", authority); consumer.accept(null); return; } waiting.add(consumer); blockedSessions.incrementUsed(); } } @Override public void afterRequestSent(HttpConnection connection) { // Move it to the back of the queue if it is still available (do not prefer it for subsequent requests) if (connection.isAvailable()) { if (connection.inFlight() == 0) { // The request was not executed in the end (response was cached) available.addFirst(connection); } else { available.addLast(connection); } } } @Override public void release(HttpConnection connection, boolean becameAvailable, boolean afterRequest) { if (trace) { log.trace("Release {} (became available={} after request={})", connection, becameAvailable, afterRequest); } if (becameAvailable) { assert !connection.isClosed(); if (connection.inFlight() == 0) { // We are adding to the beginning of the queue to prefer reusing connections rather than cycling // too many often-idle connections available.addFirst(connection); } else { available.addLast(connection); } } if (afterRequest) { inFlight.decrementUsed(); } if (connection.inFlight() == 0) { usedConnections.decrementUsed(); } if (keepAliveFuture == null && sizeConfig.keepAliveTime() > 0) { long lastUsed = available.stream().filter(c -> !c.isClosed()).mapToLong(HttpConnection::lastUsed).min() .orElse(connection.lastUsed()); long nextCheck = sizeConfig.keepAliveTime() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastUsed); log.debug("Scheduling next keep-alive check in {} ms", nextCheck); keepAliveFuture = eventLoop.schedule(() -> { long now = System.nanoTime(); // We won't removing closed connections from available: acquire() will eventually remove these for (HttpConnection c : available) { if (c.isClosed()) continue; long idleTime = TimeUnit.NANOSECONDS.toMillis(now - c.lastUsed()); if (idleTime > sizeConfig.keepAliveTime()) { c.close(); } } keepAliveFuture = null; }, nextCheck, TimeUnit.MILLISECONDS); } } @Override public void onSessionReset() { // noop } @Override public int waitingSessions() { return waiting.size(); } @Override public EventLoop executor() { return eventLoop; } @Override public void pulse() { if (trace) { log.trace("Pulse to {} ({} waiting)", authority, waiting.size()); } ConnectionConsumer consumer = waiting.poll(); if (consumer != null) { HttpConnection connection = acquireNow(false); if (connection != null) { blockedSessions.decrementUsed(); consumer.accept(connection); } else if (failures > MAX_FAILURES) { log.error("The request cannot be made since the failures to connect to {} exceeded a threshold. Stopping session.", authority); consumer.accept(null); } else { waiting.addFirst(consumer); } } // The session might not use the connection (e.g. when it's terminated) and call pulse() again // We don't want to activate all the sessions, though so we need to schedule another pulse if (pulseFuture == null && !waiting.isEmpty()) { pulseFuture = executor().schedule(this::scheduledPulse, 1, TimeUnit.MILLISECONDS); } } // signature to match Callable private Object scheduledPulse() { pulseFuture = null; pulse(); return null; } @Override public Collection<HttpConnection> connections() { return connections; } private void checkCreateConnections() { assert eventLoop.inEventLoop(); if (shutdown) { return; } if (failures > MAX_FAILURES) { // When the connection is not available we'll let sessions see & terminate if it's past the duration Handler<AsyncResult<Void>> handler = this.startedHandler; if (handler != null) { startedHandler = null; String failureMessage = String.format("Cannot connect to %s: %d created, %d failures.", authority, created, failures); if (created > 0) { failureMessage += " Hint: either configure SUT to accept more open connections or reduce http.sharedConnections."; } handler.handle(Future.failedFuture(failureMessage)); } pulse(); return; } if (needsMoreConnections()) { connecting++; clientPool.connect(this, handleNewConnection); eventLoop.schedule(checkCreateConnections, 2, TimeUnit.MILLISECONDS); } } private boolean needsMoreConnections() { return created + connecting < sizeConfig.core() || (created + connecting < sizeConfig.max() && connecting + available.size() - availableClosed < sizeConfig.buffer()); } private void handleNewConnection(HttpConnection conn, Throwable err) { // at this moment we're in unknown thread if (err != null) { // Accessing created & failures is unreliable - we need to access those in eventloop thread. // For logging, though, we won't care. log.warn(new FormattedMessage("Cannot create connection to {} (created: {}, failures: {})", authority, created, failures + 1), err); // scheduling task when the executor is shut down causes errors if (!eventLoop.isShuttingDown() && !eventLoop.isShutdown()) { eventLoop.execute(onConnectFailure); } } else { // we are using this eventloop as the bootstrap group so the connection should be created for us assert conn.context().executor() == eventLoop; assert eventLoop.inEventLoop(); Handler<AsyncResult<Void>> handler = null; connections.add(conn); connecting--; created++; // With each success we reset the counter - otherwise we'd eventually // stop trying to create new connections and the sessions would be stuck. failures = 0; available.add(conn); log.debug("Created {} to {} ({}+{}=?{}:{}/{})", conn, authority, created, connecting, connections.size(), available.size() - availableClosed, sizeConfig.max()); incrementTypeStats(conn); conn.context().channel().closeFuture().addListener(v -> { conn.setClosed(); log.debug("Closed {} to {}. ({}+{}=?{}:{}/{})", conn, authority, created, connecting, connections.size(), available.size() - availableClosed, sizeConfig.max()); created--; closed++; if (available.contains(conn)) { availableClosed++; } typeStats.get(tagConnection(conn)).decrementUsed(); if (!shutdown) { if (closed >= sizeConfig.max()) { // do cleanup connections.removeIf(HttpConnection::isClosed); closed = 0; } checkCreateConnections(); } }); if (needsMoreConnections()) { checkCreateConnections(); } else { if (startedHandler != null && created >= sizeConfig.core()) { handler = startedHandler; startedHandler = null; } } if (handler != null) { handler.handle(Future.succeededFuture()); } pulse(); } } private void onConnectFailure() { failures++; connecting--; eventLoop.schedule(checkCreateConnections, 50, TimeUnit.MILLISECONDS); } @Override public void start(Handler<AsyncResult<Void>> handler) { startedHandler = handler; eventLoop.execute(checkCreateConnections); } @Override public void shutdown() { log.debug("Shutdown called"); shutdown = true; if (eventLoop.isShutdown()) { // Already shutdown return; } eventLoop.execute(() -> { log.debug("Closing all connections"); for (HttpConnection conn : connections) { if (conn.isClosed()) { continue; } conn.context().writeAndFlush(Unpooled.EMPTY_BUFFER); conn.context().close(); conn.context().flush(); } }); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/Http1xConnection.java
http/src/main/java/io/hyperfoil/http/connection/Http1xConnection.java
package io.hyperfoil.http.connection; import java.util.ArrayDeque; import java.util.Deque; import java.util.function.BiConsumer; import java.util.function.BiFunction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.http.api.HttpCache; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpConnectionPool; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.HttpRequestWriter; import io.hyperfoil.http.api.HttpVersion; import io.hyperfoil.http.config.Http; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.util.AsciiString; import io.netty.util.CharsetUtil; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ class Http1xConnection extends ChannelDuplexHandler implements HttpConnection { private static final Logger log = LogManager.getLogger(Http1xConnection.class); private static final boolean trace = log.isTraceEnabled(); private static final byte[] HTTP1_1 = { ' ', 'H', 'T', 'T', 'P', '/', '1', '.', '1', '\r', '\n' }; private final Deque<HttpRequest> inflights; private final BiConsumer<HttpConnection, Throwable> activationHandler; private final boolean secure; private final int pipeliningLimit; private HttpConnectionPool pool; private ChannelHandlerContext ctx; private int aboutToSend; private boolean activated; private Status status = Status.OPEN; private long lastUsed = System.nanoTime(); Http1xConnection(HttpClientPoolImpl client, BiConsumer<HttpConnection, Throwable> handler) { this.activationHandler = handler; this.inflights = new ArrayDeque<>(client.config().pipeliningLimit()); this.secure = client.isSecure(); this.pipeliningLimit = client.config().pipeliningLimit(); } @Override public void handlerAdded(ChannelHandlerContext ctx) { this.ctx = ctx; if (ctx.channel().isActive()) { checkActivated(ctx); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); checkActivated(ctx); } private void checkActivated(ChannelHandlerContext ctx) { if (!activated) { activated = true; activationHandler.accept(this, null); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // We should have handled that before throw new UnsupportedOperationException(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof SessionStopException) { // ignore } else { log.warn("Exception in {}", this, cause); cancelRequests(cause); } ctx.close(); } @Override public void channelInactive(ChannelHandlerContext ctx) { cancelRequests(CLOSED_EXCEPTION); } private void cancelRequests(Throwable cause) { HttpRequest request; while ((request = inflights.poll()) != null) { pool.release(this, false, true); if (request.isRunning()) { request.cancel(cause); } } } @Override public void attach(HttpConnectionPool pool) { this.pool = pool; } @Override public void request(HttpRequest request, BiConsumer<Session, HttpRequestWriter>[] headerAppenders, boolean injectHostHeader, BiFunction<Session, Connection, ByteBuf> bodyGenerator) { assert aboutToSend > 0; aboutToSend--; ByteBuf buf = ctx.alloc().buffer(); buf.writeBytes(request.method.netty.asciiName().array()); buf.writeByte(' '); boolean beforeQuestion = true; for (int i = 0; i < request.path.length(); ++i) { if (request.path.charAt(i) == ' ') { if (beforeQuestion) { buf.writeByte(0xFF & '%'); buf.writeByte(0xFF & '2'); buf.writeByte(0xFF & '0'); } else { buf.writeByte(0xFF & '+'); } } else { if (request.path.charAt(i) == '?') { beforeQuestion = false; } buf.writeByte(0xFF & request.path.charAt(i)); } } buf.writeBytes(HTTP1_1); if (injectHostHeader) { writeHeader(buf, HttpHeaderNames.HOST.array(), pool.clientPool().originalDestinationBytes()); } // TODO: adjust interface - we can't send static buffers anyway ByteBuf body = bodyGenerator != null ? bodyGenerator.apply(request.session, request.connection()) : null; if (body == null) { body = Unpooled.EMPTY_BUFFER; } if (body.readableBytes() > 0) { if (trace) { log.trace("Sending HTTP request body: {}\n", Util.toString(body, body.readerIndex(), body.readableBytes())); } buf.writeBytes(HttpHeaderNames.CONTENT_LENGTH.array()).writeByte(':').writeByte(' '); Util.intAsText2byteBuf(body.readableBytes(), buf); buf.writeByte('\r').writeByte('\n'); } HttpCache httpCache = null; if (request.hasCacheControl()) { httpCache = HttpCache.get(request.session); httpCache.beforeRequestHeaders(request); } // TODO: if headers are strings, UTF-8 conversion creates a lot of trash HttpRequestWriterImpl writer = new HttpRequestWriterImpl(request, buf); if (headerAppenders != null) { // TODO: allocation, if it's not eliminated we could store a reusable object for (BiConsumer<Session, HttpRequestWriter> headerAppender : headerAppenders) { headerAppender.accept(request.session, writer); } } buf.writeByte('\r').writeByte('\n'); assert ctx.executor().inEventLoop(); // here the httpCache is guaranteed to be not null if request.hasCacheControl is true if (httpCache != null && httpCache.isCached(request, writer)) { if (trace) { log.trace("#{} Request is completed from cache", request.session.uniqueId()); } // prevent adding to available twice if (inFlight() != pipeliningLimit - 1) { pool.afterRequestSent(this); } request.handleCached(); releasePoolAndPulse(); return; } inflights.add(request); ChannelPromise writePromise = ctx.newPromise(); writePromise.addListener(request); if (body.isReadable()) { ctx.write(buf); ctx.writeAndFlush(body, writePromise); } else { ctx.writeAndFlush(buf, writePromise); } pool.afterRequestSent(this); } private void writeHeader(ByteBuf buf, byte[] name, byte[] value) { buf.writeBytes(name).writeByte(':').writeByte(' ').writeBytes(value).writeByte('\r').writeByte('\n'); } void releasePoolAndPulse() { lastUsed = System.nanoTime(); // If this connection was not available we make it available HttpConnectionPool pool = this.pool; if (pool != null) { // Note: the pool might be already released if the completion handler // invoked another request which was served from cache. pool.release(this, inFlight() == pipeliningLimit - 1 && !isClosed(), true); pool.pulse(); } } @Override public HttpRequest dispatchedRequest() { return inflights.peekLast(); } @Override public HttpRequest peekRequest(int streamId) { assert streamId == 0; return inflights.peek(); } @Override public boolean removeRequest(int streamId, HttpRequest request) { HttpRequest req = inflights.poll(); if (req == null) { // cancel() was called before draining the queue return false; } else if (req != request) { throw new IllegalStateException(); } return true; } @Override public void setClosed() { status = Status.CLOSED; } @Override public boolean isOpen() { return status == Status.OPEN; } @Override public boolean isClosed() { return status == Status.CLOSED; } @Override public boolean isSecure() { return secure; } @Override public HttpVersion version() { return HttpVersion.HTTP_1_1; } @Override public Http config() { return pool.clientPool().config(); } @Override public HttpConnectionPool pool() { return pool; } @Override public long lastUsed() { return lastUsed; } @Override public ChannelHandlerContext context() { return ctx; } @Override public void onAcquire() { aboutToSend++; } @Override public boolean isAvailable() { // Having pool not attached implies that the connection is not taken out of the pool // and therefore it's fully available return pool == null || inFlight() < pipeliningLimit; } @Override public int inFlight() { return inflights.size() + aboutToSend; } @Override public void close() { if (status == Status.OPEN) { status = Status.CLOSING; // We need to cancel requests manually before sending the FIN packet, otherwise the server // could give us an unexpected response before closing the connection with RST packet. cancelRequests(SELF_CLOSED_EXCEPTION); } ctx.close(); } @Override public String host() { return pool.clientPool().host(); } @Override public String toString() { return "Http1xConnection{" + ctx.channel().localAddress() + " -> " + ctx.channel().remoteAddress() + ", status=" + status + ", size=" + inflights.size() + "+" + aboutToSend + ":" + inflights + '}'; } private class HttpRequestWriterImpl implements HttpRequestWriter { private final HttpRequest request; private final ByteBuf buf; HttpRequestWriterImpl(HttpRequest request, ByteBuf buf) { this.request = request; this.buf = buf; } @Override public HttpConnection connection() { return Http1xConnection.this; } @Override public HttpRequest request() { return request; } @Override public void putHeader(CharSequence header, CharSequence value) { final ByteBuf buf = this.buf; buf.ensureWritable(header.length() + value.length() + 4); if (header instanceof AsciiString) { final AsciiString ascii = (AsciiString) header; // remove this when https://github.com/netty/netty/pull/13197 will be merged buf.writeBytes(ascii.array(), ascii.arrayOffset(), ascii.length()); } else { // header name CANNOT be anything but US-ASCII: latin is already wider buf.writeCharSequence(header, CharsetUtil.ISO_8859_1); } buf.writeByte(':'); buf.writeByte(' '); if (value instanceof AsciiString) { final AsciiString ascii = (AsciiString) value; // remove this when https://github.com/netty/netty/pull/13197 will be merged buf.writeBytes(ascii.array(), ascii.arrayOffset(), ascii.length()); } else { if (Util.isLatin(value)) { buf.writeCharSequence(value, CharsetUtil.ISO_8859_1); } else { buf.writeCharSequence(value, CharsetUtil.UTF_8); } } buf.writeByte('\r'); buf.writeByte('\n'); if (request.hasCacheControl()) { HttpCache.get(request.session).requestHeader(request, header, value); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/HttpDestinationTableImpl.java
http/src/main/java/io/hyperfoil/http/connection/HttpDestinationTableImpl.java
package io.hyperfoil.http.connection; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.api.HttpConnectionPool; import io.hyperfoil.http.api.HttpDestinationTable; public class HttpDestinationTableImpl implements HttpDestinationTable { private final Map<String, HttpConnectionPool> byAuthority; private final Map<String, HttpConnectionPool> byName; private final String[] authorities; private final byte[][] authorityBytes; public HttpDestinationTableImpl(Map<String, HttpConnectionPool> byAuthority) { this.byAuthority = byAuthority; this.byName = byAuthority.entrySet().stream() .filter(entry -> entry.getKey() != null && entry.getValue().clientPool().config().name() != null) .collect(Collectors.toMap(entry -> entry.getValue().clientPool().config().name(), Map.Entry::getValue)); this.authorities = byAuthority.keySet().stream().filter(Objects::nonNull).toArray(String[]::new); this.authorityBytes = Stream.of(authorities).map(url -> url.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new); } public HttpDestinationTableImpl(HttpDestinationTable other, Function<HttpConnectionPool, HttpConnectionPool> replacePool) { this.authorities = other.authorities(); this.authorityBytes = other.authorityBytes(); this.byAuthority = new HashMap<>(); this.byName = new HashMap<>(); HttpConnectionPool defaultPool = other.getConnectionPoolByAuthority(null); for (String authority : authorities) { HttpConnectionPool pool = other.getConnectionPoolByAuthority(authority); HttpConnectionPool newPool = replacePool.apply(pool); byAuthority.put(authority, newPool); if (pool == defaultPool) { byAuthority.put(null, newPool); } byName.put(pool.clientPool().config().name(), newPool); } } @Override public String[] authorities() { return authorities; } @Override public byte[][] authorityBytes() { return authorityBytes; } @Override public void onSessionReset(Session session) { byAuthority.values().forEach(HttpConnectionPool::onSessionReset); } @Override public boolean hasSingleDestination() { return authorities.length == 1; } @Override public HttpConnectionPool getConnectionPoolByName(String endpoint) { return byName.get(endpoint); } @Override public HttpConnectionPool getConnectionPoolByAuthority(String authority) { return byAuthority.get(authority); } public Iterable<Map.Entry<String, HttpConnectionPool>> iterable() { return byAuthority.entrySet(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/connection/Http2RawResponseHandler.java
http/src/main/java/io/hyperfoil/http/connection/Http2RawResponseHandler.java
package io.hyperfoil.http.connection; import static io.netty.handler.codec.http2.Http2CodecUtil.FRAME_HEADER_LENGTH; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpRequest; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; public class Http2RawResponseHandler extends BaseResponseHandler { private static final Logger log = LogManager.getLogger(Http2RawResponseHandler.class); private int streamId = -1; private byte[] frameHeader = new byte[FRAME_HEADER_LENGTH]; private int frameHeaderIndex = 0; Http2RawResponseHandler(HttpConnection connection) { super(connection); } @Override protected boolean isRequestStream(int streamId) { // 0 is any connection-related stuff // 1 is HTTP upgrade response // even numbers are server-initiated connections return (streamId & 1) == 1 && streamId >= 3; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; while (buf.isReadable()) { if (responseBytes <= 0) { // we haven't received the header yet if (frameHeaderIndex > 0) { // we have received some short buffers int maxBytes = Math.min(FRAME_HEADER_LENGTH - frameHeaderIndex, buf.readableBytes()); buf.readBytes(frameHeader, frameHeaderIndex, maxBytes); frameHeaderIndex += maxBytes; if (frameHeaderIndex >= FRAME_HEADER_LENGTH) { ByteBuf wrapped = Unpooled.wrappedBuffer(frameHeader); responseBytes = wrapped.getUnsignedMedium(0); streamId = wrapped.getInt(5) & Integer.MAX_VALUE; HttpRequest request = connection.peekRequest(streamId); onRawData(request, wrapped, wrapped.readableBytes() == responseBytes); ctx.fireChannelRead(wrapped); frameHeaderIndex = 0; if (!handleBuffer(ctx, buf, streamId)) { break; } } } else if (buf.readableBytes() >= FRAME_HEADER_LENGTH) { responseBytes = FRAME_HEADER_LENGTH + buf.getUnsignedMedium(buf.readerIndex()); streamId = buf.getInt(buf.readerIndex() + 5) & Integer.MAX_VALUE; if (!handleBuffer(ctx, buf, streamId)) { break; } } else { frameHeaderIndex = buf.readableBytes(); buf.readBytes(frameHeader, 0, frameHeaderIndex); assert !buf.isReadable(); buf.release(); } } else if (!handleBuffer(ctx, buf, streamId)) { break; } } } else { log.error("Unexpected message type: {}", msg); super.channelRead(ctx, msg); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/TagAttributeHandlerBuilder.java
http/src/main/java/io/hyperfoil/http/html/TagAttributeHandlerBuilder.java
package io.hyperfoil.http.html; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.core.handlers.MultiProcessor; import io.hyperfoil.core.handlers.StoreShortcuts; public class TagAttributeHandlerBuilder implements HtmlHandler.TagHandlerBuilder<TagAttributeHandlerBuilder>, StoreShortcuts.Host { private String tag; private String attribute; @SuppressWarnings("FieldMayBeFinal") private MultiProcessor.Builder<TagAttributeHandlerBuilder, ?> processors = new MultiProcessor.Builder<>(this); @SuppressWarnings("FieldMayBeFinal") private StoreShortcuts<TagAttributeHandlerBuilder> storeShortcuts = new StoreShortcuts<>(this); @Embed public MultiProcessor.Builder<TagAttributeHandlerBuilder, ?> processors() { return processors; } @Embed public StoreShortcuts<TagAttributeHandlerBuilder> storeShortcuts() { return storeShortcuts; } /** * Name of the tag this handler should look for, e.g. <code>form</code> * * @param tag Name of the tag. * @return Self. */ public TagAttributeHandlerBuilder tag(String tag) { this.tag = tag; return this; } /** * Name of the attribute in this element you want to process, e.g. <code>action</code> * * @param attribute Name of the attribute. * @return Self. */ public TagAttributeHandlerBuilder attribute(String attribute) { this.attribute = attribute; return this; } @Override public HtmlHandler.BaseTagAttributeHandler build() { return new HtmlHandler.BaseTagAttributeHandler(new String[] { tag }, new String[] { attribute }, processors.build(false)); } @Override public void accept(Processor.Builder processor) { processors.processor(processor); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/Match.java
http/src/main/java/io/hyperfoil/http/html/Match.java
package io.hyperfoil.http.html; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; class Match { private int partial = 0; private boolean hasMatch = false; public void shift(ByteBuf data, int offset, int length, boolean isLast, byte[] string) { if (partial < 0) { if (isLast) { partial = 0; } return; } int i = 0; for (; i < length && partial < string.length; ++i, ++partial) { if (string[partial] != Util.toLowerCase(data.getByte(offset + i))) { hasMatch = false; if (!isLast) { partial = -1; } else { partial = 0; } return; } } if (isLast) { hasMatch = i == length && partial == string.length; partial = 0; } } public void reset() { hasMatch = false; partial = 0; } public boolean hasMatch() { return hasMatch; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/MetaRefreshHandler.java
http/src/main/java/io/hyperfoil/http/html/MetaRefreshHandler.java
package io.hyperfoil.http.html; import java.nio.charset.StandardCharsets; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; public class MetaRefreshHandler implements HtmlHandler.TagHandler { private static final byte[] META = "meta".getBytes(StandardCharsets.UTF_8); private static final byte[] HTTP_EQUIV = "http-equiv".getBytes(StandardCharsets.UTF_8); private static final byte[] REFRESH = "refresh".getBytes(StandardCharsets.UTF_8); private static final byte[] CONTENT = "content".getBytes(StandardCharsets.UTF_8); private final Processor processor; public MetaRefreshHandler(Processor processor) { this.processor = processor; } @Override public Processor processor() { return processor; } @Override public HtmlHandler.HandlerContext newContext() { return new Context(); } class Context implements HtmlHandler.HandlerContext { private final Match meta = new Match(); private final Match httpEquiv = new Match(); private final Match content = new Match(); private final Match refresh = new Match(); private final ByteBuf valueBuffer = ByteBufAllocator.DEFAULT.buffer(); @Override public void onTag(Session session, boolean close, ByteBuf data, int offset, int length, boolean isLast) { if (close) { endTag(session, true); } else { meta.shift(data, offset, length, isLast, META); } } @Override public void onAttr(Session session, ByteBuf data, int offset, int length, boolean isLast) { if (meta.hasMatch()) { httpEquiv.shift(data, offset, length, isLast, HTTP_EQUIV); content.shift(data, offset, length, isLast, CONTENT); } } @Override public void onValue(Session session, ByteBuf data, int offset, int length, boolean isLast) { if (httpEquiv.hasMatch()) { refresh.shift(data, offset, length, isLast, REFRESH); if (refresh.hasMatch() && valueBuffer.isReadable()) { processor.process(session, valueBuffer, valueBuffer.readerIndex(), valueBuffer.readableBytes(), true); valueBuffer.clear(); } } else if (content.hasMatch()) { valueBuffer.writeBytes(data, offset, length); if (refresh.hasMatch() && isLast) { processor.process(session, valueBuffer, valueBuffer.readerIndex(), valueBuffer.readableBytes(), true); valueBuffer.clear(); } } } @Override public void endTag(Session session, boolean closing) { meta.reset(); httpEquiv.reset(); content.reset(); refresh.reset(); valueBuffer.clear(); } @Override public void destroy() { valueBuffer.release(); } } public static class Builder implements HtmlHandler.TagHandlerBuilder<Builder> { private Processor.Builder processor; public Builder processor(Processor.Builder processor) { this.processor = processor; return this; } @Override public MetaRefreshHandler build() { return new MetaRefreshHandler(processor.build(false)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/EmbeddedResourceProcessor.java
http/src/main/java/io/hyperfoil/http/html/EmbeddedResourceProcessor.java
package io.hyperfoil.http.html; import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.HttpUtil; import io.hyperfoil.http.api.HttpDestinationTable; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.util.internal.AppendableCharSequence; class EmbeddedResourceProcessor extends Processor.BaseDelegating { private static final Logger log = LogManager.getLogger(EmbeddedResourceProcessor.class); private static final boolean trace = log.isTraceEnabled(); private static final byte[] HTTP_PREFIX = HttpUtil.HTTP_PREFIX.getBytes(StandardCharsets.UTF_8); private static final byte[] HTTPS_PREFIX = HttpUtil.HTTP_PREFIX.getBytes(StandardCharsets.UTF_8); private final boolean ignoreExternal; private final FetchResourceHandler fetchResource; EmbeddedResourceProcessor(boolean ignoreExternal, Processor delegate, FetchResourceHandler fetchResource) { super(delegate); this.ignoreExternal = ignoreExternal; this.fetchResource = fetchResource; } @Override public void before(Session session) { if (fetchResource != null) { fetchResource.before(session); } if (delegate != null) { super.before(session); } } @Override public void after(Session session) { if (delegate != null) { super.after(session); } if (fetchResource != null) { fetchResource.after(session); } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { assert isLastPart; // TODO: here we should normalize the URL, remove escapes etc... HttpRequest request = HttpRequest.ensure(session.currentRequest()); if (request == null) { return; } boolean isHttp = Util.hasPrefix(data, offset, length, HTTP_PREFIX); boolean isHttps = Util.hasPrefix(data, offset, length, HTTPS_PREFIX); if (isHttp || isHttps) { String authority = null; HttpDestinationTable destinations = HttpDestinationTable.get(session); byte[][] authorityBytes = destinations.authorityBytes(); for (int i = 0; i < authorityBytes.length; i++) { if (HttpUtil.authorityMatch(data, offset, length, authorityBytes[i], isHttp)) { authority = destinations.authorities()[i]; break; } } if (authority == null && ignoreExternal) { if (trace) { log.trace("#{} Ignoring external URL {}", session.uniqueId(), Util.toString(data, offset, length)); } return; } if (trace) { log.trace("#{} Matched URL {}", session.uniqueId(), Util.toString(data, offset, length)); } if (fetchResource != null) { int pathStart = data.indexOf(offset + (isHttp ? HTTP_PREFIX.length : HTTPS_PREFIX.length), offset + length, (byte) '/'); CharSequence path = pathStart < 0 ? "/" : data.toString(pathStart, offset + length - pathStart, StandardCharsets.UTF_8); fetchResource.handle(session, authority, path); } if (delegate != null) { delegate.process(session, data, offset, length, true); } } else if (data.getByte(offset) == '/') { // No need to rewrite relative URL if (trace) { log.trace("#{} Matched URL {}", session.uniqueId(), Util.toString(data, offset, length)); } if (fetchResource != null) { fetchResource.handle(session, request.authority, data.toString(offset, length, StandardCharsets.UTF_8)); } if (delegate != null) { delegate.process(session, data, offset, length, true); } } else { if (trace) { log.trace("#{} Matched URL {}", session.uniqueId(), Util.toString(data, offset, length)); } if (fetchResource != null) { AppendableCharSequence newPath = new AppendableCharSequence(request.path.length() + length); int end = request.path.lastIndexOf('/'); if (end < 0) { newPath.append(request.path).append('/'); } else { newPath.append(request.path, 0, end + 1); } // TODO allocation newPath.append(Util.toString(data, offset, length)); if (trace) { log.trace("#{} Rewritten relative URL to {}", session.uniqueId(), newPath); } fetchResource.handle(session, request.authority, newPath); } if (delegate != null) { ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(request.path.length() + length); try { Util.string2byteBuf(request.path, buffer); for (int i = buffer.writerIndex() - 1; i >= 0; --i) { if (buffer.getByte(i) == '/') { buffer.writerIndex(i + 1); break; } } buffer.ensureWritable(length); buffer.writeBytes(data, offset, length); if (trace) { log.trace("#{} Rewritten relative URL to {}", session.uniqueId(), Util.toString(buffer, buffer.readerIndex(), buffer.readableBytes())); } delegate.process(session, buffer, buffer.readerIndex(), buffer.readableBytes(), true); } finally { buffer.release(); } } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/RefreshHandler.java
http/src/main/java/io/hyperfoil/http/html/RefreshHandler.java
package io.hyperfoil.http.html; import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.LimitedPoolResource; import io.hyperfoil.core.data.Queue; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.http.HttpUtil; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.handlers.Redirect; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; public class RefreshHandler implements Processor, ResourceUtilizer { private static final Logger log = LogManager.getLogger(RefreshHandler.class); private static final byte[] URL = "url".getBytes(StandardCharsets.UTF_8); private final Queue.Key immediateQueueKey; private final Queue.Key delayedQueueKey; private final LimitedPoolResource.Key<Redirect.Coords> poolKey; private final int concurrency; private final ObjectAccess immediateQueueVar; private final ObjectAccess delayedQueueVar; private final String redirectSequence; private final String delaySequence; private final ObjectAccess tempCoordsVar; private final SerializableFunction<Session, SequenceInstance> originalSequenceSupplier; public RefreshHandler(Queue.Key immediateQueueKey, Queue.Key delayedQueueKey, LimitedPoolResource.Key<Redirect.Coords> poolKey, int concurrency, ObjectAccess immediateQueueVar, ObjectAccess delayedQueueVar, String redirectSequence, String delaySequence, ObjectAccess tempCoordsVar, SerializableFunction<Session, SequenceInstance> originalSequenceSupplier) { this.immediateQueueKey = immediateQueueKey; this.delayedQueueKey = delayedQueueKey; this.poolKey = poolKey; this.concurrency = concurrency; this.immediateQueueVar = immediateQueueVar; this.delayedQueueVar = delayedQueueVar; this.redirectSequence = redirectSequence; this.delaySequence = delaySequence; this.tempCoordsVar = tempCoordsVar; this.originalSequenceSupplier = originalSequenceSupplier; } @Override public void before(Session session) { tempCoordsVar.unset(session); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { assert isLastPart; HttpRequest request = HttpRequest.ensure(session.currentRequest()); if (request == null) { return; } try { long seconds = 0; String url = null; for (int i = 0; i < length; ++i) { if (data.getByte(offset + i) == ';') { seconds = Util.parseLong(data, offset, i); ++i; while (Character.isWhitespace(data.getByte(offset + i))) ++i; while (length > 0 && Character.isWhitespace(data.getByte(offset + length - 1))) --length; for (int j = 0; j < URL.length; ++j, ++i) { if (Util.toLowerCase(data.getByte(offset + i)) != URL[j]) { log.warn("#{} Failed to parse META refresh content (missing URL): {}", session.uniqueId(), Util.toString(data, offset, length)); return; } } while (Character.isWhitespace(data.getByte(offset + i))) ++i; if (data.getByte(offset + i) != '=') { log.warn("#{} Failed to parse META refresh content (missing = after URL): {}", session.uniqueId(), Util.toString(data, offset, length)); return; } else { ++i; } while (Character.isWhitespace(data.getByte(offset + i))) ++i; url = Util.toString(data, offset + i, length - i); break; } } if (url == null) { seconds = Util.parseLong(data, offset, length); } Redirect.Coords coords = session.getResource(poolKey).acquire(); coords.method = HttpMethod.GET; coords.originalSequence = originalSequenceSupplier.apply(session); coords.delay = (int) seconds; if (url == null) { coords.authority = request.authority; coords.path = request.path; } else if (url.startsWith(HttpUtil.HTTP_PREFIX) || url.startsWith(HttpUtil.HTTPS_PREFIX)) { coords.authority = null; coords.path = url; } else { coords.authority = request.authority; if (url.startsWith("/")) { coords.path = url; } else { int lastSlash = request.path.lastIndexOf('/'); if (lastSlash < 0) { log.warn("#{} Did the request have a relative path? {}", session.uniqueId(), request.path); coords.path = "/" + url; } else { coords.path = request.path.substring(0, lastSlash + 1) + url; } } } session.getResource(seconds == 0 ? immediateQueueKey : delayedQueueKey).push(session, coords); // this prevents completion handlers from running tempCoordsVar.setObject(session, coords); } catch (NumberFormatException e) { log.warn("#{} Failed to parse META refresh content: {}", session.uniqueId(), Util.toString(data, offset, length)); } } @Override public void reserve(Session session) { session.declareResource(poolKey, () -> LimitedPoolResource.create(concurrency, Redirect.Coords.class, Redirect.Coords::new), true); session.declareResource(immediateQueueKey, () -> new Queue(immediateQueueVar, concurrency, concurrency, redirectSequence, null), true); session.declareResource(delayedQueueKey, () -> new Queue(delayedQueueVar, concurrency, concurrency, delaySequence, null), true); initQueueVar(session, immediateQueueVar); initQueueVar(session, delayedQueueVar); } private void initQueueVar(Session session, ObjectAccess var) { if (!var.isSet(session)) { var.setObject(session, ObjectVar.newArray(session, concurrency)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/EmbeddedResourceHandlerBuilder.java
http/src/main/java/io/hyperfoil/http/html/EmbeddedResourceHandlerBuilder.java
package io.hyperfoil.http.html; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.core.handlers.MultiProcessor; /** * Handles <code>&lt;img src="..."&gt;</code>, <code>&lt;link href="..."&gt;</code>, * <code>&lt;embed src="..."&gt;</code>, <code>&lt;frame src="..."&gt;</code>, * <code>&lt;iframe src="..."&gt;</code>, <code>&lt;object data="..."&gt;</code> and <code>&lt;script src="..."&gt;</code>. * <p> * Does not handle <code>&lt;source src="..."&gt;</code> or <code>&lt;track src="..."&gt;</code> because browser * would choose only one of the options. */ public class EmbeddedResourceHandlerBuilder implements HtmlHandler.TagHandlerBuilder<EmbeddedResourceHandlerBuilder> { private static final String[] TAGS = { "img", "link", "embed", "frame", "iframe", "object", "script" }; private static final String[] ATTRS = { "src", "href", "src", "src", "src", "data", "src" }; private boolean ignoreExternal = true; private MultiProcessor.Builder<EmbeddedResourceHandlerBuilder, ?> processors = new MultiProcessor.Builder<>(this); private FetchResourceHandler.Builder fetchResource; /** * Ignore resources hosted on servers that are not covered in the <code>http</code> section. * * @param ignoreExternal Ignore? * @return Self. */ public EmbeddedResourceHandlerBuilder ignoreExternal(boolean ignoreExternal) { this.ignoreExternal = ignoreExternal; return this; } /** * Automatically download referenced resource. * * @return Builder. */ public FetchResourceHandler.Builder fetchResource() { return this.fetchResource = new FetchResourceHandler.Builder(); } /** * Custom processor invoked pointing to attribute data - e.g. in case of <code>&lt;img&gt;</code> tag * the processor gets contents of the <code>src</code> attribute. * * @return Builder. */ public ServiceLoadedBuilderProvider<Processor.Builder> processor() { return processors().processor(); } @Embed public MultiProcessor.Builder<EmbeddedResourceHandlerBuilder, ?> processors() { return processors; } @Override public HtmlHandler.BaseTagAttributeHandler build() { if (processors.isEmpty() && fetchResource == null) { throw new BenchmarkDefinitionException("embedded resource handler must define either processor or fetchResource!"); } Processor processor = processors.isEmpty() ? null : processors.build(false); FetchResourceHandler fetchResource = this.fetchResource != null ? this.fetchResource.build() : null; return new HtmlHandler.BaseTagAttributeHandler(TAGS, ATTRS, new EmbeddedResourceProcessor(ignoreExternal, processor, fetchResource)); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/FetchResourceHandler.java
http/src/main/java/io/hyperfoil/http/html/FetchResourceHandler.java
package io.hyperfoil.http.html; import static io.hyperfoil.core.session.SessionFactory.sequenceScopedObjectAccess; import static io.hyperfoil.core.session.SessionFactory.sequenceScopedReadAccess; import java.io.Serializable; import java.util.concurrent.ThreadLocalRandom; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.SequenceBuilder; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.core.data.LimitedPoolResource; import io.hyperfoil.core.data.Queue; import io.hyperfoil.core.metric.AuthorityAndPathMetric; import io.hyperfoil.core.metric.MetricSelector; import io.hyperfoil.core.metric.PathMetricSelector; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.util.Unique; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.handlers.Location; import io.hyperfoil.http.steps.HttpRequestStepBuilder; public class FetchResourceHandler implements Serializable, ResourceUtilizer { private final ObjectAccess var; private final int maxResources; private final String sequence; private final int concurrency; private final Action onCompletion; private final Queue.Key queueKey; private final LimitedPoolResource.Key<Location> locationPoolKey; public FetchResourceHandler(Queue.Key queueKey, LimitedPoolResource.Key<Location> locationPoolKey, ObjectAccess var, int maxResources, String sequence, int concurrency, Action onCompletion) { this.queueKey = queueKey; this.locationPoolKey = locationPoolKey; this.var = var; this.maxResources = maxResources; this.sequence = sequence; this.concurrency = concurrency; this.onCompletion = onCompletion; } public void before(Session session) { Queue queue = session.getResource(queueKey); queue.reset(session); } public void handle(Session session, CharSequence authority, CharSequence path) { Queue queue = session.getResource(queueKey); LimitedPoolResource<Location> locationPool = session.getResource(locationPoolKey); Location location = locationPool.acquire(); location.authority = authority; location.path = path; queue.push(session, location); } public void after(Session session) { Queue queue = session.getResource(queueKey); queue.producerComplete(session); } @Override public void reserve(Session session) { // If there are multiple concurrent requests all the data end up in single queue; // there's no way to set up different output var so merging them is the only useful behaviour. if (!var.isSet(session)) { var.setObject(session, ObjectVar.newArray(session, concurrency)); } session.declareResource(queueKey, () -> new Queue(var, maxResources, concurrency, sequence, onCompletion), true); session.declareResource(locationPoolKey, () -> LimitedPoolResource.create(maxResources, Location.class, Location::new), true); } /** * Automates download of embedded resources. */ public static class Builder implements BuilderBase<Builder> { private MetricSelector metricSelector; private int maxResources; private int concurrency = 8; private Action.Builder onCompletion; private Queue.Key queueKey; private LimitedPoolResource.Key<Location> locationPoolKey; private ObjectAccess varAccess; private String sequenceName; public Builder() { } /** * Maximum number of resources that can be fetched. * * @param maxResources Max resources. * @return Self. */ public Builder maxResources(int maxResources) { this.maxResources = maxResources; return this; } /** * Maximum number of resources fetched concurrently. Default is 8. * * @param concurrency Max concurrently fetched resources. * @return Self. */ public Builder concurrency(int concurrency) { this.concurrency = concurrency; return this; } /** * Metrics selector for downloaded resources. * * @return Builder. */ public PathMetricSelector metric() { PathMetricSelector metricSelector = new PathMetricSelector(); metric(metricSelector); return metricSelector; } public Builder metric(MetricSelector metricSelector) { if (this.metricSelector != null) { throw new BenchmarkDefinitionException("Metric already set!"); } this.metricSelector = metricSelector; return this; } /** * Action performed when the download of all resources completes. * * @return Builder. */ public ServiceLoadedBuilderProvider<Action.Builder> onCompletion() { return new ServiceLoadedBuilderProvider<>(Action.Builder.class, this::onCompletion); } public Builder onCompletion(Action.Builder onCompletion) { this.onCompletion = onCompletion; return this; } public void prepareBuild() { queueKey = new Queue.Key(); locationPoolKey = new LimitedPoolResource.Key<>(); Locator locator = Locator.current(); sequenceName = String.format("%s_fetchResources_%08x", locator.sequence().name(), ThreadLocalRandom.current().nextInt()); Unique locationVar = new Unique(); varAccess = SessionFactory.objectAccess(locationVar); // We'll keep the request synchronous to keep the session running while the resources are fetched // even if the benchmark did not specify any completion action. HttpRequestStepBuilder requestBuilder = new HttpRequestStepBuilder().sync(true).method(HttpMethod.GET); requestBuilder.path(() -> new Location.GetPath(sequenceScopedReadAccess(locationVar))); requestBuilder.authority(() -> new Location.GetAuthority(sequenceScopedReadAccess(locationVar))); if (metricSelector != null) { requestBuilder.metric(metricSelector); } else { // Rather than using auto-generated sequence name we'll use the full path requestBuilder.metric(new AuthorityAndPathMetric()); } SequenceBuilder sequence = locator.scenario().sequence(sequenceName).concurrency(concurrency); sequence.stepBuilder(requestBuilder); var myQueueKey = queueKey; // prevent capturing self reference var myPoolKey = locationPoolKey; requestBuilder.handler() .onCompletion(() -> new Location.Complete<>(myPoolKey, myQueueKey, sequenceScopedObjectAccess(locationVar))); // As we're preparing build, the list of sequences-to-be-prepared is already final and we need to prepare // this one manually sequence.prepareBuild(); } public FetchResourceHandler build() { if (maxResources <= 0) { throw new BenchmarkDefinitionException("Maximum size for queue must be set!"); } Action onCompletion = this.onCompletion == null ? null : this.onCompletion.build(); return new FetchResourceHandler(queueKey, locationPoolKey, varAccess, maxResources, sequenceName, concurrency, onCompletion); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/html/HtmlHandler.java
http/src/main/java/io/hyperfoil/http/html/HtmlHandler.java
package io.hyperfoil.http.html; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.util.Trie; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; public class HtmlHandler implements Processor, ResourceUtilizer, Session.ResourceKey<HtmlHandler.Context> { private static final Logger log = LogManager.getLogger(HtmlHandler.class); private static final boolean trace = log.isTraceEnabled(); private static final byte[] SCRIPT = "script".getBytes(StandardCharsets.UTF_8); private final TagHandler[] handlers; private HtmlHandler(TagHandler... handlers) { this.handlers = handlers; } @Override public void before(Session session) { for (TagHandler h : handlers) { h.processor().before(session); } } @Override public void after(Session session) { for (TagHandler h : handlers) { h.processor().after(session); } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { Context ctx = session.getResource(this); switch (ctx.tagStatus) { case PARSING_TAG: ctx.tagStart = offset; break; case PARSING_ATTR: ctx.attrStart = offset; break; case PARSING_VALUE: ctx.valueStart = offset; break; } while (length > 0) { byte c = data.getByte(offset++); --length; switch (ctx.tagStatus) { case NO_TAG: if (c == '<') { ctx.tagStatus = TagStatus.ENTERED; } break; case ENTERED: if (c == '!') { ctx.tagStatus = TagStatus.DOCTYPE_START; } else if (Character.isWhitespace(c)) { ctx.tagStatus = TagStatus.BEFORE_TAG; } else if (c == '/') { ctx.tagClosing = true; ctx.tagStatus = TagStatus.BEFORE_TAG; } else { ctx.tagStart = offset - 1; ctx.tagStatus = TagStatus.PARSING_TAG; } break; case DOCTYPE_START: if (c == '-') { ctx.comment = 3; ctx.tagStatus = TagStatus.COMMENT; } else { ctx.tagStatus = TagStatus.DOCTYPE; } break; case DOCTYPE: if (c == '>') { ctx.endTag(session); } break; case COMMENT: if (ctx.comment == 1) { if (c == '>') { ctx.comment = 0; ctx.tagStatus = TagStatus.NO_TAG; } else if (c != '-') { ctx.comment = 3; } } else if (ctx.comment > 0) { if (c == '-') { ctx.comment--; } } break; case BEFORE_TAG: if (!Character.isWhitespace(c)) { ctx.tagStatus = TagStatus.PARSING_TAG; ctx.tagStart = offset - 1; } break; case PARSING_TAG: if (Character.isWhitespace(c)) { // setting the tag status before to let onTag overwrite it ctx.tagStatus = TagStatus.BEFORE_ATTR; ctx.onTag(session, data, offset - 1, true); } else if (c == '>') { ctx.onTag(session, data, offset - 1, true); ctx.endTag(session); } break; case BEFORE_ATTR: if (c == '>') { ctx.endTag(session); } else if (c == '/') { ctx.tagClosing = true; } else if (!Character.isWhitespace(c)) { ctx.attrStart = offset - 1; ctx.tagStatus = TagStatus.PARSING_ATTR; ctx.tagClosing = false; } break; case PARSING_ATTR: if (c == '=' || Character.isWhitespace(c)) { ctx.onAttr(session, data, offset - 1, true); ctx.tagStatus = TagStatus.BEFORE_VALUE; } else if (c == '/') { ctx.tagClosing = true; } else if (c == '>') { ctx.onAttr(session, data, offset - 1, true); ctx.endTag(session); } break; case BEFORE_VALUE: if (c == '>') { ctx.endTag(session); } else if (c == '=' || Character.isWhitespace(c)) { // ignore, there was a whitespace break; } else if (c == '"') { ctx.tagStatus = TagStatus.PARSING_VALUE; ctx.valueStart = offset; ctx.valueQuoted = true; } else { // missing quotes ctx.tagStatus = TagStatus.PARSING_VALUE; ctx.valueStart = offset - 1; } break; case PARSING_VALUE: if (c == '\\') { ctx.charEscaped = true; } else if (c == '"' && !ctx.charEscaped) { ctx.onValue(session, data, offset - 1, true); ctx.tagStatus = TagStatus.BEFORE_ATTR; ctx.valueQuoted = false; } else if (!ctx.valueQuoted && Character.isWhitespace(c)) { ctx.onValue(session, data, offset - 1, true); ctx.tagStatus = TagStatus.BEFORE_ATTR; } else { ctx.charEscaped = false; } break; default: throw new IllegalStateException(); } } switch (ctx.tagStatus) { case PARSING_TAG: ctx.onTag(session, data, offset, false); break; case PARSING_ATTR: ctx.onAttr(session, data, offset, false); break; case PARSING_VALUE: ctx.onValue(session, data, offset, false); break; } } @Override public void reserve(Session session) { session.declareResource(this, Context::new); } public interface TagHandlerBuilder<S extends TagHandlerBuilder<S>> extends BuilderBase<S> { TagHandler build(); } public interface TagHandler extends Serializable { Processor processor(); HandlerContext newContext(); } enum TagStatus { NO_TAG, ENTERED, BEFORE_TAG, PARSING_TAG, BEFORE_ATTR, PARSING_ATTR, DOCTYPE_START, // doctype, comment DOCTYPE, BEFORE_VALUE, PARSING_VALUE, COMMENT, } class Context implements Session.Resource { TagStatus tagStatus = TagStatus.NO_TAG; boolean valueQuoted; boolean charEscaped; boolean tagClosing; int tagStart = -1; int attrStart = -1; int valueStart = -1; int comment; // We need alternative parsing when Match scriptMatch = new Match(); boolean inScript; HandlerContext[] handlerCtx; Context() { handlerCtx = Stream.of(handlers).map(TagHandler::newContext).toArray(HandlerContext[]::new); } @Override public void destroy() { for (HandlerContext ctx : handlerCtx) { ctx.destroy(); } } void onTag(Session session, ByteBuf data, int tagEnd, boolean isLast) { assert tagStart >= 0; scriptMatch.shift(data, tagStart, tagEnd - tagStart, isLast, SCRIPT); if (inScript && !(tagClosing && scriptMatch.hasMatch())) { // this is not a tag tagStart = -1; tagStatus = TagStatus.NO_TAG; return; } for (HandlerContext handlerCtx : handlerCtx) { handlerCtx.onTag(session, tagClosing, data, tagStart, tagEnd - tagStart, isLast); } tagStart = -1; } void onAttr(Session session, ByteBuf data, int attrEnd, boolean isLast) { assert attrStart >= 0; for (HandlerContext handlerCtx : handlerCtx) { handlerCtx.onAttr(session, data, attrStart, attrEnd - attrStart, isLast); } attrStart = -1; } void onValue(Session session, ByteBuf data, int valueEnd, boolean isLast) { assert valueStart >= 0; for (HandlerContext handlerCtx : handlerCtx) { handlerCtx.onValue(session, data, valueStart, valueEnd - valueStart, isLast); } valueStart = -1; } // TODO: content handling private void endTag(Session session) { if (!inScript && !tagClosing && scriptMatch.hasMatch()) { inScript = true; } else if (inScript && tagClosing && scriptMatch.hasMatch()) { inScript = false; } scriptMatch.reset(); for (int i = 0; i < handlerCtx.length; ++i) { handlerCtx[i].endTag(session, tagClosing); } tagStatus = TagStatus.NO_TAG; tagClosing = false; } } interface HandlerContext { /** * Called upon both opening (&lt;foo&gt;), closing (&lt;/foo&gt;) and self-closing (&lt<foo /&gt;) element. * Since there's no buffering the element name might be only partial - check the <code>isLast</code> parameter. * * @param session Current session. * @param close Is it the closing (&lt;/foo&gt;) form? * @param data Buffer with element name. * @param offset Starting index in the buffer. * @param length Number of bytes in the buffer that contain the name. * @param isLast True if the element name is complete. */ // TODO: this API does not inform if the element is self-closing! Make close into enum void onTag(Session session, boolean close, ByteBuf data, int offset, int length, boolean isLast); void onAttr(Session session, ByteBuf data, int offset, int length, boolean isLast); void onValue(Session session, ByteBuf data, int offset, int length, boolean isLast); /** * Called when the &gt; is reached while parsing a tag (opening, closing or self-closing). * * @param session Current session. * @param closing Set to true if this is closing or self-closing tag. */ void endTag(Session session, boolean closing); void destroy(); } /** * Parses HTML tags and invokes handlers based on criteria. */ @MetaInfServices(Processor.Builder.class) @Name("parseHtml") public static class Builder implements Processor.Builder { private List<TagHandlerBuilder<?>> handlers = new ArrayList<>(); /** * Handler firing upon reference to other resource, e.g. image, stylesheet... * * @return Builder. */ public EmbeddedResourceHandlerBuilder onEmbeddedResource() { if (handlers.stream().anyMatch(EmbeddedResourceHandlerBuilder.class::isInstance)) { throw new BenchmarkDefinitionException("Embedded resource handler already set!"); } EmbeddedResourceHandlerBuilder builder = new EmbeddedResourceHandlerBuilder(); handler(builder); return builder; } public TagAttributeHandlerBuilder onTagAttribute() { TagAttributeHandlerBuilder builder = new TagAttributeHandlerBuilder(); handler(builder); return builder; } public Builder handler(TagHandlerBuilder<?> handler) { handlers.add(handler); return this; } @Override public HtmlHandler build(boolean fragmented) { TagHandler[] tagHandlers = handlers.stream().map(TagHandlerBuilder::build).toArray(TagHandler[]::new); return new HtmlHandler(tagHandlers); } } static class BaseTagAttributeHandler implements TagHandler { private final Trie trie; private final byte[][] attributes; private final Processor processor; BaseTagAttributeHandler(String[] tags, String[] attributes, Processor processor) { this.processor = processor; if (tags.length != attributes.length) { throw new IllegalArgumentException(); } this.trie = new Trie(Arrays.stream(tags).map(tag -> tag.toLowerCase(Locale.ROOT)).toArray(String[]::new)); this.attributes = Stream.of(attributes) .map(s -> s.toLowerCase(Locale.ROOT).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new); } @Override public Processor processor() { return processor; } @Override public HandlerContext newContext() { return new Ctx(); } protected class Ctx implements HandlerContext { private final Trie.State trieState = trie.newState(); private int tagMatched = -1; private int attrMatchedIndex = -1; private final ByteBuf valueBuffer = ByteBufAllocator.DEFAULT.buffer(); @Override public void onTag(Session session, boolean close, ByteBuf data, int offset, int length, boolean isLast) { for (int i = 0; i < length; ++i) { int terminal = trieState.next(Util.toLowerCase(data.getByte(offset + i))); if (isLast && terminal >= 0) { tagMatched = terminal; attrMatchedIndex = 0; } } } @Override public void onAttr(Session session, ByteBuf data, int offset, int length, boolean isLast) { if (tagMatched < 0) { return; } if (attrMatchedIndex >= 0) { for (int i = 0; i < length; ++i) { if (attrMatchedIndex >= attributes[tagMatched].length) { attrMatchedIndex = -1; break; } else if (attributes[tagMatched][attrMatchedIndex] == Util.toLowerCase(data.getByte(offset + i))) { attrMatchedIndex++; } else { attrMatchedIndex = -1; break; } } } if (isLast) { if (attrMatchedIndex != attributes[tagMatched].length) { attrMatchedIndex = 0; } // otherwise keep matched positive for value } } @Override public void onValue(Session session, ByteBuf data, int offset, int length, boolean isLast) { if (tagMatched < 0 || attrMatchedIndex <= 0) { return; } valueBuffer.ensureWritable(length); valueBuffer.writeBytes(data, offset, length); if (isLast) { processor().process(session, valueBuffer, valueBuffer.readerIndex(), valueBuffer.readableBytes(), true); valueBuffer.clear(); attrMatchedIndex = 0; } } @Override public void endTag(Session session, boolean closing) { trieState.reset(); tagMatched = -1; attrMatchedIndex = -1; } @Override public void destroy() { valueBuffer.release(); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/StatusHandler.java
http/src/main/java/io/hyperfoil/http/api/StatusHandler.java
package io.hyperfoil.http.api; import java.io.Serializable; import io.hyperfoil.api.config.BuilderBase; public interface StatusHandler extends Serializable { void handleStatus(HttpRequest request, int status); interface Builder extends BuilderBase<Builder> { StatusHandler build(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HeaderHandler.java
http/src/main/java/io/hyperfoil/http/api/HeaderHandler.java
package io.hyperfoil.http.api; import java.io.Serializable; import io.hyperfoil.api.config.BuilderBase; public interface HeaderHandler extends Serializable { default void beforeHeaders(HttpRequest request) { } void handleHeader(HttpRequest request, CharSequence header, CharSequence value); default void afterHeaders(HttpRequest request) { } interface Builder extends BuilderBase<Builder> { HeaderHandler build(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpRequest.java
http/src/main/java/io/hyperfoil/http/api/HttpRequest.java
package io.hyperfoil.http.api; import java.util.function.BiConsumer; import java.util.function.BiFunction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.FormattedMessage; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.http.HttpRequestPool; import io.hyperfoil.http.statistics.HttpStats; import io.netty.buffer.ByteBuf; public class HttpRequest extends Request { public static final Logger log = LogManager.getLogger(HttpRequest.class); public HttpResponseHandlers handlers; public HttpMethod method; public String authority; public String path; public final CacheControl cacheControl; private HttpConnectionPool pool; public HttpRequest(Session session, boolean httpCacheEnabled) { super(session); this.cacheControl = httpCacheEnabled ? new CacheControl() : null; } public static HttpRequest ensure(Request request) { if (request instanceof HttpRequest) { return (HttpRequest) request; } else { log.error("#{}: Expected HttpRequest, got {}", request.session.uniqueId(), request); return null; } } public void start(HttpConnectionPool pool, HttpResponseHandlers handlers, SequenceInstance sequence, Statistics statistics) { this.handlers = handlers; this.pool = pool; start(sequence, statistics); } public void send(HttpConnection connection, BiConsumer<Session, HttpRequestWriter>[] headerAppenders, boolean injectHostHeader, BiFunction<Session, Connection, ByteBuf> bodyGenerator) { if (session.currentRequest() != null) { // Refuse to fire request from other request's handler as the other handlers // would have messed up current request in session. // Handlers must not block anyway, so this is illegal way to run request // and happens only with programmatic configuration in testsuite. throw new IllegalStateException(String.format( "#%d Invoking request directly from a request handler; current: %s, requested %s", session.uniqueId(), session.currentRequest(), this)); } attach(connection); connection.attach(pool); connection.request(this, headerAppenders, injectHostHeader, bodyGenerator); } @Override public HttpConnection connection() { return (HttpConnection) super.connection(); } @Override public void setCompleted() { super.setCompleted(); this.handlers = null; this.method = null; this.authority = null; this.path = null; this.pool = null; if (this.cacheControl != null) { this.cacheControl.reset(); } } public HttpResponseHandlers handlers() { return handlers; } @Override public String toString() { return super.toString() + " " + method + " " + authority + path; } @Override public void release() { if (status() != Status.IDLE) { HttpRequestPool.get(session).release(this); setIdle(); } } public void handleCached() { HttpStats.addCacheHit(statistics(), startTimestampMillis()); enter(); try { handlers.handleEnd(this, false); } catch (SessionStopException e) { // ignore, other exceptions would propagate } finally { exit(); release(); } session.proceed(); } public void cancel(Throwable cause) { if (isRunning()) { enter(); try { handlers.handleThrowable(this, cause); } catch (SessionStopException e) { // ignore - the cancelled request decided to stop its session, too } catch (Exception e) { log.error(new FormattedMessage("{} {} threw an exception when cancelling", session.uniqueId(), this), e); } finally { exit(); release(); } session.proceed(); } } /** * Checks if the cache control is set. * Worth to note that, if this is true the tool guarantees that HttpCache.get(request.session) is not null. * * @return {@code true} if {@code cacheControl} is not {@code null}, * indicating that HTTP cache is enabled; {@code false} otherwise. */ public boolean hasCacheControl() { return this.cacheControl != null; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpVersion.java
http/src/main/java/io/hyperfoil/http/api/HttpVersion.java
package io.hyperfoil.http.api; public enum HttpVersion { HTTP_1_0("http/1.0"), HTTP_1_1("http/1.1"), HTTP_2_0("h2"); public static final HttpVersion[] ALL_VERSIONS = { HTTP_2_0, HTTP_1_1, HTTP_1_0 }; public final String protocolName; HttpVersion(String protocolName) { this.protocolName = protocolName; } public String protocolName() { return protocolName; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpCache.java
http/src/main/java/io/hyperfoil/http/api/HttpCache.java
package io.hyperfoil.http.api; import io.hyperfoil.api.session.Session; public interface HttpCache extends Session.Resource { Session.ResourceKey<HttpCache> KEY = new Session.ResourceKey<>() { }; void beforeRequestHeaders(HttpRequest request); void requestHeader(HttpRequest request, CharSequence header, CharSequence value); boolean isCached(HttpRequest request, HttpRequestWriter writer); void responseHeader(HttpRequest request, CharSequence header, CharSequence value); void tryStore(HttpRequest request); void invalidate(CharSequence authority, CharSequence path); // mostly for testing int size(); void clear(); interface Record { } static HttpCache get(Session session) { return session.getResource(KEY); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpConnectionPool.java
http/src/main/java/io/hyperfoil/http/api/HttpConnectionPool.java
package io.hyperfoil.http.api; import java.util.Collection; import io.hyperfoil.core.impl.ConnectionStatsConsumer; import io.netty.channel.EventLoop; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; public interface HttpConnectionPool { HttpClientPool clientPool(); void acquire(boolean exclusiveConnection, ConnectionConsumer consumer); void afterRequestSent(HttpConnection connection); int waitingSessions(); EventLoop executor(); void pulse(); Collection<? extends HttpConnection> connections(); void release(HttpConnection connection, boolean becameAvailable, boolean afterRequest); void onSessionReset(); void incrementInFlight(); void decrementInFlight(); void visitConnectionStats(ConnectionStatsConsumer consumer); void start(Handler<AsyncResult<Void>> handler); void shutdown(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/ConnectionConsumer.java
http/src/main/java/io/hyperfoil/http/api/ConnectionConsumer.java
package io.hyperfoil.http.api; public interface ConnectionConsumer { void accept(HttpConnection connection); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpClientPool.java
http/src/main/java/io/hyperfoil/http/api/HttpClientPool.java
/* * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hyperfoil.http.api; import io.hyperfoil.core.impl.ConnectionStatsConsumer; import io.hyperfoil.http.config.Http; import io.netty.util.concurrent.EventExecutor; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; /** * Manages access to single host (identified by the same URL), keeping a {@link HttpConnectionPool} for each executor. */ public interface HttpClientPool { Http config(); void start(Handler<AsyncResult<Void>> completionHandler); void shutdown(); HttpConnectionPool next(); HttpConnectionPool connectionPool(EventExecutor executor); String host(); String authority(); byte[] originalDestinationBytes(); String scheme(); boolean isSecure(); void visitConnectionStats(ConnectionStatsConsumer consumer); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/CacheControl.java
http/src/main/java/io/hyperfoil/http/api/CacheControl.java
package io.hyperfoil.http.api; import java.util.ArrayList; import java.util.List; public class CacheControl { public boolean noCache; public boolean noStore; public boolean onlyIfCached; public boolean ignoreExpires; // TODO: We're allocating iterator in this collection for removal // TODO: also optimize more for removal in the middle public List<HttpCache.Record> matchingCached = new ArrayList<>(4); public boolean invalidate; public boolean responseNoCache; public boolean responseMustRevalidate; public long responseExpires = Long.MIN_VALUE; public int responseAge; public int responseMaxAge; public CharSequence responseEtag; public long responseDate = Long.MIN_VALUE; public long responseLastModified = Long.MIN_VALUE; public boolean wasCached; public void reset() { noCache = false; noStore = false; onlyIfCached = false; ignoreExpires = false; matchingCached.clear(); invalidate = false; responseNoCache = false; responseMustRevalidate = false; responseExpires = Long.MIN_VALUE; responseAge = 0; responseMaxAge = 0; responseEtag = null; responseDate = Long.MIN_VALUE; responseLastModified = Long.MIN_VALUE; wasCached = false; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpRequestWriter.java
http/src/main/java/io/hyperfoil/http/api/HttpRequestWriter.java
package io.hyperfoil.http.api; public interface HttpRequestWriter { HttpConnection connection(); HttpRequest request(); void putHeader(CharSequence header, CharSequence value); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpMethod.java
http/src/main/java/io/hyperfoil/http/api/HttpMethod.java
/* * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hyperfoil.http.api; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.session.Session; import io.hyperfoil.function.SerializableFunction; public enum HttpMethod { GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH, TRACE, CONNECT; public final io.netty.handler.codec.http.HttpMethod netty; HttpMethod() { this.netty = io.netty.handler.codec.http.HttpMethod.valueOf(name()); } @FunctionalInterface public interface Builder extends BuilderBase<Builder> { SerializableFunction<Session, HttpMethod> build(); } public static class Provided implements SerializableFunction<Session, HttpMethod> { private final HttpMethod method; public Provided(HttpMethod method) { this.method = method; } @Override public HttpMethod apply(Session o) { return method; } } public static class ProvidedBuilder implements HttpMethod.Builder { private HttpMethod method; public ProvidedBuilder(ProvidedBuilder other) { this.method = other.method; } public ProvidedBuilder(HttpMethod method) { this.method = method; } @Override public SerializableFunction<Session, HttpMethod> build() { return new Provided(method); } @Override public String toString() { return method.name(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpConnection.java
http/src/main/java/io/hyperfoil/http/api/HttpConnection.java
package io.hyperfoil.http.api; import java.util.function.BiConsumer; import java.util.function.BiFunction; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.config.Http; import io.netty.buffer.ByteBuf; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public interface HttpConnection extends Connection { void attach(HttpConnectionPool pool); void request(HttpRequest request, BiConsumer<Session, HttpRequestWriter>[] headerAppenders, boolean injectHostHeader, BiFunction<Session, Connection, ByteBuf> bodyGenerator); HttpRequest dispatchedRequest(); HttpRequest peekRequest(int streamId); boolean removeRequest(int streamId, HttpRequest request); boolean isSecure(); HttpVersion version(); Http config(); HttpConnectionPool pool(); /** * @return Timestamp form System.nanotime() */ long lastUsed(); enum Status { OPEN, CLOSING, CLOSED, } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/FollowRedirect.java
http/src/main/java/io/hyperfoil/http/api/FollowRedirect.java
package io.hyperfoil.http.api; public enum FollowRedirect { /** * Do not insert any automatic redirection handling. */ NEVER, /** * Redirect only upon status 3xx accompanied with a 'location' header. * Status, headers, body and completions handlers are suppressed in this case * (only raw-bytes handlers are still running). * This is the default option. */ LOCATION_ONLY, /** * Handle only HTML response with META refresh header. * Status, headers and body handlers are invoked both on the original response * and on the response from subsequent requests. * Completion handlers are suppressed on this request and invoked after the last * response arrives (in case of multiple redirections). */ HTML_ONLY, /** * Implement both status 3xx + location and HTML redirects. */ ALWAYS, }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpDestinationTable.java
http/src/main/java/io/hyperfoil/http/api/HttpDestinationTable.java
package io.hyperfoil.http.api; import io.hyperfoil.api.session.Session; /** * Manages all {@link HttpConnectionPool http connection pools} for sessions in single executor. */ public interface HttpDestinationTable extends Session.Resource { Session.ResourceKey<HttpDestinationTable> KEY = new Session.ResourceKey<>() { }; HttpConnectionPool getConnectionPoolByName(String endpoint); HttpConnectionPool getConnectionPoolByAuthority(String authority); String[] authorities(); byte[][] authorityBytes(); boolean hasSingleDestination(); static HttpDestinationTable get(Session session) { return session.getResource(KEY); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/api/HttpResponseHandlers.java
http/src/main/java/io/hyperfoil/http/api/HttpResponseHandlers.java
package io.hyperfoil.http.api; import io.hyperfoil.api.connection.ResponseHandlers; import io.netty.buffer.ByteBuf; public interface HttpResponseHandlers extends ResponseHandlers<HttpRequest> { void handleStatus(HttpRequest request, int status, String reason); boolean requiresHandlingHeaders(HttpRequest request); void handleHeader(HttpRequest request, CharSequence header, CharSequence value); void handleBodyPart(HttpRequest request, ByteBuf data, int offset, int length, boolean isLastPart); void handleRawRequest(HttpRequest request, ByteBuf data, int offset, int length); void handleRawResponse(HttpRequest request, ByteBuf data, int offset, int length, boolean isLastPart); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/FilterHeaderHandler.java
http/src/main/java/io/hyperfoil/http/handlers/FilterHeaderHandler.java
package io.hyperfoil.http.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.StringConditionBuilder; import io.hyperfoil.core.handlers.MultiProcessor; import io.hyperfoil.function.SerializableBiPredicate; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class FilterHeaderHandler implements HeaderHandler { private final SerializableBiPredicate<Session, CharSequence> header; private final Processor processor; public FilterHeaderHandler(SerializableBiPredicate<Session, CharSequence> header, Processor processor) { this.header = header; this.processor = processor; } @Override public void beforeHeaders(HttpRequest request) { this.processor.before(request.session); } @Override public void afterHeaders(HttpRequest request) { this.processor.after(request.session); } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { if (this.header.test(request.session, header)) { if (value == null || value.length() == 0) { processor.process(request.session, Unpooled.EMPTY_BUFFER, 0, 0, true); } else { ByteBuf byteBuf = Util.string2byteBuf(value, request.connection().context().alloc().buffer()); try { processor.process(request.session, byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes(), true); } finally { byteBuf.release(); } } } } /** * Compares if the header name matches expression and invokes a processor with the value. */ @MetaInfServices(HeaderHandler.Builder.class) @Name("filter") public static class Builder implements HeaderHandler.Builder { private StringConditionBuilder<?, Builder> header = new StringConditionBuilder<>(this).caseSensitive(false); @Embed public MultiProcessor.Builder<Builder, ?> processors = new MultiProcessor.Builder<>(this); @Override public FilterHeaderHandler build() { if (processors.isEmpty()) { throw new BenchmarkDefinitionException("Processor was not set!"); } Processor processor = processors.buildSingle(false); return new FilterHeaderHandler(header.buildPredicate(), processor); } /** * Condition on the header name. * * @return Builder. */ public StringConditionBuilder<?, Builder> header() { return header; } public Builder processor(Processor.Builder processor) { processors.processor(processor); return this; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/MultiplexStatusHandler.java
http/src/main/java/io/hyperfoil/http/handlers/MultiplexStatusHandler.java
package io.hyperfoil.http.handlers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.PartialBuilder; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; public class MultiplexStatusHandler extends BaseRangeStatusHandler { private final StatusHandler[][] handlers; private final StatusHandler[] other; public MultiplexStatusHandler(int[] ranges, StatusHandler[][] handlers, StatusHandler[] other) { super(ranges); this.handlers = handlers; this.other = other; } @Override protected void onStatusRange(HttpRequest request, int status, int index) { for (StatusHandler h : handlers[index]) { h.handleStatus(request, status); } } @Override protected void onOtherStatus(HttpRequest request, int status) { if (other != null) { for (StatusHandler h : other) { h.handleStatus(request, status); } } } /** * Multiplexes the status based on range into different status handlers. */ @MetaInfServices(StatusHandler.Builder.class) @Name("multiplex") public static class Builder implements StatusHandler.Builder, PartialBuilder { private final Map<String, List<StatusHandler.Builder>> handlers = new HashMap<>(); /** * Run another handler if the range matches. Use range as the key and another status handler in the mapping. * Possible values of the status should be separated by commas (,). Ranges can be set using low-high (inclusive) (e.g. * 200-299), or replacing lower digits with 'x' (e.g. 2xx). * * @param range Status range. * @return Builder */ @Override public ServiceLoadedBuilderProvider<StatusHandler.Builder> withKey(String range) { List<StatusHandler.Builder> handlers = new ArrayList<>(); add(range, handlers); return new ServiceLoadedBuilderProvider<>(StatusHandler.Builder.class, handlers::add); } public Builder add(String range, List<StatusHandler.Builder> handlers) { if (this.handlers.putIfAbsent(range, handlers) != null) { throw new BenchmarkDefinitionException("Range '" + range + "' is already set."); } return this; } @Override public MultiplexStatusHandler build() { List<Integer> ranges = new ArrayList<>(); List<StatusHandler[]> handlers = new ArrayList<>(); StatusHandler[] other = checkAndSortRanges(this.handlers, ranges, handlers, list -> list.stream().map(StatusHandler.Builder::build).toArray(StatusHandler[]::new)); return new MultiplexStatusHandler(ranges.stream().mapToInt(Integer::intValue).toArray(), handlers.toArray(new StatusHandler[0][]), other); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/Location.java
http/src/main/java/io/hyperfoil/http/handlers/Location.java
package io.hyperfoil.http.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.LimitedPoolResource; import io.hyperfoil.core.data.Queue; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.function.SerializableFunction; public class Location { private static final Logger log = LogManager.getLogger(Location.class); private static final boolean trace = log.isTraceEnabled(); public CharSequence authority; public CharSequence path; public Location reset() { authority = null; path = null; return this; } public static class GetAuthority implements SerializableFunction<Session, String> { private final ReadAccess locationVar; public GetAuthority(ReadAccess locationVar) { this.locationVar = locationVar; } @Override public String apply(Session session) { Location location = (Location) locationVar.getObject(session); return location.authority == null ? null : location.authority.toString(); } } public static class GetPath implements SerializableFunction<Session, String> { private final ReadAccess locationVar; public GetPath(ReadAccess locationVar) { this.locationVar = locationVar; } @Override public String apply(Session session) { Location location = (Location) locationVar.getObject(session); return location.path.toString(); } } public static class Complete<T extends Location> implements Action { private final LimitedPoolResource.Key<T> poolKey; private final Session.ResourceKey<Queue> queueKey; private final ObjectAccess locationVar; public Complete(LimitedPoolResource.Key<T> poolKey, Queue.Key queueKey, ObjectAccess locationVar) { this.poolKey = poolKey; this.queueKey = queueKey; this.locationVar = locationVar; } @Override public void run(Session session) { LimitedPoolResource<T> pool = session.getResource(poolKey); ObjectVar var = (ObjectVar) locationVar.getVar(session); Location location = (Location) var.objectValue(session); if (trace) { log.trace("#{} releasing {} from {}[{}]", session.uniqueId(), location, locationVar, session.currentSequence().index()); } @SuppressWarnings("unchecked") T castLocation = (T) location.reset(); pool.release(castLocation); var.set(null); var.unset(); session.getResource(queueKey).consumed(session); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/BaseDelegatingStatusHandler.java
http/src/main/java/io/hyperfoil/http/handlers/BaseDelegatingStatusHandler.java
package io.hyperfoil.http.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; public abstract class BaseDelegatingStatusHandler implements StatusHandler { protected final StatusHandler[] handlers; public BaseDelegatingStatusHandler(StatusHandler[] handlers) { this.handlers = handlers; } @Override public void handleStatus(HttpRequest request, int status) { for (StatusHandler handler : handlers) { handler.handleStatus(request, status); } } public abstract static class Builder<S extends Builder<S>> implements StatusHandler.Builder { private final List<StatusHandler.Builder> handlers = new ArrayList<>(); @SuppressWarnings("unchecked") public S handlers(Collection<? extends StatusHandler.Builder> handlers) { this.handlers.addAll(handlers); return (S) this; } protected StatusHandler[] buildHandlers() { return handlers.stream().map(StatusHandler.Builder::build).toArray(StatusHandler[]::new); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/RangeStatusValidator.java
http/src/main/java/io/hyperfoil/http/handlers/RangeStatusValidator.java
package io.hyperfoil.http.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; import io.hyperfoil.impl.Util; public class RangeStatusValidator implements StatusHandler { private static final Logger log = LogManager.getLogger(RangeStatusValidator.class); public final int min; public final int max; public RangeStatusValidator(int min, int max) { this.min = min; this.max = max; } @Override public void handleStatus(HttpRequest request, int status) { boolean valid = status >= min && status <= max; if (!valid) { request.markInvalid(); log.warn("#{} Sequence {}, request {} on connection {} received invalid status {}", request.session.uniqueId(), request.sequence(), request, request.connection(), status); } } /** * Marks requests that don't fall into the desired range as invalid. */ @MetaInfServices(StatusHandler.Builder.class) @Name("range") public static class Builder implements StatusHandler.Builder, InitFromParam<Builder> { private int min = 200; private int max = 299; /** * @param param Single status code (<code>204</code>), masked code (<code>2xx</code>) or range (<code>200-399</code>). * @return Self. */ @Override public Builder init(String param) { int xn = 0; for (int i = param.length() - 1; i >= 0; --i) { if (param.charAt(i) == 'x') { ++xn; } else break; } try { int dash = param.indexOf('-'); if (dash >= 0) { min = Integer.parseInt(param.substring(0, dash).trim()); max = Integer.parseInt(param.substring(dash + 1).trim()); } else { int value = Integer.parseInt(param.substring(0, param.length() - xn)); int mul = Util.pow(10, xn); min = value * mul; max = (value + 1) * mul - 1; } } catch (NumberFormatException e) { throw new BenchmarkDefinitionException("Cannot parse '" + param + "' as status range"); } return this; } @Override public RangeStatusValidator build() { return new RangeStatusValidator(min, max); } /** * Lowest accepted status code. * * @param min Minimum status (inclusive). * @return Self. */ public Builder min(int min) { this.min = min; return this; } /** * Highest accepted status code. * * @param max Maximum status (inclusive) * @return Self. */ public Builder max(int max) { this.max = max; return this; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/LogInvalidHandler.java
http/src/main/java/io/hyperfoil/http/handlers/LogInvalidHandler.java
package io.hyperfoil.http.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; public class LogInvalidHandler implements Processor, HeaderHandler { private static final Logger log = LogManager.getLogger(LogInvalidHandler.class); @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLast) { Request request = session.currentRequest(); if (request != null && !request.isValid()) { if (request instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) request; log.debug("#{}: {} {}/{}, {} bytes: {}", session.uniqueId(), httpRequest.method, httpRequest.authority, httpRequest.path, data.readableBytes(), Util.toString(data, data.readerIndex(), data.readableBytes())); } else { log.debug("#{}: {} bytes: {}", session.uniqueId(), data.readableBytes(), Util.toString(data, data.readerIndex(), data.readableBytes())); } } } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { if (!request.isValid()) { log.debug("#{}: {} {}/{}, {}: {}", request.session.uniqueId(), request.method, request.authority, request.path, header, value); } } /** * Logs body chunks from requests marked as invalid. */ @MetaInfServices(Processor.Builder.class) @Name("logInvalid") public static class BodyHandlerBuilder implements Processor.Builder { @Override public LogInvalidHandler build(boolean fragmented) { return new LogInvalidHandler(); } } /** * Logs headers from requests marked as invalid. */ @MetaInfServices(HeaderHandler.Builder.class) @Name("logInvalid") public static class HeaderHandlerBuilder implements HeaderHandler.Builder { @Override public LogInvalidHandler build() { return new LogInvalidHandler(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/RecordHeaderTimeHandler.java
http/src/main/java/io/hyperfoil/http/handlers/RecordHeaderTimeHandler.java
package io.hyperfoil.http.handlers; import java.util.concurrent.TimeUnit; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.function.SerializableToLongFunction; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.impl.Util; import io.netty.util.AsciiString; public class RecordHeaderTimeHandler implements HeaderHandler { private final int stepId; private final String header; private final String statistics; private final SerializableToLongFunction<CharSequence> transform; private transient AsciiString asciiHeader; public RecordHeaderTimeHandler(int stepId, String header, String statistics, SerializableToLongFunction<CharSequence> transform) { this.stepId = stepId; this.header = header; this.statistics = statistics; this.transform = transform; this.asciiHeader = new AsciiString(header); } private Object readResolve() { this.asciiHeader = new AsciiString(header); return this; } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { if (!asciiHeader.contentEqualsIgnoreCase(header)) { return; } long longValue = transform.applyAsLong(value); if (longValue < 0) { // we're not recording negative values return; } Statistics statistics = request.session.statistics(stepId, this.statistics); // we need to set both requests and responses to calculate stats properly statistics.incrementRequests(request.startTimestampMillis()); statistics.recordResponse(request.startTimestampMillis(), longValue); } /** * Records alternative metric based on values from a header (e.g. when a proxy reports processing time). */ @MetaInfServices(HeaderHandler.Builder.class) @Name("recordHeaderTime") public static class Builder implements HeaderHandler.Builder, InitFromParam<Builder> { private String header; private String metric; private String unit; @Override public Builder init(String param) { header = param; return this; } @Override public RecordHeaderTimeHandler build() { if (header == null || header.isEmpty()) { throw new BenchmarkDefinitionException("Must define the header."); } else if (header.chars().anyMatch(c -> c > 0xFF)) { throw new BenchmarkDefinitionException("Header contains non-ASCII characters."); } if (metric == null) { metric = header; } SerializableToLongFunction<CharSequence> transform = Util::parseLong; if (unit != null) { switch (unit) { case "ms": transform = value -> TimeUnit.MILLISECONDS.toNanos(Util.parseLong(value)); break; case "ns": break; default: throw new BenchmarkDefinitionException("Unknown unit '" + unit + "'"); } } return new RecordHeaderTimeHandler(Locator.current().step().id(), header, metric, transform); } /** * Header carrying the time. * * @param header Header name. * @return Self. */ public Builder header(String header) { this.header = header; return this; } /** * Name of the created metric. * * @param metric Metric name. * @return Self. */ public Builder metric(String metric) { this.metric = metric; return this; } /** * Time unit in the header; use either `ms` or `ns`. * * @param unit Ms or ns. * @return Self. */ public Builder unit(String unit) { this.unit = unit; return this; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/Redirect.java
http/src/main/java/io/hyperfoil/http/handlers/Redirect.java
package io.hyperfoil.http.handlers; import java.util.Objects; import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.LimitedPoolResource; import io.hyperfoil.core.data.Queue; import io.hyperfoil.core.handlers.BaseDelegatingAction; import io.hyperfoil.core.handlers.MultiProcessor; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.http.HttpUtil; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; public class Redirect { private static final Logger log = LogManager.getLogger(Redirect.class); private static final boolean trace = log.isTraceEnabled(); public static class StatusHandler extends BaseDelegatingStatusHandler implements ResourceUtilizer { private final ObjectAccess coordsVar; private final LimitedPoolResource.Key<Coords> poolKey; private final int concurrency; public StatusHandler(ObjectAccess coordsVar, io.hyperfoil.http.api.StatusHandler[] handlers, LimitedPoolResource.Key<Coords> poolKey, int concurrency) { super(handlers); this.coordsVar = coordsVar; this.poolKey = poolKey; this.concurrency = concurrency; } @Override public void handleStatus(HttpRequest request, int status) { Coords coords; switch (status) { case 301: case 302: case 303: coords = request.session.getResource(poolKey).acquire(); coords.method = HttpMethod.GET; coordsVar.setObject(request.session, coords); break; case 307: case 308: coords = request.session.getResource(poolKey).acquire(); coords.method = request.method; coordsVar.setObject(request.session, coords); break; default: coordsVar.unset(request.session); super.handleStatus(request, status); } } @Override public void reserve(Session session) { session.declareResource(poolKey, () -> LimitedPoolResource.create(concurrency, Coords.class, Coords::new), true); } public static class Builder extends BaseDelegatingStatusHandler.Builder<Builder> { private Object coordsVar; private LimitedPoolResource.Key<Coords> poolKey; private int concurrency; public Builder coordsVar(Object coordsVar) { this.coordsVar = coordsVar; return this; } public Builder poolKey(LimitedPoolResource.Key<Coords> poolKey) { this.poolKey = poolKey; return this; } public Builder concurrency(int concurrency) { this.concurrency = concurrency; return this; } @Override public StatusHandler build() { return new StatusHandler(SessionFactory.objectAccess(coordsVar), buildHandlers(), poolKey, concurrency); } } } public static class Coords extends Location { public HttpMethod method; public int delay; public SequenceInstance originalSequence; @Override public Coords reset() { super.reset(); method = null; delay = 0; originalSequence = null; return this; } @Override public String toString() { return method + " " + path; } } public static class LocationRecorder implements HeaderHandler, ResourceUtilizer { private static final String LOCATION = "location"; private final int concurrency; private final Session.ResourceKey<Queue> queueKey; private final ReadAccess inputVar; private final ObjectAccess outputVar; private final String sequence; private final SerializableFunction<Session, SequenceInstance> originalSequenceSupplier; public LocationRecorder(int concurrency, Session.ResourceKey<Queue> queueKey, ReadAccess inputVar, ObjectAccess outputVar, String sequence, SerializableFunction<Session, SequenceInstance> originalSequenceSupplier) { this.concurrency = concurrency; this.queueKey = queueKey; this.inputVar = inputVar; this.outputVar = outputVar; this.sequence = sequence; this.originalSequenceSupplier = originalSequenceSupplier; } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { if (Util.regionMatchesIgnoreCase(header, 0, LOCATION, 0, LOCATION.length())) { Session session = request.session; ObjectVar var = (ObjectVar) inputVar.getVar(session); if (!var.isSet()) { return; } Coords coords = (Coords) var.objectValue(session); if (coords.path == null) { if (!Util.startsWith(value, 0, HttpUtil.HTTP_PREFIX) && !Util.startsWith(value, 0, HttpUtil.HTTPS_PREFIX)) { coords.authority = request.authority; if (!Util.startsWith(value, 0, "/")) { int lastSlash = request.path.lastIndexOf('/'); if (lastSlash < 0) { log.warn("#{} Did the request have a relative path? {}", session.uniqueId(), request.path); value = "/" + value; } value = request.path.substring(0, lastSlash + 1) + value; } } coords.path = value; coords.originalSequence = originalSequenceSupplier.apply(request.session); var.set(coords); Queue queue = session.getResource(queueKey); queue.push(session, coords); } else { log.error("Duplicate location header: previously got {}, now {}. Ignoring the second match.", coords.path, value); } } } @Override public void afterHeaders(HttpRequest request) { Session.Var var = inputVar.getVar(request.session); if (var.isSet() && !(var.objectValue(request.session) instanceof Coords)) { log.error("Location header is missing in response from {} {}{}!", request.method, request.authority, request.path); request.markInvalid(); } } @Override public void reserve(Session session) { if (!outputVar.isSet(session)) { outputVar.setObject(session, ObjectVar.newArray(session, concurrency)); } session.declareResource(queueKey, () -> new Queue(outputVar, concurrency, concurrency, sequence, null)); } public static class Builder implements HeaderHandler.Builder { private Session.ResourceKey<Queue> queueKey; private Object inputVar, outputVar; private int concurrency; private String sequence; private Supplier<SerializableFunction<Session, SequenceInstance>> originalSequenceSupplier; public Builder() { } public Builder concurrency(int concurrency) { this.concurrency = concurrency; return this; } public Builder inputVar(Object inputVar) { this.inputVar = inputVar; return this; } public Builder outputVar(Object outputVar) { this.outputVar = outputVar; return this; } public Builder queueKey(Session.ResourceKey<Queue> queueKey) { this.queueKey = queueKey; return this; } public Builder sequence(String sequence) { this.sequence = sequence; return this; } public Builder originalSequenceSupplier(Supplier<SerializableFunction<Session, SequenceInstance>> supplier) { this.originalSequenceSupplier = supplier; return this; } @Override public LocationRecorder build() { if (Objects.equals(inputVar, outputVar)) { throw new BenchmarkDefinitionException( "Input (" + inputVar + ") and output (" + outputVar + ") variables must differ"); } assert inputVar != null; assert outputVar != null; assert sequence != null; return new LocationRecorder(concurrency, queueKey, SessionFactory.readAccess(inputVar), SessionFactory.objectAccess(outputVar), this.sequence, originalSequenceSupplier.get()); } } } public static class GetMethod implements SerializableFunction<Session, HttpMethod> { private final ReadAccess coordVar; public GetMethod(ReadAccess coordVar) { this.coordVar = coordVar; } @Override public HttpMethod apply(Session session) { Coords coords = (Coords) coordVar.getObject(session); return coords.method; } } private static SequenceInstance pushCurrentSequence(Session session, ReadAccess coordsVar) { Coords coords = (Coords) coordsVar.getObject(session); SequenceInstance currentSequence = session.currentSequence(); session.currentSequence(coords.originalSequence); Request request = session.currentRequest(); if (request != null) { request.unsafeEnterSequence(coords.originalSequence); } return currentSequence; } private static void popCurrentSequence(Session session, SequenceInstance currentSequence) { session.currentSequence(currentSequence); Request request = session.currentRequest(); if (request != null) { request.unsafeEnterSequence(currentSequence); } } public static class WrappingStatusHandler extends BaseDelegatingStatusHandler { private final ReadAccess coordsVar; public WrappingStatusHandler(io.hyperfoil.http.api.StatusHandler[] handlers, ReadAccess coordsVar) { super(handlers); this.coordsVar = coordsVar; } @Override public void handleStatus(HttpRequest request, int status) { SequenceInstance currentSequence = pushCurrentSequence(request.session, coordsVar); try { super.handleStatus(request, status); } finally { popCurrentSequence(request.session, currentSequence); } } public static class Builder extends BaseDelegatingStatusHandler.Builder<Builder> { private Object coordsVar; public Builder coordsVar(Object coordsVar) { this.coordsVar = coordsVar; return this; } @Override public WrappingStatusHandler build() { return new WrappingStatusHandler(buildHandlers(), SessionFactory.sequenceScopedReadAccess(coordsVar)); } } } public static class WrappingHeaderHandler extends BaseDelegatingHeaderHandler { private final ReadAccess coordsVar; public WrappingHeaderHandler(HeaderHandler[] handlers, ReadAccess coordsVar) { super(handlers); this.coordsVar = coordsVar; } @Override public void beforeHeaders(HttpRequest request) { SequenceInstance currentSequence = pushCurrentSequence(request.session, coordsVar); try { super.beforeHeaders(request); } finally { popCurrentSequence(request.session, currentSequence); } } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { SequenceInstance currentSequence = pushCurrentSequence(request.session, coordsVar); try { super.handleHeader(request, header, value); } finally { popCurrentSequence(request.session, currentSequence); } } @Override public void afterHeaders(HttpRequest request) { SequenceInstance currentSequence = pushCurrentSequence(request.session, coordsVar); try { super.afterHeaders(request); } finally { popCurrentSequence(request.session, currentSequence); } } public static class Builder extends BaseDelegatingHeaderHandler.Builder<Builder> { private Object coordVar; public Builder coordVar(Object coordVar) { this.coordVar = coordVar; return this; } @Override public WrappingHeaderHandler build() { return new WrappingHeaderHandler(buildHandlers(), SessionFactory.sequenceScopedReadAccess(coordVar)); } } } public static class WrappingProcessor extends MultiProcessor { private final ReadAccess coordVar; public WrappingProcessor(Processor[] processors, ReadAccess coordVar) { super(processors); this.coordVar = coordVar; } @Override public void before(Session session) { SequenceInstance currentSequence = pushCurrentSequence(session, coordVar); try { super.before(session); } finally { popCurrentSequence(session, currentSequence); } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { SequenceInstance currentSequence = pushCurrentSequence(session, coordVar); try { super.process(session, data, offset, length, isLastPart); } finally { popCurrentSequence(session, currentSequence); } } @Override public void after(Session session) { SequenceInstance currentSequence = pushCurrentSequence(session, coordVar); try { super.after(session); } finally { popCurrentSequence(session, currentSequence); } } public static class Builder extends MultiProcessor.Builder<Void, Builder> { private Object coordVar; public Builder() { super(null); } public Builder coordVar(Object coordVar) { this.coordVar = coordVar; return this; } @Override public WrappingProcessor build(boolean fragmented) { return new WrappingProcessor(buildProcessors(fragmented), SessionFactory.sequenceScopedReadAccess(coordVar)); } } } public static class WrappingAction extends BaseDelegatingAction { private final ReadAccess coordVar; public WrappingAction(Action[] actions, ReadAccess coordVar) { super(actions); this.coordVar = coordVar; } @Override public void run(Session session) { SequenceInstance currentSequence = pushCurrentSequence(session, coordVar); try { super.run(session); } finally { popCurrentSequence(session, currentSequence); } } public static class Builder extends BaseDelegatingAction.Builder<Builder> { private Object coordVar; public Builder coordVar(Object coordVar) { this.coordVar = coordVar; return this; } @Override public WrappingAction build() { return new WrappingAction(buildActions(), SessionFactory.sequenceScopedReadAccess(coordVar)); } } } public static class GetOriginalSequence implements SerializableFunction<Session, SequenceInstance> { private final ReadAccess coordVar; public GetOriginalSequence(ReadAccess coordVar) { this.coordVar = coordVar; } @Override public SequenceInstance apply(Session session) { return ((Redirect.Coords) coordVar.getObject(session)).originalSequence; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/ActionStatusHandler.java
http/src/main/java/io/hyperfoil/http/handlers/ActionStatusHandler.java
package io.hyperfoil.http.handlers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.PartialBuilder; import io.hyperfoil.api.session.Action; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; // Note: maybe it would be better to just use multiplex and let actions convert to status handlers? public class ActionStatusHandler extends BaseRangeStatusHandler { private final Action[][] actions; private final Action[] otherActions; public ActionStatusHandler(int[] statusRanges, Action[][] actions, Action[] otherActions) { super(statusRanges); assert statusRanges.length == 2 * actions.length; this.actions = actions; this.otherActions = otherActions; } @Override protected void onStatusRange(HttpRequest request, int status, int index) { for (Action a : actions[index]) { a.run(request.session); } } @Override protected void onOtherStatus(HttpRequest request, int status) { if (otherActions != null) { for (Action a : otherActions) { a.run(request.session); } } } /** * Perform certain actions when the status falls into a range. */ @MetaInfServices(StatusHandler.Builder.class) @Name("action") public static class Builder implements StatusHandler.Builder, PartialBuilder { private Map<String, List<Action.Builder>> actions = new HashMap<>(); /** * Perform a sequence of actions if the range matches. Use range as the key and action in the mapping. * Possible values of the status should be separated by commas (,). Ranges can be set using low-high (inclusive) (e.g. * 200-299), or replacing lower digits with 'x' (e.g. 2xx). * * @param range Status range. * @return Builder */ @Override public ServiceLoadedBuilderProvider<Action.Builder> withKey(String range) { List<Action.Builder> actions = new ArrayList<>(); add(range, actions); return new ServiceLoadedBuilderProvider<>(Action.Builder.class, actions::add); } public Builder add(String range, List<Action.Builder> actions) { if (this.actions.putIfAbsent(range, actions) != null) { throw new BenchmarkDefinitionException("Range '" + range + "' is already set."); } return this; } @Override public ActionStatusHandler build() { List<Integer> ranges = new ArrayList<>(); List<Action[]> actions = new ArrayList<>(); Action[] otherActions = checkAndSortRanges(this.actions, ranges, actions, list -> list.stream().map(Action.Builder::build).toArray(Action[]::new)); return new ActionStatusHandler(ranges.stream().mapToInt(Integer::intValue).toArray(), actions.toArray(new Action[0][]), otherActions); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/ConditionalHeaderHandler.java
http/src/main/java/io/hyperfoil/http/handlers/ConditionalHeaderHandler.java
package io.hyperfoil.http.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.config.Name; import io.hyperfoil.core.builders.Condition; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpRequest; public class ConditionalHeaderHandler extends BaseDelegatingHeaderHandler { private final Condition condition; public ConditionalHeaderHandler(Condition condition, HeaderHandler[] handlers) { super(handlers); this.condition = condition; } @Override public void beforeHeaders(HttpRequest request) { if (condition.test(request.session)) { super.beforeHeaders(request); } } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { if (condition.test(request.session)) { super.handleHeader(request, header, value); } } @Override public void afterHeaders(HttpRequest request) { if (condition.test(request.session)) { super.afterHeaders(request); } } /** * Passes the headers to nested handler if the condition holds. * Note that the condition may be evaluated multiple times and therefore * any nested handlers should not change the results of the condition. */ @MetaInfServices(HeaderHandler.Builder.class) @Name("conditional") public static class Builder extends BaseDelegatingHeaderHandler.Builder<Builder> { private Condition.TypesBuilder<Builder> condition = new Condition.TypesBuilder<>(this); @Embed public Condition.TypesBuilder<Builder> condition() { return condition; } @Override public ConditionalHeaderHandler build() { if (handlers.isEmpty()) { throw new BenchmarkDefinitionException("Conditional handler does not delegate to any handler."); } Condition condition = this.condition.buildCondition(); if (condition == null) { throw new BenchmarkDefinitionException("Conditional handler must specify a condition."); } return new ConditionalHeaderHandler(condition, buildHandlers()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/StatusToCounterHandler.java
http/src/main/java/io/hyperfoil/http/handlers/StatusToCounterHandler.java
package io.hyperfoil.http.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; public class StatusToCounterHandler implements StatusHandler { private final Integer expectStatus; private final IntAccess var; private final int init; private final Integer add; private final Integer set; public StatusToCounterHandler(int expectStatus, IntAccess var, int init, Integer add, Integer set) { this.expectStatus = expectStatus; this.var = var; this.init = init; this.add = add; this.set = set; } @Override public void handleStatus(HttpRequest request, int status) { if (expectStatus != null && expectStatus != status) { return; } if (add != null) { if (var.isSet(request.session)) { var.addToInt(request.session, add); } else { var.setInt(request.session, init + add); } } else if (set != null) { var.setInt(request.session, set); } else { throw new IllegalStateException(); } } /** * Counts how many times given status is received. */ @MetaInfServices(StatusHandler.Builder.class) @Name("counter") public static class Builder implements StatusHandler.Builder { private Integer expectStatus; private String var; private int init; private Integer add; private Integer set; /** * Expected status (others are ignored). All status codes match by default. * * @param expectStatus Status code. * @return Self. */ public Builder expectStatus(int expectStatus) { this.expectStatus = expectStatus; return this; } /** * Variable name. * * @param var Variable name. * @return Self. */ public Builder var(String var) { this.var = var; return this; } /** * Initial value for the session variable. * * @param init Initial value. * @return Self. */ public Builder init(int init) { this.init = init; return this; } /** * Number to be added to the session variable. * * @param add Value. * @return Self. */ public Builder add(int add) { this.add = add; return this; } /** * Do not accumulate (add), just set the variable to this value. * * @param set Value. * @return Self. */ public Builder set(int set) { this.set = set; return this; } @Override public StatusHandler build() { if (add != null && set != null) { throw new BenchmarkDefinitionException("Use either 'add' or 'set' (not both)"); } else if (add == null && set == null) { throw new BenchmarkDefinitionException("Use either 'add' or 'set'"); } return new StatusToCounterHandler(expectStatus, SessionFactory.intAccess(var), init, add, set); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/CountHeadersHandler.java
http/src/main/java/io/hyperfoil/http/handlers/CountHeadersHandler.java
package io.hyperfoil.http.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.statistics.Counters; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpRequest; public class CountHeadersHandler implements HeaderHandler { @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { request.statistics().update("countHeaders", request.startTimestampMillis(), Counters::new, Counters::increment, header); } /** * Stores number of occurences of each header in custom statistics (these can be displayed in CLI using the * <code>stats -c</code> command). */ @MetaInfServices(HeaderHandler.Builder.class) @Name("countHeaders") public static class Builder implements HeaderHandler.Builder { @Override public CountHeadersHandler build() { return new CountHeadersHandler(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/StoreStatusHandler.java
http/src/main/java/io/hyperfoil/http/handlers/StoreStatusHandler.java
package io.hyperfoil.http.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; public class StoreStatusHandler implements StatusHandler { private final IntAccess toVar; public StoreStatusHandler(IntAccess toVar) { this.toVar = toVar; } @Override public void handleStatus(HttpRequest request, int status) { toVar.setInt(request.session, status); } /** * Stores the status into session variable. */ @MetaInfServices(StatusHandler.Builder.class) @Name("store") public static class Builder implements StatusHandler.Builder, InitFromParam<Builder> { private Object toVar; /** * @param param Variable name. * @return Self. */ @Override public Builder init(String param) { return toVar(param); } /** * Variable name. * * @param toVar Variable name. * @return Self. */ public Builder toVar(Object toVar) { this.toVar = toVar; return this; } @Override public StoreStatusHandler build() { return new StoreStatusHandler(SessionFactory.intAccess(toVar)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/StatusToStatsHandler.java
http/src/main/java/io/hyperfoil/http/handlers/StatusToStatsHandler.java
package io.hyperfoil.http.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.statistics.Counters; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; public class StatusToStatsHandler implements StatusHandler { private static final int FIRST_STATUS = 100; private static final int LAST_STATUS = 599; private static final String[] statusStrings; static { statusStrings = new String[LAST_STATUS - FIRST_STATUS + 1]; for (int i = 0; i <= LAST_STATUS - FIRST_STATUS; ++i) { statusStrings[i] = "status_" + (i + FIRST_STATUS); } } @Override public void handleStatus(HttpRequest request, int status) { String statusString; if (status >= FIRST_STATUS && status <= LAST_STATUS) { statusString = statusStrings[status - FIRST_STATUS]; } else { statusString = "status_" + status; } request.statistics().update("exact_status", request.startTimestampMillis(), Counters::new, Counters::increment, statusString); } /** * Records number of occurrences of each status counts into custom statistics * (these can be displayed in CLI using <code>stats -c</code>). */ @MetaInfServices @Name("stats") public static class Builder implements StatusHandler.Builder { @Override public StatusHandler build() { return new StatusToStatsHandler(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/BaseDelegatingHeaderHandler.java
http/src/main/java/io/hyperfoil/http/handlers/BaseDelegatingHeaderHandler.java
package io.hyperfoil.http.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpRequest; public abstract class BaseDelegatingHeaderHandler implements HeaderHandler { protected final HeaderHandler[] handlers; public BaseDelegatingHeaderHandler(HeaderHandler[] handlers) { this.handlers = handlers; } @Override public void beforeHeaders(HttpRequest request) { for (HeaderHandler h : handlers) { h.beforeHeaders(request); } } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { for (HeaderHandler h : handlers) { h.handleHeader(request, header, value); } } @Override public void afterHeaders(HttpRequest request) { for (HeaderHandler h : handlers) { h.afterHeaders(request); } } public abstract static class Builder<S extends Builder<S>> implements HeaderHandler.Builder { protected final List<HeaderHandler.Builder> handlers = new ArrayList<>(); @SuppressWarnings("unchecked") protected S self() { return (S) this; } public S handler(HeaderHandler.Builder handler) { this.handlers.add(handler); return self(); } public S handlers(Collection<? extends HeaderHandler.Builder> handlers) { this.handlers.addAll(handlers); return self(); } /** * One or more header handlers that should be invoked. * * @return Builder. */ public ServiceLoadedBuilderProvider<HeaderHandler.Builder> handler() { return new ServiceLoadedBuilderProvider<>(HeaderHandler.Builder.class, this::handler); } protected HeaderHandler[] buildHandlers() { return handlers.stream().map(HeaderHandler.Builder::build).toArray(HeaderHandler[]::new); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/handlers/BaseRangeStatusHandler.java
http/src/main/java/io/hyperfoil/http/handlers/BaseRangeStatusHandler.java
package io.hyperfoil.http.handlers; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.StatusHandler; import io.hyperfoil.impl.Util; public abstract class BaseRangeStatusHandler implements StatusHandler { protected final int[] statusRanges; public BaseRangeStatusHandler(int[] statusRanges) { this.statusRanges = statusRanges; } @Override public void handleStatus(HttpRequest request, int status) { for (int i = 0; 2 * i < statusRanges.length; ++i) { if (status >= statusRanges[2 * i] && status <= statusRanges[2 * i + 1]) { onStatusRange(request, status, i); return; } } onOtherStatus(request, status); } protected abstract void onStatusRange(HttpRequest request, int status, int index); protected abstract void onOtherStatus(HttpRequest request, int status); protected static <S, T> T checkAndSortRanges(Map<String, S> map, List<Integer> ranges, List<T> values, Function<S, T> func) { T other = null; TreeMap<Integer, T> byLow = new TreeMap<>(); Map<Integer, Integer> toHigh = new HashMap<>(); for (Map.Entry<String, S> entry : map.entrySet()) { if (entry.getKey().equals("other")) { other = func.apply(entry.getValue()); continue; } for (String part : entry.getKey().split(",")) { part = part.trim(); int low, high; try { if (part.contains("-")) { int di = part.indexOf('-'); low = Integer.parseInt(part.substring(0, di).trim()); high = Integer.parseInt(part.substring(di + 1).trim()); } else { int xn = 0; for (int i = part.length() - 1; i >= 0; --i) { if (part.charAt(i) == 'x') { ++xn; } else break; } int value = Integer.parseInt(part.substring(0, part.length() - xn)); int mul = Util.pow(10, xn); low = value * mul; high = (value + 1) * mul - 1; } if (low > high || low < 100 || high > 599) { throw new BenchmarkDefinitionException( "Invalid status range " + low + "-" + high + " in '" + entry.getKey() + "'"); } T partValue = func.apply(entry.getValue()); Integer floor = byLow.floorKey(low); if (floor == null) { Integer ceiling = byLow.ceilingKey(low); if (ceiling != null && ceiling <= high) { throw new BenchmarkDefinitionException( "Overlapping ranges: " + low + "-" + high + " and " + ceiling + "-" + toHigh.get(ceiling)); } byLow.put(low, partValue); toHigh.put(low, high); } else if (floor == low) { throw new BenchmarkDefinitionException( "Overlapping ranges: " + low + "-" + high + " and " + floor + "-" + toHigh.get(floor)); } else { Integer floorHigh = toHigh.get(floor); if (floorHigh >= low) { throw new BenchmarkDefinitionException( "Overlapping ranges: " + low + "-" + high + " and " + floor + "-" + floorHigh); } Integer ceiling = byLow.ceilingKey(low); if (ceiling != null && ceiling <= high) { throw new BenchmarkDefinitionException( "Overlapping ranges: " + low + "-" + high + " and " + ceiling + "-" + toHigh.get(ceiling)); } byLow.put(low, partValue); toHigh.put(low, high); } } catch (NumberFormatException e) { throw new BenchmarkDefinitionException("Cannot parse status range '" + part + "' in '" + entry.getKey() + "'"); } } } Integer lastLow = null, lastHigh = null; T lastValue = null; for (Map.Entry<Integer, T> entry : byLow.entrySet()) { Integer high = toHigh.get(entry.getKey()); if (lastValue == entry.getValue() && lastHigh != null && lastHigh == entry.getKey() - 1) { lastHigh = high; continue; } if (lastValue != null) { ranges.add(lastLow); ranges.add(lastHigh); values.add(lastValue); } lastLow = entry.getKey(); lastHigh = high; lastValue = entry.getValue(); } if (lastValue != null) { ranges.add(lastLow); ranges.add(lastHigh); values.add(lastValue); } return other; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/HttpPluginBuilder.java
http/src/main/java/io/hyperfoil/http/config/HttpPluginBuilder.java
package io.hyperfoil.http.config; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.PluginBuilder; import io.hyperfoil.api.config.PluginConfig; public class HttpPluginBuilder extends PluginBuilder<HttpErgonomics> { private HttpBuilder defaultHttp; private final List<HttpBuilder> httpList = new ArrayList<>(); private final HttpErgonomics ergonomics = new HttpErgonomics(this); public HttpPluginBuilder(BenchmarkBuilder parent) { super(parent); } public static Collection<HttpBuilder> httpForTesting(BenchmarkBuilder benchmarkBuilder) { HttpPluginBuilder builder = benchmarkBuilder.plugin(HttpPluginBuilder.class); if (builder.defaultHttp == null) { return Collections.unmodifiableList(builder.httpList); } else if (builder.httpList.isEmpty()) { return Collections.singletonList(builder.defaultHttp); } else { ArrayList<HttpBuilder> list = new ArrayList<>(builder.httpList); list.add(builder.defaultHttp); return list; } } public HttpBuilder http() { if (defaultHttp == null) { defaultHttp = new HttpBuilder(this); } return defaultHttp; } public HttpBuilder http(String host) { HttpBuilder builder = new HttpBuilder(this).host(host); httpList.add(builder); return builder; } @Override public HttpErgonomics ergonomics() { return ergonomics; } @Override public void prepareBuild() { if (defaultHttp == null) { if (httpList.isEmpty()) { // may be removed in the future when we define more than HTTP connections throw new BenchmarkDefinitionException("No default HTTP target set!"); } else if (httpList.size() == 1) { defaultHttp = httpList.iterator().next(); } } else { if (httpList.stream().anyMatch(http -> http.authority().equals(defaultHttp.authority()))) { throw new BenchmarkDefinitionException("Ambiguous HTTP definition for " + defaultHttp.authority() + ": defined both as default and non-default"); } httpList.add(defaultHttp); } httpList.forEach(HttpBuilder::prepareBuild); } @Override public void addTags(Map<String, Object> tags) { if (defaultHttp != null) { Http defaultHttp = this.defaultHttp.build(true); tags.put("url", defaultHttp.protocol().scheme + "://" + defaultHttp.host() + ":" + defaultHttp.port()); tags.put("protocol", defaultHttp.protocol().scheme); } } @Override public PluginConfig build() { Map<String, Http> byName = new HashMap<>(); Map<String, Http> byAuthority = new HashMap<>(); for (HttpBuilder builder : httpList) { Http http = builder.build(builder == defaultHttp); Http previous = builder.name() == null ? null : byName.put(builder.name(), http); if (previous != null) { throw new BenchmarkDefinitionException("Duplicate HTTP endpoint name " + builder.name() + ": used both for " + http.originalDestination() + " and " + previous.originalDestination()); } previous = byAuthority.put(builder.authority(), http); if (previous != null && builder.name() == null) { throw new BenchmarkDefinitionException("Duplicate HTTP endpoint for authority " + builder.authority()); } } return new HttpPluginConfig(byAuthority); } public boolean validateAuthority(String authority) { if (authority == null) return defaultHttp != null; return isValidAuthority(authority); } private boolean isValidAuthority(String authority) { long matches = httpList.stream() .filter(distinctByKey(http -> http.protocol() + http.authority())) // skip potential duplicate authorities .filter(http -> compareAuthorities(http, authority)) .count(); return matches == 1; // only one authority should match } private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } private static boolean compareAuthorities(HttpBuilder http, String authority) { final StringBuilder auth1 = new StringBuilder(http.authority()), auth2 = new StringBuilder(authority); if (!http.authority().contains(":")) { auth1.append(":").append(http.portOrDefault()); } if (!authority.contains(":")) { auth2.append(":").append(http.portOrDefault()); } return auth1.toString().equals(auth2.toString()); } public boolean validateEndpoint(String endpoint) { return httpList.stream().anyMatch(http -> endpoint.equals(http.name())); } public HttpBuilder getHttp(String authority) { if (authority == null && defaultHttp != null) { return defaultHttp; } else { return httpList.stream().filter(http -> http.authority().equals(authority)).findFirst().orElse(null); } } public HttpBuilder getHttpByName(String endpoint) { if (endpoint == null) { throw new IllegalArgumentException(); } return httpList.stream().filter(http -> http.name().equals(endpoint)).findFirst().orElse(null); } public HttpBuilder decoupledHttp() { return new HttpBuilder(this); } public void addHttp(HttpBuilder builder) { if (builder.authority() == null) { throw new BenchmarkDefinitionException("Missing hostname!"); } httpList.add(builder); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/ConnectionStrategy.java
http/src/main/java/io/hyperfoil/http/config/ConnectionStrategy.java
package io.hyperfoil.http.config; public enum ConnectionStrategy { /** * Connections are created in a pool and then borrowed by the session. * When the request is complete the connection is returned to the shared pool. */ SHARED_POOL, /** * Connections are created in a shared pool. When the request is completed * it is not returned to the shared pool but to a session-local pool. * Subsequent requests by this session first try to acquire the connection from * this local pool. * When the session completes all connections from the session-local pool are returned * to the shared pool. */ SESSION_POOLS, /** * Connections are created before request or borrowed from a session-local pool. * When the request is completed the connection is returned to this pool. * When the session completes all connections from the session-local pool are closed. */ OPEN_ON_REQUEST, /** * Always create the connection before the request and close it when it is complete. * No pooling of connections. */ ALWAYS_NEW }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/HttpBuilder.java
http/src/main/java/io/hyperfoil/http/config/HttpBuilder.java
/* * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.hyperfoil.http.config; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.http.api.HttpVersion; import io.hyperfoil.impl.Util; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ public class HttpBuilder implements BuilderBase<HttpBuilder> { private final HttpPluginBuilder parent; private String name; private Http http; private String originalDestination; private Protocol protocol; private String host; private int port = -1; private List<String> addresses = new ArrayList<>(); private boolean allowHttp1x = true; private boolean allowHttp2 = true; private ConnectionPoolConfig.Builder sharedConnections = new ConnectionPoolConfig.Builder(this); private int maxHttp2Streams = 100; private int pipeliningLimit = 1; private boolean directHttp2 = false; private long requestTimeout = 30000; private long sslHandshakeTimeout = 10000; private boolean rawBytesHandlers = true; private KeyManagerBuilder keyManager = new KeyManagerBuilder(this); private TrustManagerBuilder trustManager = new TrustManagerBuilder(this); private ConnectionStrategy connectionStrategy = ConnectionStrategy.SHARED_POOL; private boolean useHttpCache = true; public static HttpBuilder forTesting() { return new HttpBuilder(null); } public HttpBuilder(HttpPluginBuilder parent) { this.parent = parent; } public HttpBuilder name(String name) { this.name = name; return this; } String name() { return name; } String authority() { if (host() == null) { return null; } else if (port == -1) { return host(); } else { return host() + ":" + portOrDefault(); } } public HttpBuilder protocol(Protocol protocol) { if (this.protocol != null) { throw new BenchmarkDefinitionException("Duplicate 'protocol'"); } this.protocol = protocol; return this; } public Protocol protocol() { return protocol; } public String host() { return host; } public int portOrDefault() { if (port != -1) { return port; } else if (protocol != null) { return protocol.portOrDefault(port); } else { throw new BenchmarkDefinitionException("No port nor protocol has been defined"); } } public HttpBuilder host(String destination) { if (this.host != null) { throw new BenchmarkDefinitionException("Duplicate 'host'. Are you missing '-'s?"); } URL result; String spec; int schemeEnd = destination.indexOf("://"); if (schemeEnd < 0) { spec = "http://" + destination; originalDestination = destination; } else { spec = destination; originalDestination = destination.substring(schemeEnd + 3); } try { result = new URL(spec); } catch (MalformedURLException e) { throw new BenchmarkDefinitionException("Failed to parse host:port", e); } URL url = result; this.protocol = protocol == null ? Protocol.fromScheme(url.getProtocol()) : protocol; this.host = url.getHost(); this.port = url.getPort(); if (url.getFile() != null && !url.getFile().isEmpty()) { throw new BenchmarkDefinitionException("Host must not contain any path: " + destination); } return this; } public HttpBuilder port(int port) { if (this.port > 0) { throw new BenchmarkDefinitionException("Duplicate 'port'"); } this.port = port; return this; } public HttpBuilder allowHttp1x(boolean allowHttp1x) { this.allowHttp1x = allowHttp1x; return this; } public HttpBuilder allowHttp2(boolean allowHttp2) { this.allowHttp2 = allowHttp2; return this; } public HttpPluginBuilder endHttp() { return parent; } public HttpBuilder sharedConnections(int sharedConnections) { this.sharedConnections.core(sharedConnections).max(sharedConnections).buffer(0).keepAliveTime(0); return this; } public ConnectionPoolConfig.Builder sharedConnections() { return this.sharedConnections; } public HttpBuilder maxHttp2Streams(int maxStreams) { this.maxHttp2Streams = maxStreams; return this; } public HttpBuilder pipeliningLimit(int limit) { this.pipeliningLimit = limit; return this; } public HttpBuilder directHttp2(boolean directHttp2) { this.directHttp2 = directHttp2; return this; } public HttpBuilder requestTimeout(long requestTimeout) { this.requestTimeout = requestTimeout; return this; } public HttpBuilder requestTimeout(String requestTimeout) { if ("none".equals(requestTimeout)) { this.requestTimeout = -1; } else { this.requestTimeout = Util.parseToMillis(requestTimeout); } return this; } public long requestTimeout() { return requestTimeout; } public HttpBuilder sslHandshakeTimeout(long sslHandshakeTimeout) { this.sslHandshakeTimeout = sslHandshakeTimeout; return this; } public HttpBuilder sslHandshakeTimeout(String sslHandshakeTimeout) { if ("none".equals(sslHandshakeTimeout)) { this.sslHandshakeTimeout = -1; } else { this.sslHandshakeTimeout = Util.parseToMillis(sslHandshakeTimeout); } return this; } public long sslHandshakeTimeout() { return sslHandshakeTimeout; } public HttpBuilder addAddress(String address) { addresses.add(address); return this; } public HttpBuilder rawBytesHandlers(boolean rawBytesHandlers) { this.rawBytesHandlers = rawBytesHandlers; return this; } public KeyManagerBuilder keyManager() { return keyManager; } public TrustManagerBuilder trustManager() { return trustManager; } public HttpBuilder connectionStrategy(ConnectionStrategy connectionStrategy) { this.connectionStrategy = connectionStrategy; return this; } public ConnectionStrategy connectionStrategy() { return connectionStrategy; } public HttpBuilder useHttpCache(boolean useHttpCache) { this.useHttpCache = useHttpCache; return this; } public boolean useHttpCache() { return useHttpCache; } public void prepareBuild() { } public Http build(boolean isDefault) { if (http != null) { if (isDefault != http.isDefault()) { throw new IllegalArgumentException("Already built as isDefault=" + http.isDefault()); } return http; } List<HttpVersion> httpVersions = new ArrayList<>(); // The order is important here because it will be provided to the ALPN if (allowHttp2) { httpVersions.add(HttpVersion.HTTP_2_0); } if (allowHttp1x) { httpVersions.add(HttpVersion.HTTP_1_1); httpVersions.add(HttpVersion.HTTP_1_0); } if (directHttp2) { throw new UnsupportedOperationException("Direct HTTP/2 not implemented"); } if (originalDestination == null) { originalDestination = host; if (port >= 0) { originalDestination += ":" + port; } } Protocol protocol = this.protocol != null ? this.protocol : Protocol.fromPort(port); return http = new Http(name, isDefault, originalDestination, protocol, host, protocol.portOrDefault(port), addresses.toArray(new String[0]), httpVersions.toArray(new HttpVersion[0]), maxHttp2Streams, pipeliningLimit, sharedConnections.build(), directHttp2, requestTimeout, sslHandshakeTimeout, rawBytesHandlers, keyManager.build(), trustManager.build(), connectionStrategy, useHttpCache); } public static class KeyManagerBuilder implements BuilderBase<KeyManagerBuilder> { private final HttpBuilder parent; private String storeType = "JKS"; private byte[] storeBytes; private String password; private String alias; private byte[] certBytes; private byte[] keyBytes; public KeyManagerBuilder(HttpBuilder parent) { this.parent = parent; } public KeyManagerBuilder storeType(String type) { this.storeType = type; return this; } public KeyManagerBuilder storeFile(String filename) { try { this.storeBytes = readBytes(filename); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot read key store file " + filename, e); } return this; } public KeyManagerBuilder storeBytes(byte[] storeBytes) { this.storeBytes = storeBytes; return this; } public KeyManagerBuilder password(String password) { this.password = password; return this; } public KeyManagerBuilder alias(String alias) { this.alias = alias; return this; } public KeyManagerBuilder certFile(String certFile) { try { this.certBytes = readBytes(certFile); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot read certificate file " + certFile, e); } return this; } public KeyManagerBuilder certBytes(byte[] certBytes) { this.certBytes = certBytes; return this; } public KeyManagerBuilder keyFile(String keyFile) { try { this.keyBytes = readBytes(keyFile); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot read private key file " + keyFile, e); } return this; } public KeyManagerBuilder keyBytes(byte[] keyBytes) { this.keyBytes = keyBytes; return this; } public HttpBuilder end() { return parent; } public Http.KeyManager build() { return new Http.KeyManager(storeType, storeBytes, password, alias, certBytes, keyBytes); } } public static class TrustManagerBuilder implements BuilderBase<TrustManagerBuilder> { private final HttpBuilder parent; private String storeType = "JKS"; private byte[] storeBytes; private String password; private byte[] certBytes; public TrustManagerBuilder(HttpBuilder parent) { this.parent = parent; } public TrustManagerBuilder storeType(String type) { this.storeType = type; return this; } public TrustManagerBuilder storeFile(String filename) { try { this.storeBytes = readBytes(filename); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot read keystore file " + filename, e); } return this; } public TrustManagerBuilder storeBytes(byte[] storeBytes) { this.storeBytes = storeBytes; return this; } public TrustManagerBuilder password(String password) { this.password = password; return this; } public TrustManagerBuilder certFile(String certFile) { try { this.certBytes = readBytes(certFile); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot read certificate file " + certFile, e); } return this; } public TrustManagerBuilder certBytes(byte[] certBytes) { this.certBytes = certBytes; return this; } public HttpBuilder end() { return parent; } public Http.TrustManager build() { return new Http.TrustManager(storeType, storeBytes, password, certBytes); } } private static byte[] readBytes(String filename) throws IOException { try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)) { if (stream != null) { return Util.toByteArray(stream); } } return Files.readAllBytes(Paths.get(filename)); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/Protocol.java
http/src/main/java/io/hyperfoil/http/config/Protocol.java
package io.hyperfoil.http.config; import java.util.stream.Stream; public enum Protocol { HTTP("http", 80, false), HTTPS("https", 443, true); public final String scheme; public final int defaultPort; public final boolean secure; Protocol(String scheme, int defaultPort, boolean secure) { this.scheme = scheme; this.defaultPort = defaultPort; this.secure = secure; } public static Protocol fromScheme(String scheme) { return Stream.of(values()).filter(p -> p.scheme.equals(scheme)).findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown scheme '" + scheme + "'")); } public static Protocol fromPort(int port) { if (port == HTTPS.defaultPort) { return HTTPS; } else { return HTTP; } } public int portOrDefault(int port) { return port < 0 ? defaultPort : port; } public boolean secure() { return secure; } @Override public String toString() { return secure ? "https://" : "http://"; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/HttpErgonomics.java
http/src/main/java/io/hyperfoil/http/config/HttpErgonomics.java
package io.hyperfoil.http.config; import io.hyperfoil.http.api.FollowRedirect; // Contrary to the builder - immutable instance model we're using for most configuration objects // we'll keep only single object for ergonomics as this is used only when the benchmark is being built. public class HttpErgonomics { private final HttpPluginBuilder parent; private boolean repeatCookies = true; private boolean userAgentFromSession = true; private boolean autoRangeCheck = true; private boolean stopOnInvalid = true; private FollowRedirect followRedirect = FollowRedirect.NEVER; public HttpErgonomics(HttpPluginBuilder parent) { this.parent = parent; } /** * Set global cookie-repeating behaviour for all steps. * * @param repeatCookies Auto repeat? * @return Self. */ public HttpErgonomics repeatCookies(boolean repeatCookies) { this.repeatCookies = repeatCookies; return this; } public boolean repeatCookies() { return repeatCookies; } public HttpErgonomics userAgentFromSession(boolean userAgentFromSession) { this.userAgentFromSession = userAgentFromSession; return this; } public boolean userAgentFromSession() { return userAgentFromSession; } public boolean autoRangeCheck() { return autoRangeCheck; } public HttpErgonomics autoRangeCheck(boolean autoRangeCheck) { this.autoRangeCheck = autoRangeCheck; return this; } public boolean stopOnInvalid() { return stopOnInvalid; } public HttpErgonomics stopOnInvalid(boolean stopOnInvalid) { this.stopOnInvalid = stopOnInvalid; return this; } public FollowRedirect followRedirect() { return followRedirect; } public HttpErgonomics followRedirect(FollowRedirect followRedirect) { this.followRedirect = followRedirect; return this; } public HttpPluginBuilder endErgonomics() { return parent; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/HttpPlugin.java
http/src/main/java/io/hyperfoil/http/config/HttpPlugin.java
package io.hyperfoil.http.config; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.PluginConfig; import io.hyperfoil.core.api.Plugin; import io.hyperfoil.core.parser.ErgonomicsParser; import io.hyperfoil.core.parser.PropertyParser; import io.hyperfoil.http.HttpRunData; import io.hyperfoil.http.api.FollowRedirect; import io.hyperfoil.http.parser.HttpParser; import io.netty.channel.EventLoop; @MetaInfServices(Plugin.class) public class HttpPlugin implements Plugin { @Override public Class<? extends PluginConfig> configClass() { return HttpPluginConfig.class; } @Override public String name() { return "http"; } @Override public HttpParser parser() { return new HttpParser(); } @Override public void enhanceErgonomics(ErgonomicsParser parser) { parser.register("repeatCookies", HttpPluginBuilder.class, new PropertyParser.Boolean<>(HttpErgonomics::repeatCookies)); parser.register("userAgentFromSession", HttpPluginBuilder.class, new PropertyParser.Boolean<>(HttpErgonomics::userAgentFromSession)); parser.register("autoRangeCheck", HttpPluginBuilder.class, new PropertyParser.Boolean<>(HttpErgonomics::autoRangeCheck)); parser.register("stopOnInvalid", HttpPluginBuilder.class, new PropertyParser.Boolean<>(HttpErgonomics::stopOnInvalid)); parser.register("followRedirect", HttpPluginBuilder.class, new PropertyParser.Enum<>(FollowRedirect.values(), HttpErgonomics::followRedirect)); } @Override public HttpRunData createRunData(Benchmark benchmark, EventLoop[] executors, int agentId) { return new HttpRunData(benchmark, executors, agentId); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/ConnectionPoolConfig.java
http/src/main/java/io/hyperfoil/http/config/ConnectionPoolConfig.java
package io.hyperfoil.http.config; import java.io.Serializable; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.BuilderBase; public class ConnectionPoolConfig implements Serializable { private final int core; private final int max; private final int buffer; private final long keepAliveTime; public ConnectionPoolConfig(int core, int max, int buffer, long keepAliveTime) { this.core = core; this.max = max; this.buffer = buffer; this.keepAliveTime = keepAliveTime; } public int core() { return core; } public int max() { return max; } public int buffer() { return buffer; } public long keepAliveTime() { return keepAliveTime; } public static class Builder implements BuilderBase<Builder> { private final HttpBuilder parent; private int core; private int max; private int buffer; private long keepAliveTime; public Builder(HttpBuilder parent) { this.parent = parent; } public Builder core(int core) { this.core = core; return this; } public Builder max(int max) { this.max = max; return this; } public Builder buffer(int buffer) { this.buffer = buffer; return this; } public Builder keepAliveTime(long keepAliveTime) { this.keepAliveTime = keepAliveTime; return this; } public ConnectionPoolConfig build() { if (core < 0) { throw new BenchmarkDefinitionException("Illegal value for 'core': " + core + " (must be >= 0)"); } else if (max < 0) { throw new BenchmarkDefinitionException("Illegal value for 'max': " + max + " (must be >= 0)"); } else if (buffer < 0) { throw new BenchmarkDefinitionException("Illegal value for 'buffer': " + buffer + " (must be >= 0)"); } if (core > max) { throw new BenchmarkDefinitionException("'core' > 'max': " + core + " > " + max); } else if (buffer > max) { throw new BenchmarkDefinitionException("'buffer' > 'max': " + buffer + " > " + max); } return new io.hyperfoil.http.config.ConnectionPoolConfig(core, max, buffer, keepAliveTime); } public HttpBuilder end() { return parent; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/Http.java
http/src/main/java/io/hyperfoil/http/config/Http.java
/* * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.hyperfoil.http.config; import java.io.Serializable; import io.hyperfoil.http.api.HttpVersion; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ public class Http implements Serializable { private final String name; private final boolean isDefault; private final String originalDestination; private final Protocol protocol; private final String host; private final int port; private final String[] addresses; private final HttpVersion[] versions; private final int maxHttp2Streams; private final int pipeliningLimit; private final ConnectionPoolConfig sharedConnections; private final boolean directHttp2; private final long requestTimeout; private final long sslHandshakeTimeout; private final boolean rawBytesHandlers; private final KeyManager keyManager; private final TrustManager trustManager; private final ConnectionStrategy connectionStrategy; private final boolean useHttpCache; public Http(String name, boolean isDefault, String originalDestination, Protocol protocol, String host, int port, String[] addresses, HttpVersion[] versions, int maxHttp2Streams, int pipeliningLimit, ConnectionPoolConfig sharedConnections, boolean directHttp2, long requestTimeout, long sslHandshakeTimeout, boolean rawBytesHandlers, KeyManager keyManager, TrustManager trustManager, ConnectionStrategy connectionStrategy, boolean useHttpCache) { this.name = name; this.isDefault = isDefault; this.originalDestination = originalDestination; this.protocol = protocol; this.host = host; this.port = port; this.addresses = addresses; this.versions = versions; this.maxHttp2Streams = maxHttp2Streams; this.pipeliningLimit = pipeliningLimit; this.sharedConnections = sharedConnections; this.directHttp2 = directHttp2; this.requestTimeout = requestTimeout; this.sslHandshakeTimeout = sslHandshakeTimeout; this.rawBytesHandlers = rawBytesHandlers; this.keyManager = keyManager; this.trustManager = trustManager; this.connectionStrategy = connectionStrategy; this.useHttpCache = useHttpCache; } public String name() { return name; } /** * The difference between this method and authority is that the port is optional; * this is exactly what the user typed into the <code>host:</code> property and will * be used for the Host/SNI header. */ public String originalDestination() { return originalDestination; } public Protocol protocol() { return protocol; } public String host() { return host; } public int port() { return port; } public HttpVersion[] versions() { return versions; } public int maxHttp2Streams() { return maxHttp2Streams; } public int pipeliningLimit() { return pipeliningLimit; } public ConnectionPoolConfig sharedConnections() { return sharedConnections; } public boolean directHttp2() { return directHttp2; } public boolean isDefault() { return isDefault; } public long requestTimeout() { return requestTimeout; } public long sslHandshakeTimeout() { return sslHandshakeTimeout; } public String[] addresses() { return addresses; } public boolean rawBytesHandlers() { return rawBytesHandlers; } public TrustManager trustManager() { return trustManager; } public KeyManager keyManager() { return keyManager; } public ConnectionStrategy connectionStrategy() { return connectionStrategy; } public boolean enableHttpCache() { return useHttpCache; } public static class KeyManager implements Serializable { private final String storeType; private final byte[] storeBytes; private final String password; private final String alias; private final byte[] certBytes; private final byte[] keyBytes; public KeyManager(String storeType, byte[] storeBytes, String password, String alias, byte[] certBytes, byte[] keyBytes) { this.storeType = storeType; this.storeBytes = storeBytes; this.password = password; this.alias = alias; this.certBytes = certBytes; this.keyBytes = keyBytes; } public String storeType() { return storeType; } public byte[] storeBytes() { return storeBytes; } public String password() { return password; } public String alias() { return alias; } public byte[] certBytes() { return certBytes; } public byte[] keyBytes() { return keyBytes; } } public static class TrustManager implements Serializable { private final String storeType; private final byte[] storeBytes; private final String password; private final byte[] certBytes; public TrustManager(String storeType, byte[] storeBytes, String password, byte[] certBytes) { this.storeType = storeType; this.storeBytes = storeBytes; this.password = password; this.certBytes = certBytes; } public String storeType() { return storeType; } public byte[] storeBytes() { return storeBytes; } public String password() { return password; } public byte[] certBytes() { return certBytes; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/config/HttpPluginConfig.java
http/src/main/java/io/hyperfoil/http/config/HttpPluginConfig.java
package io.hyperfoil.http.config; import java.util.Map; import io.hyperfoil.api.config.PluginConfig; import io.hyperfoil.api.config.Visitor; public class HttpPluginConfig implements PluginConfig { private final Map<String, Http> http; @Visitor.Ignore private final Http defaultHttp; public HttpPluginConfig(Map<String, Http> http) { this.http = http; this.defaultHttp = http.values().stream().filter(Http::isDefault).findFirst().orElse(null); } public Map<String, Http> http() { return http; } public Http defaultHttp() { return defaultHttp; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/statistics/HttpStats.java
http/src/main/java/io/hyperfoil/http/statistics/HttpStats.java
package io.hyperfoil.http.statistics; import org.kohsuke.MetaInfServices; import com.fasterxml.jackson.annotation.JsonTypeName; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.api.statistics.StatisticsSnapshot; import io.hyperfoil.api.statistics.StatisticsSummary; import io.hyperfoil.api.statistics.StatsExtension; @MetaInfServices(StatsExtension.class) @JsonTypeName("http") public class HttpStats implements StatsExtension { public static final String HTTP = "http"; private static final Statistics.LongUpdater<HttpStats> ADD_STATUS = (s, value) -> { switch ((int) value / 100) { case 2: s.status_2xx++; break; case 3: s.status_3xx++; break; case 4: s.status_4xx++; break; case 5: s.status_5xx++; break; default: s.status_other++; } }; private static final Statistics.LongUpdater<HttpStats> ADD_CACHE_HIT = (s, ignored) -> s.cacheHits++; private static final String[] HEADERS = { "2xx", "3xx", "4xx", "5xx", "OtherStatus", "CacheHits" }; public int status_2xx; public int status_3xx; public int status_4xx; public int status_5xx; public int status_other; public int cacheHits; public static void addStatus(Statistics statistics, long timestamp, int status) { statistics.update(HTTP, timestamp, HttpStats::new, HttpStats.ADD_STATUS, status); } public static void addCacheHit(Statistics statistics, long timestamp) { statistics.update(HTTP, timestamp, HttpStats::new, HttpStats.ADD_CACHE_HIT, 1); } public static HttpStats get(StatisticsSnapshot snapshot) { StatsExtension stats = snapshot.extensions.get(HTTP); if (stats == null) { // return empty to prevent NPEs return new HttpStats(); } return (HttpStats) stats; } public static HttpStats get(StatisticsSummary summary) { StatsExtension stats = summary.extensions.get(HTTP); if (stats == null) { // return empty to prevent NPEs return new HttpStats(); } return (HttpStats) stats; } public int[] statuses() { return new int[] { status_2xx, status_3xx, status_4xx, status_5xx, status_other }; } @Override public void reset() { status_2xx = 0; status_3xx = 0; status_4xx = 0; status_5xx = 0; status_other = 0; cacheHits = 0; } @Override public HttpStats clone() { HttpStats copy = new HttpStats(); copy.add(this); return copy; } @Override public String[] headers() { return HEADERS; } @Override public String byHeader(String header) { switch (header) { case "2xx": return String.valueOf(status_2xx); case "3xx": return String.valueOf(status_3xx); case "4xx": return String.valueOf(status_4xx); case "5xx": return String.valueOf(status_5xx); case "OtherStatus": return String.valueOf(status_other); case "CacheHits": return String.valueOf(cacheHits); default: return "<unknown header: " + header + ">"; } } @Override public boolean isNull() { return status_2xx + status_3xx + status_4xx + status_5xx + status_other + cacheHits == 0; } @Override public void add(StatsExtension other) { if (other instanceof HttpStats) { HttpStats o = (HttpStats) other; status_2xx += o.status_2xx; status_3xx += o.status_3xx; status_4xx += o.status_4xx; status_5xx += o.status_5xx; status_other += o.status_other; cacheHits += o.cacheHits; } else { throw new IllegalArgumentException(other.toString()); } } @Override public void subtract(StatsExtension other) { if (other instanceof HttpStats) { HttpStats o = (HttpStats) other; status_2xx -= o.status_2xx; status_3xx -= o.status_3xx; status_4xx -= o.status_4xx; status_5xx -= o.status_5xx; status_other -= o.status_other; cacheHits -= o.cacheHits; } else { throw new IllegalArgumentException(other.toString()); } } @Override public String toString() { return '{' + ", status_2xx=" + status_2xx + ", status_3xx=" + status_3xx + ", status_4xx=" + status_4xx + ", status_5xx=" + status_5xx + ", status_other=" + status_other + ", cacheHits=" + cacheHits + '}'; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/HttpStepCatalog.java
http/src/main/java/io/hyperfoil/http/steps/HttpStepCatalog.java
package io.hyperfoil.http.steps; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BaseSequenceBuilder; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.core.builders.StepCatalog; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.impl.StepCatalogFactory; public class HttpStepCatalog extends StepCatalog { public static final Class<HttpStepCatalog> SC = HttpStepCatalog.class; HttpStepCatalog(BaseSequenceBuilder<?> parent) { super(parent); } /** * Issue a HTTP request. * * @param method HTTP method. * @return Builder. */ public HttpRequestStepBuilder httpRequest(HttpMethod method) { return new HttpRequestStepBuilder().addTo(parent).method(method); } /** * Block current sequence until all requests receive the response. * * @return This sequence. */ public BaseSequenceBuilder<?> awaitAllResponses() { return parent.step(new AwaitAllResponsesStep()); } /** * Drop all entries from HTTP cache in the session. * * @return This sequence. */ public BaseSequenceBuilder<?> clearHttpCache() { return parent.step(new StepBuilder.ActionStep(new ClearHttpCacheAction())); } @MetaInfServices(StepCatalogFactory.class) public static class Factory implements StepCatalogFactory { @Override public Class<? extends Step.Catalog> clazz() { return HttpStepCatalog.class; } @Override public Step.Catalog create(BaseSequenceBuilder<?> sequenceBuilder) { return new HttpStepCatalog(sequenceBuilder); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/ClearHttpCacheAction.java
http/src/main/java/io/hyperfoil/http/steps/ClearHttpCacheAction.java
package io.hyperfoil.http.steps; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.api.HttpCache; public class ClearHttpCacheAction implements Action { @Override public void run(Session session) { HttpCache httpCache = HttpCache.get(session); if (httpCache != null) { httpCache.clear(); } } /** * Drops all entries from HTTP cache in the session. */ @MetaInfServices(Action.Builder.class) @Name("clearHttpCache") public static class Builder implements Action.Builder { @Override public ClearHttpCacheAction build() { return new ClearHttpCacheAction(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/BodyBuilder.java
http/src/main/java/io/hyperfoil/http/steps/BodyBuilder.java
package io.hyperfoil.http.steps; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.core.generators.Pattern; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.util.ConstantBytesGenerator; import io.hyperfoil.core.util.FromVarBytesGenerator; import io.hyperfoil.impl.Util; /** * Allows building HTTP request body from session variables. */ public class BodyBuilder { private final HttpRequestStepBuilder parent; public BodyBuilder(HttpRequestStepBuilder parent) { this.parent = parent; } /** * Use variable content as request body. * * @param var Variable name. * @return Self. */ public BodyBuilder fromVar(String var) { parent.body(() -> { ReadAccess access = SessionFactory.readAccess(var); return new FromVarBytesGenerator(access); }); return this; } /** * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">Pattern</a> * replacing <code>${sessionvar}</code> with variable contents in a string. * * @param pattern Pattern. * @return Self. */ public BodyBuilder pattern(String pattern) { parent.body(() -> new Pattern(pattern, false).generator()); return this; } /** * String sent as-is. * * @param text String. * @return Self. */ public BodyBuilder text(String text) { parent.body(new ConstantBytesGenerator(text.getBytes(StandardCharsets.UTF_8))); return this; } /** * Build form as if we were sending the request using HTML form. This option automatically adds * <code>Content-Type: application/x-www-form-urlencoded</code> to the request headers. * * @return Builder. */ public FormGenerator.Builder form() { FormGenerator.Builder builder = new FormGenerator.Builder(); parent.headerAppender(new FormGenerator.ContentTypeWriter()); parent.body(builder); return builder; } /** * Send contents of the file. Note that this method does NOT set content-type automatically. * * @param path Path to loaded file. * @return Self. */ public BodyBuilder fromFile(String path) { parent.body(() -> { try (InputStream inputStream = Locator.current().benchmark().data().readFile(path)) { if (inputStream == null) { throw new BenchmarkDefinitionException("Cannot load file `" + path + "` for randomItem (not found)."); } byte[] bytes = Util.toByteArray(inputStream); return new ConstantBytesGenerator(bytes); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot load file `" + path + "` for randomItem.", e); } }); return this; } public HttpRequestStepBuilder endBody() { return parent; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/SendHttpRequestStep.java
http/src/main/java/io/hyperfoil/http/steps/SendHttpRequestStep.java
package io.hyperfoil.http.steps; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.SLA; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.steps.StatisticsStep; import io.hyperfoil.function.SerializableBiConsumer; import io.hyperfoil.function.SerializableBiFunction; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.HttpRequestWriter; import io.netty.buffer.ByteBuf; public class SendHttpRequestStep extends StatisticsStep implements SLA.Provider { private static final Logger log = LogManager.getLogger(SendHttpRequestStep.class); private static final boolean trace = log.isTraceEnabled(); final HttpRequestContext.Key contextKey; final SerializableBiFunction<Session, Connection, ByteBuf> bodyGenerator; final SerializableBiConsumer<Session, HttpRequestWriter>[] headerAppenders; @Visitor.Ignore private final boolean injectHostHeader; final long timeout; final SLA[] sla; public SendHttpRequestStep(int stepId, HttpRequestContext.Key contextKey, SerializableBiFunction<Session, Connection, ByteBuf> bodyGenerator, SerializableBiConsumer<Session, HttpRequestWriter>[] headerAppenders, boolean injectHostHeader, long timeout, SLA[] sla) { super(stepId); this.contextKey = contextKey; this.bodyGenerator = bodyGenerator; this.headerAppenders = headerAppenders; this.injectHostHeader = injectHostHeader; this.timeout = timeout; this.sla = sla; } @Override public boolean invoke(Session session) { HttpRequestContext context = session.getResource(contextKey); if (!context.ready) { // TODO: when the phase is finished, max duration is not set and the connection cannot be obtained // we'll be waiting here forever. Maybe there should be a (default) timeout to obtain the connection. context.startWaiting(); return false; } if (context.connection == null) { log.error("#{} Stopping the session as we cannot obtain connection.", session.uniqueId()); session.stop(); return false; } context.stopWaiting(); HttpRequest request = context.request; request.send(context.connection, headerAppenders, injectHostHeader, bodyGenerator); // We don't need the context anymore and we need to reset it (in case the step is repeated). context.reset(); request.statistics().incrementRequests(request.startTimestampMillis()); if (request.isCompleted()) { // When the request handlers call Session.stop() due to a failure it does not make sense to continue request.release(); return true; } // Set up timeout only after successful request if (timeout > 0) { // TODO alloc! request.setTimeout(timeout, TimeUnit.MILLISECONDS); } else { long timeout = request.connection().config().requestTimeout(); if (timeout > 0) { request.setTimeout(timeout, TimeUnit.MILLISECONDS); } } if (trace) { log.trace("#{} sent to {} request on {}", session.uniqueId(), request.path, request.connection()); } return true; } @Override public SLA[] sla() { return sla; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/AfterSyncRequestStep.java
http/src/main/java/io/hyperfoil/http/steps/AfterSyncRequestStep.java
package io.hyperfoil.http.steps; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.util.BitSetResource; class AfterSyncRequestStep implements Step { private final Session.ResourceKey<BitSetResource> key; AfterSyncRequestStep(Session.ResourceKey<BitSetResource> key) { this.key = key; } @Override public boolean invoke(Session session) { BitSetResource resource = session.getResource(key); return resource.get(session.currentSequence().index()); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/FormGenerator.java
http/src/main/java/io/hyperfoil/http/steps/FormGenerator.java
package io.hyperfoil.http.steps; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.MappingListBuilder; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.generators.Pattern; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableBiConsumer; import io.hyperfoil.function.SerializableBiFunction; import io.hyperfoil.http.api.HttpRequestWriter; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.HttpHeaderNames; public class FormGenerator implements SerializableBiFunction<Session, Connection, ByteBuf> { private static final String APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; private final SerializableBiConsumer<Session, ByteBuf>[] inputs; private FormGenerator(SerializableBiConsumer<Session, ByteBuf>[] inputs) { this.inputs = inputs; } @Override public ByteBuf apply(Session session, Connection connection) { if (inputs.length == 0) { return Unpooled.EMPTY_BUFFER; } ByteBuf buffer = connection.context().alloc().buffer(); inputs[0].accept(session, buffer); for (int i = 1; i < inputs.length; ++i) { buffer.ensureWritable(1); buffer.writeByte('&'); inputs[i].accept(session, buffer); } return buffer; } /** * Build an URL-encoded HTML form body. */ // Note: we cannot implement both a PairBuilder and MappingListBuilder at the same time public static class Builder implements HttpRequestStepBuilder.BodyGeneratorBuilder, MappingListBuilder<InputBuilder> { private final ArrayList<InputBuilder> inputs = new ArrayList<>(); /** * Add input pair described in the mapping. * * @return Builder. */ @Override public InputBuilder addItem() { InputBuilder input = new InputBuilder(); inputs.add(input); return input; } @SuppressWarnings("unchecked") @Override public SerializableBiFunction<Session, Connection, ByteBuf> build() { return new FormGenerator(inputs.stream().map(InputBuilder::build).toArray(SerializableBiConsumer[]::new)); } } /** * Form element (e.g. as if coming from an INPUT field). */ public static class InputBuilder { private String name; private String value; private String fromVar; private String pattern; public SerializableBiConsumer<Session, ByteBuf> build() { if (value != null && fromVar != null && pattern != null) { throw new BenchmarkDefinitionException("Form input: Must set only one of 'value', 'var', 'pattern'"); } else if (value == null && fromVar == null && pattern == null) { throw new BenchmarkDefinitionException("Form input: Must set one of 'value' or 'var' or 'pattern'"); } else if (name == null) { throw new BenchmarkDefinitionException("Form input: 'name' must be set."); } try { byte[] nameBytes = URLEncoder.encode(name, StandardCharsets.UTF_8.name()).getBytes(StandardCharsets.UTF_8); if (value != null) { byte[] valueBytes = URLEncoder.encode(value, StandardCharsets.UTF_8.name()).getBytes(StandardCharsets.UTF_8); return new ConstantInput(nameBytes, valueBytes); } else if (fromVar != null) { ReadAccess access = SessionFactory.readAccess(fromVar); return new VariableInput(nameBytes, access); } else { Pattern pattern = new Pattern(this.pattern, true); return new PatternInput(nameBytes, pattern); } } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } /** * Input field name. * * @param name Input name. * @return Self. */ public InputBuilder name(String name) { this.name = name; return this; } /** * Input field value (verbatim). * * @param value Input value. * @return Self. */ public InputBuilder value(String value) { this.value = value; return this; } /** * Input field value from session variable. * * @param var Variable name. * @return Self. */ public InputBuilder fromVar(String var) { this.fromVar = var; return this; } /** * Input field value replacing session variables in a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>, * e.g. <code>foo${myvariable}var</code> * * @param pattern Template pattern. * @return Self. */ public InputBuilder pattern(String pattern) { this.pattern = pattern; return this; } private static class ConstantInput implements SerializableBiConsumer<Session, ByteBuf> { private final byte[] name; private final byte[] value; ConstantInput(byte[] name, byte[] value) { this.name = name; this.value = value; } @Override public void accept(Session session, ByteBuf buf) { buf.writeBytes(name).writeByte('=').writeBytes(value); } } private static class VariableInput implements SerializableBiConsumer<Session, ByteBuf> { private final byte[] name; private final ReadAccess fromVar; VariableInput(byte[] name, ReadAccess fromVar) { this.name = name; this.fromVar = fromVar; } @Override public void accept(Session session, ByteBuf buf) { buf.writeBytes(name).writeByte('='); Session.Var var = fromVar.getVar(session); if (!var.isSet()) { throw new IllegalStateException("Variable " + fromVar + " was not set yet!"); } if (var.type() == Session.VarType.INTEGER) { Util.intAsText2byteBuf(var.intValue(session), buf); } else if (var.type() == Session.VarType.OBJECT) { Object o = var.objectValue(session); if (o == null) { // keep it empty } else if (o instanceof byte[]) { buf.writeBytes((byte[]) o); } else { Util.urlEncode(o.toString(), buf); } } else { throw new IllegalStateException(); } } } private static class PatternInput implements SerializableBiConsumer<Session, ByteBuf> { private final byte[] name; private final Pattern pattern; PatternInput(byte[] name, Pattern pattern) { this.name = name; this.pattern = pattern; } @Override public void accept(Session session, ByteBuf buf) { buf.writeBytes(name).writeByte('='); pattern.accept(session, buf); } } } public static class ContentTypeWriter implements SerializableBiConsumer<Session, HttpRequestWriter> { @Override public void accept(Session session, HttpRequestWriter writer) { writer.putHeader(HttpHeaderNames.CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/BeforeSyncRequestStep.java
http/src/main/java/io/hyperfoil/http/steps/BeforeSyncRequestStep.java
package io.hyperfoil.http.steps; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.util.BitSetResource; class BeforeSyncRequestStep implements Step, ResourceUtilizer, Session.ResourceKey<BitSetResource> { @Override public boolean invoke(Session s) { BitSetResource resource = s.getResource(this); resource.clear(s.currentSequence().index()); return true; } @Override public void reserve(Session session) { int concurrency = session.currentSequence().definition().concurrency(); session.declareResource(this, () -> BitSetResource.with(concurrency), true); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/AwaitAllResponsesStep.java
http/src/main/java/io/hyperfoil/http/steps/AwaitAllResponsesStep.java
package io.hyperfoil.http.steps; import java.util.Collections; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.HttpRequestPool; public class AwaitAllResponsesStep implements Step { @Override public boolean invoke(Session session) { return HttpRequestPool.get(session).isFull(); } /** * Block current sequence until all requests receive the response. */ @MetaInfServices(StepBuilder.class) @Name("awaitAllResponses") public static class Builder implements StepBuilder<Builder> { @Override public List<Step> build() { return Collections.singletonList(new AwaitAllResponsesStep()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/HttpRequestContext.java
http/src/main/java/io/hyperfoil/http/steps/HttpRequestContext.java
package io.hyperfoil.http.steps; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.api.ConnectionConsumer; import io.hyperfoil.http.api.HttpConnection; import io.hyperfoil.http.api.HttpRequest; /* * HttpRequestStep cannot create and obtain connection without blocking and the behaviour is dependent * on authority & path so we cannot split it into multiple steps. Therefore we'll track the internal * state of execution here. */ class HttpRequestContext implements Session.Resource, ConnectionConsumer { HttpRequest request; HttpConnection connection; boolean ready; long waitTimestamp = Long.MIN_VALUE; @Override public void onSessionReset(Session session) { reset(); } public HttpConnection connection() { return connection; } public void reset() { request = null; connection = null; ready = false; waitTimestamp = Long.MIN_VALUE; } @Override public void accept(HttpConnection connection) { assert request.session.executor().inEventLoop(); this.connection = connection; this.ready = true; this.request.session.proceed(); } public void startWaiting() { if (waitTimestamp == Long.MIN_VALUE) { waitTimestamp = System.nanoTime(); } } public void stopWaiting() { if (waitTimestamp != Long.MIN_VALUE) { long blockedTime = System.nanoTime() - waitTimestamp; request.statistics().incrementBlockedTime(request.startTimestampMillis(), blockedTime); } } public static final class Key implements Session.ResourceKey<HttpRequestContext> { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/HttpRequestStepBuilder.java
http/src/main/java/io/hyperfoil/http/steps/HttpRequestStepBuilder.java
package io.hyperfoil.http.steps; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.PairBuilder; import io.hyperfoil.api.config.PartialBuilder; import io.hyperfoil.api.config.PhaseBuilder; import io.hyperfoil.api.config.SLA; import io.hyperfoil.api.config.SLABuilder; import io.hyperfoil.api.config.ScenarioBuilder; import io.hyperfoil.api.config.SequenceBuilder; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.generators.Pattern; import io.hyperfoil.core.generators.StringGeneratorBuilder; import io.hyperfoil.core.generators.StringGeneratorImplBuilder; import io.hyperfoil.core.handlers.GzipInflatorProcessor; import io.hyperfoil.core.handlers.StoreProcessor; import io.hyperfoil.core.metric.MetricSelector; import io.hyperfoil.core.metric.PathMetricSelector; import io.hyperfoil.core.metric.ProvidedMetricSelector; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.steps.DelaySessionStartStep; import io.hyperfoil.core.steps.StatisticsStep; import io.hyperfoil.core.util.DoubleIncrementBuilder; import io.hyperfoil.core.util.Unique; import io.hyperfoil.function.SerializableBiConsumer; import io.hyperfoil.function.SerializableBiFunction; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.http.UserAgentAppender; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.HttpRequestWriter; import io.hyperfoil.http.config.ConnectionStrategy; import io.hyperfoil.http.config.HttpBuilder; import io.hyperfoil.http.config.HttpErgonomics; import io.hyperfoil.http.config.HttpPluginBuilder; import io.hyperfoil.http.cookie.CookieAppender; import io.hyperfoil.http.handlers.FilterHeaderHandler; import io.hyperfoil.http.statistics.HttpStats; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.util.AsciiString; /** * Issues a HTTP request and registers handlers for the response. */ @MetaInfServices(StepBuilder.class) @Name("httpRequest") public class HttpRequestStepBuilder extends BaseStepBuilder<HttpRequestStepBuilder> { private static final Logger log = LogManager.getLogger(SendHttpRequestStep.class); private int stepId = -1; private HttpMethod.Builder method; private StringGeneratorBuilder authority; private StringGeneratorBuilder endpoint; private StringGeneratorBuilder path; private BodyGeneratorBuilder body; private final List<Supplier<SerializableBiConsumer<Session, HttpRequestWriter>>> headerAppenders = new ArrayList<>(); private boolean injectHostHeader = true; private MetricSelector metricSelector; private long timeout = Long.MIN_VALUE; private HttpResponseHandlersImpl.Builder handler = new HttpResponseHandlersImpl.Builder(this); private boolean sync = true; private SLABuilder.ListBuilder<HttpRequestStepBuilder> sla = null; private CompensationBuilder compensation; private CompressionBuilder compression = new CompressionBuilder(this); /** * HTTP method used for the request. * * @param method HTTP method. * @return Self. */ public HttpRequestStepBuilder method(HttpMethod method) { return method(new HttpMethod.ProvidedBuilder(method)); } public HttpRequestStepBuilder method(HttpMethod.Builder method) { this.method = method; return this; } /** * Issue HTTP GET request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder GET(String path) { return method(HttpMethod.GET).path().pattern(path).end(); } /** * Issue HTTP GET request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> GET() { return method(HttpMethod.GET).path(); } /** * Issue HTTP HEAD request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder HEAD(String path) { return method(HttpMethod.HEAD).path().pattern(path).end(); } /** * Issue HTTP HEAD request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> HEAD() { return method(HttpMethod.HEAD).path(); } /** * Issue HTTP POST request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder POST(String path) { return method(HttpMethod.POST).path().pattern(path).end(); } /** * Issue HTTP POST request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> POST() { return method(HttpMethod.POST).path(); } /** * Issue HTTP PUT request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder PUT(String path) { return method(HttpMethod.PUT).path().pattern(path).end(); } /** * Issue HTTP PUT request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> PUT() { return method(HttpMethod.PUT).path(); } /** * Issue HTTP DELETE request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder DELETE(String path) { return method(HttpMethod.DELETE).path().pattern(path).end(); } /** * Issue HTTP DELETE request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> DELETE() { return method(HttpMethod.DELETE).path(); } /** * Issue HTTP OPTIONS request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder OPTIONS(String path) { return method(HttpMethod.OPTIONS).path().pattern(path).end(); } /** * Issue HTTP OPTIONS request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> OPTIONS() { return method(HttpMethod.OPTIONS).path(); } /** * Issue HTTP PATCH request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder PATCH(String path) { return method(HttpMethod.PATCH).path().pattern(path).end(); } /** * Issue HTTP PATCH request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> PATCH() { return method(HttpMethod.PATCH).path(); } /** * Issue HTTP TRACE request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder TRACE(String path) { return method(HttpMethod.TRACE).path().pattern(path).end(); } /** * Issue HTTP TRACE request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> TRACE() { return method(HttpMethod.TRACE).path(); } /** * Issue HTTP CONNECT request to given path. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param path HTTP path, a pattern replacing <code>${sessionvar}</code> with variable contents. * @return Self. */ public HttpRequestStepBuilder CONNECT(String path) { return method(HttpMethod.CONNECT).path().pattern(path).end(); } /** * Issue HTTP CONNECT request to given path. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> CONNECT() { return method(HttpMethod.CONNECT).path(); } /** * HTTP authority (host:port) this request should target. Must match one of the entries in <code>http</code> section. * The string can use <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">string * interpolation</a>. * * @param authority Host:port. * @return Self. */ public HttpRequestStepBuilder authority(String authority) { return authority().pattern(authority).end(); } public HttpRequestStepBuilder authority(SerializableFunction<Session, String> authorityGenerator) { return authority(() -> authorityGenerator); } /** * HTTP authority (host:port) this request should target. Must match one of the entries in <code>http</code> section. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> authority() { StringGeneratorImplBuilder<HttpRequestStepBuilder> builder = new StringGeneratorImplBuilder<>(this); authority(builder); return builder; } public HttpRequestStepBuilder authority(StringGeneratorBuilder authority) { this.authority = authority; return this; } /** * HTTP endpoint this request should target. Must match to the <code>name</code> of the entries in <code>http</code> section. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> endpoint() { var builder = new StringGeneratorImplBuilder<>(this); this.endpoint = builder; return builder; } /** * HTTP path (absolute or relative), including query and fragment. * The string can use <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">string * interpolation</a>. * * @return Self. */ public HttpRequestStepBuilder path(String path) { return path(() -> new Pattern(path, false)); } /** * HTTP path (absolute or relative), including query and fragment. * * @return Builder. */ public StringGeneratorImplBuilder<HttpRequestStepBuilder> path() { StringGeneratorImplBuilder<HttpRequestStepBuilder> builder = new StringGeneratorImplBuilder<>(this); path(builder); return builder; } public HttpRequestStepBuilder path(SerializableFunction<Session, String> pathGenerator) { return path(() -> pathGenerator); } public HttpRequestStepBuilder path(StringGeneratorBuilder builder) { if (this.path != null) { throw new BenchmarkDefinitionException("Path generator already set."); } this.path = builder; return this; } /** * HTTP request body (possibly a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>). * * @param string Request body. * @return Self. */ public HttpRequestStepBuilder body(String string) { return body().pattern(string).endBody(); } /** * HTTP request body. * * @return Builder. */ public BodyBuilder body() { return new BodyBuilder(this); } public HttpRequestStepBuilder body(SerializableBiFunction<Session, Connection, ByteBuf> bodyGenerator) { return body(() -> bodyGenerator); } public HttpRequestStepBuilder body(BodyGeneratorBuilder bodyGenerator) { if (this.body != null) { throw new BenchmarkDefinitionException("Body generator already set."); } this.body = bodyGenerator; return this; } BodyGeneratorBuilder bodyBuilder() { return body; } public HttpRequestStepBuilder headerAppender(SerializableBiConsumer<Session, HttpRequestWriter> headerAppender) { headerAppenders.add(() -> headerAppender); return this; } public HttpRequestStepBuilder headerAppenders( Collection<? extends Supplier<SerializableBiConsumer<Session, HttpRequestWriter>>> appenders) { headerAppenders.addAll(appenders); return this; } List<Supplier<SerializableBiConsumer<Session, HttpRequestWriter>>> headerAppenders() { return Collections.unmodifiableList(headerAppenders); } /** * HTTP headers sent in the request. * * @return Builder. */ public HeadersBuilder headers() { return new HeadersBuilder(this); } public HttpRequestStepBuilder timeout(long timeout, TimeUnit timeUnit) { if (timeout <= 0) { throw new BenchmarkDefinitionException("Timeout must be positive!"); } else if (this.timeout != Long.MIN_VALUE) { throw new BenchmarkDefinitionException("Timeout already set!"); } this.timeout = timeUnit.toMillis(timeout); return this; } /** * Request timeout - after this time the request will be marked as failed and connection will be closed. * <p> * Defaults to value set globally in <code>http</code> section. * * @param timeout Timeout. * @return Self. */ public HttpRequestStepBuilder timeout(String timeout) { return timeout(Util.parseToMillis(timeout), TimeUnit.MILLISECONDS); } /** * Requests statistics will use this metric name. * * @param name Metric name. * @return Self. */ public HttpRequestStepBuilder metric(String name) { return metric(new ProvidedMetricSelector(name)); } public HttpRequestStepBuilder metric(MetricSelector selector) { this.metricSelector = selector; return this; } /** * Allows categorizing request statistics into metrics based on the request path. * * @return Builder. */ public PathMetricSelector metric() { PathMetricSelector selector = new PathMetricSelector(); this.metricSelector = selector; return selector; } /** * HTTP response handlers. * * @return Builder. */ public HttpResponseHandlersImpl.Builder handler() { return handler; } /** * This request is synchronous; execution of the sequence does not continue until the full response * is received. If this step is executed from multiple parallel instances of this sequence the progress * of all sequences is blocked until there is a request in flight without response. * <p> * Default is <code>true</code>. * * @param sync Synchronous? * @return Self. */ public HttpRequestStepBuilder sync(boolean sync) { this.sync = sync; return this; } /** * List of SLAs the requests are subject to. * * @return Builder. */ public SLABuilder.ListBuilder<HttpRequestStepBuilder> sla() { if (sla == null) { sla = new SLABuilder.ListBuilder<>(this); } return sla; } /** * Configures additional metric compensated for coordinated omission. * * @return Builder. */ public CompensationBuilder compensation() { return this.compensation = new CompensationBuilder(this); } /** * Request server to respond with compressed entity using specified content encoding. * * @param encoding Encoding. Currently supports only <code>gzip</code>. * @return Self. */ public HttpRequestStepBuilder compression(String encoding) { compression().encoding(encoding); return this; } /** * Configure response compression. * * @return Builder. */ public CompressionBuilder compression() { return compression; } @Override public int id() { assert stepId >= 0; return stepId; } @Override public void prepareBuild() { stepId = StatisticsStep.nextId(); Locator locator = Locator.current(); HttpErgonomics ergonomics = locator.benchmark().plugin(HttpPluginBuilder.class).ergonomics(); if (ergonomics.repeatCookies()) { headerAppender(new CookieAppender()); } if (ergonomics.userAgentFromSession()) { headerAppender(new UserAgentAppender()); } BeforeSyncRequestStep beforeSyncRequestStep = null; if (sync) { // We need to perform this in prepareBuild() because the completion handlers must not be modified // in the build() method. Alternative would be caching the key and returning the wrapping steps // in the list. beforeSyncRequestStep = new BeforeSyncRequestStep(); locator.sequence().insertBefore(locator).step(beforeSyncRequestStep); handler.onCompletion(new ReleaseSyncAction(beforeSyncRequestStep)); // AfterSyncRequestStep must be inserted only after all handlers are prepared } if (metricSelector == null) { String sequenceName = Locator.current().sequence().name(); metricSelector = new ProvidedMetricSelector(sequenceName); } if (compensation != null) { compensation.prepareBuild(); } compression.prepareBuild(); handler.prepareBuild(); // We insert the AfterSyncRequestStep only after preparing all the handlers to ensure // that this is added immediately after the SendHttpRequestStep, in case some of the handlers // insert their own steps after current step. (We could do this in the build() method, too). if (sync) { locator.sequence().insertAfter(locator).step(new AfterSyncRequestStep(beforeSyncRequestStep)); } } @Override public List<Step> build() { String guessedAuthority = null; boolean checkAuthority = true; HttpPluginBuilder httpPlugin = Locator.current().benchmark().plugin(HttpPluginBuilder.class); SerializableFunction<Session, String> authority = this.authority != null ? this.authority.build() : null; SerializableFunction<Session, String> endpoint = this.endpoint != null ? this.endpoint.build() : null; HttpBuilder http = null; if (authority != null && endpoint != null) { throw new BenchmarkDefinitionException( "You have set both endpoint (abstract name) and authority (host:port) as the request target; use only one."); } if (endpoint != null) { checkAuthority = false; try { String guessedEndpoint = endpoint.apply(null); if (guessedEndpoint != null) { if (!httpPlugin.validateEndpoint(guessedEndpoint)) { throw new BenchmarkDefinitionException("There is no HTTP endpoint '" + guessedEndpoint + "'"); } http = httpPlugin.getHttpByName(guessedEndpoint); } } catch (Throwable e) { // errors are allowed here } } SerializableFunction<Session, String> pathGenerator = this.path != null ? this.path.build() : null; try { guessedAuthority = authority == null ? null : authority.apply(null); } catch (Throwable e) { checkAuthority = false; } if (checkAuthority) { http = httpPlugin.getHttp(guessedAuthority); } if (checkAuthority && !httpPlugin.validateAuthority(guessedAuthority)) { String guessedPath = "<unknown path>"; try { if (pathGenerator != null) { guessedPath = pathGenerator.apply(null); } } catch (Throwable e) { // errors are allowed here } if (authority == null) { throw new BenchmarkDefinitionException(String .format("%s to <default route>%s is invalid as we don't have a default route set.", method, guessedPath)); } else { throw new BenchmarkDefinitionException(String.format("%s to %s%s is invalid - no HTTP configuration defined.", method, guessedAuthority, guessedPath)); } } if (sla == null && http != null && (http.connectionStrategy() == ConnectionStrategy.OPEN_ON_REQUEST || http.connectionStrategy() == ConnectionStrategy.ALWAYS_NEW)) { this.sla = new SLABuilder.ListBuilder<>(this).addItem().blockedRatio(1.01).endSLA(); } @SuppressWarnings("unchecked") SerializableBiConsumer<Session, HttpRequestWriter>[] headerAppenders = this.headerAppenders.isEmpty() ? null : this.headerAppenders.stream().map(Supplier::get).toArray(SerializableBiConsumer[]::new); SLA[] sla = this.sla != null ? this.sla.build() : SLABuilder.DEFAULT; SerializableBiFunction<Session, Connection, ByteBuf> bodyGenerator = this.body != null ? this.body.build() : null; HttpRequestContext.Key contextKey = new HttpRequestContext.Key(); PrepareHttpRequestStep prepare = new PrepareHttpRequestStep(stepId, contextKey, method.build(), endpoint, authority, pathGenerator, metricSelector, handler.build()); SendHttpRequestStep step = new SendHttpRequestStep(stepId, contextKey, bodyGenerator, headerAppenders, injectHostHeader, timeout, sla); return Arrays.asList(prepare, step); } public enum CompressionType { /** * Use <code>Accept-Encoding</code> in request and expect <code>Content-Encoding</code> in response. */ CONTENT_ENCODING, /** * Use <code>TE</code> in request and expect <code>Transfer-Encoding</code> in response. */ TRANSFER_ENCODING } public interface BodyGeneratorBuilder extends BuilderBase<BodyGeneratorBuilder> { SerializableBiFunction<Session, Connection, ByteBuf> build(); } private static class PrefixMetricSelector implements SerializableBiFunction<String, String, String> { private final String prefix; private final SerializableBiFunction<String, String, String> delegate; private PrefixMetricSelector(String prefix, SerializableBiFunction<String, String, String> delegate) { this.prefix = prefix; this.delegate = delegate; } @Override public String apply(String authority, String path) { return prefix + delegate.apply(authority, path); } } private static class ReleaseSyncAction implements Action { @Visitor.Ignore private final BeforeSyncRequestStep beforeSyncRequestStep; ReleaseSyncAction(BeforeSyncRequestStep beforeSyncRequestStep) { this.beforeSyncRequestStep = beforeSyncRequestStep; } @Override public void run(Session s) { s.getResource(beforeSyncRequestStep).set(s.currentSequence().index()); } } public static class HeadersBuilder extends PairBuilder.OfString implements PartialBuilder { private final HttpRequestStepBuilder parent; public HeadersBuilder(HttpRequestStepBuilder builder) { this.parent = builder; } public HeadersBuilder header(CharSequence header, CharSequence value) { warnIfUsingHostHeader(header); parent.headerAppender(new StaticHeaderWriter(header, value)); return this; } /** * Use header name (e.g. <code>Content-Type</code>) as key and value (possibly a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>). */ @Override public void accept(String header, String value) { withKey(header).pattern(value); } public HttpRequestStepBuilder endHeaders() { return parent; } /** * Use header name (e.g. <code>Content-Type</code>) as key and specify value in the mapping. */ @Override public PartialHeadersBuilder withKey(String key) { warnIfUsingHostHeader(key); return new PartialHeadersBuilder(this, key); } private void warnIfUsingHostHeader(CharSequence key) { if (key.toString().equalsIgnoreCase("host")) { log.warn( "Setting `host` header explicitly is not recommended. Use the HTTP host and adjust actual target using `addresses` property."); parent.injectHostHeader = false; } } } private static class StaticHeaderWriter implements SerializableBiConsumer<Session, HttpRequestWriter> { private final CharSequence header; private final CharSequence value; private StaticHeaderWriter(CharSequence header, CharSequence value) { this.header = header; this.value = value; } @Override public void accept(Session session, HttpRequestWriter writer) { writer.putHeader(header, value); } } /** * Specifies value that should be sent in headers. */ public static class PartialHeadersBuilder implements InitFromParam<PartialHeadersBuilder> { private final HeadersBuilder parent; private final String header; private boolean added; private PartialHeadersBuilder(HeadersBuilder parent, String header) { this.parent = parent; this.header = header; } /** * @param param The value. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * @return Self. */ @Override public PartialHeadersBuilder init(String param) { return pattern(param); } /** * Load header value from session variable. * * @param var Variable name. * @return Self. */ public PartialHeadersBuilder fromVar(String var) { ensureOnce(); parent.parent.headerAppenders.add(() -> new FromVarHeaderWriter(header, SessionFactory.readAccess(var))); return this; } /** * Load header value using a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param patternString Pattern to be encoded, e.g. <code>foo${variable}bar${another-variable}</code> * @return Builder. */ public PartialHeadersBuilder pattern(String patternString) { ensureOnce(); parent.parent.headerAppenders .add(() -> new PartialHeadersBuilder.PatternHeaderWriter(header, new Pattern(patternString, false))); return this; } private void ensureOnce() { if (added) { throw new BenchmarkDefinitionException( "Trying to add header " + header + " twice. Use only one of: fromVar, pattern"); } added = true; } public HeadersBuilder end() { return parent; } private static class PatternHeaderWriter implements SerializableBiConsumer<Session, HttpRequestWriter> { private final String header; private final Pattern pattern; PatternHeaderWriter(String header, Pattern pattern) { this.header = header; this.pattern = pattern; } @Override public void accept(Session session, HttpRequestWriter writer) { writer.putHeader(header, pattern.apply(session)); } } } private static class FromVarHeaderWriter implements SerializableBiConsumer<Session, HttpRequestWriter> { private final CharSequence header; private final ReadAccess fromVar; FromVarHeaderWriter(CharSequence header, ReadAccess fromVar) { this.fromVar = fromVar; this.header = header; } @Override public void accept(Session session, HttpRequestWriter writer) { Object value = fromVar.getObject(session); if (value instanceof CharSequence) { writer.putHeader(header, (CharSequence) value); } else { log.error("#{} Cannot convert variable {}: {} to CharSequence", session.uniqueId(), fromVar, value); } } } public static class CompensationBuilder { private static final String DELAY_SESSION_START = "__delay-session-start"; private final HttpRequestStepBuilder parent; public SerializableBiFunction<String, String, String> metricSelector; public double targetRate; public double targetRateIncrement; private DoubleIncrementBuilder targetRateBuilder; public CompensationBuilder(HttpRequestStepBuilder parent) { this.parent = parent; } /** * Desired rate of new virtual users per second. This is similar to <code>constantRate.usersPerSec</code> * phase settings but works closer to legacy benchmark drivers by fixing the concurrency. * * @param targetRate Used for calculating the period of each virtual user. * @return Self. */ public CompensationBuilder targetRate(double targetRate) { this.targetRate = targetRate; return this; } /** * Desired rate of new virtual users per second. This is similar to <code>constantRate.usersPerSec</code> * phase settings but works closer to legacy benchmark drivers by fixing the concurrency. * * @return Builder. */ public DoubleIncrementBuilder targetRate() { return targetRateBuilder = new DoubleIncrementBuilder((base, inc) -> { this.targetRate = base; this.targetRateIncrement = inc; }); } /** * Metric name for the compensated results. * * @param name Metric name. * @return Self. */ public CompensationBuilder metric(String name) { this.metricSelector = new ProvidedMetricSelector(name); return this; } /** * Configure a custom metric for the compensated results. * * @return Builder. */ public PathMetricSelector metric() { PathMetricSelector metricSelector = new PathMetricSelector(); this.metricSelector = metricSelector; return metricSelector; } public void prepareBuild() { if (targetRateBuilder != null) { targetRateBuilder.apply(); } ScenarioBuilder scenario = Locator.current().scenario(); PhaseBuilder<?> phaseBuilder = scenario.endScenario(); if (!(phaseBuilder instanceof PhaseBuilder.Always)) { throw new BenchmarkDefinitionException("delaySessionStart step makes sense only in phase type 'always'"); } if (!scenario.hasSequence(DELAY_SESSION_START)) { List<SequenceBuilder> prev = scenario.resetInitialSequences(); scenario.initialSequence(DELAY_SESSION_START) .step(new DelaySessionStartStep(prev.stream().map(SequenceBuilder::name).toArray(String[]::new), targetRate, targetRateIncrement, true)); } else { log.warn( "Scenario for phase {} contains multiple compensating HTTP requests: make sure that all use the same rate.", phaseBuilder.name());
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
true
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/HttpResponseHandlersImpl.java
http/src/main/java/io/hyperfoil/http/steps/HttpResponseHandlersImpl.java
package io.hyperfoil.http.steps; import static io.hyperfoil.core.session.SessionFactory.objectAccess; import static io.hyperfoil.core.session.SessionFactory.sequenceScopedObjectAccess; import static io.hyperfoil.core.session.SessionFactory.sequenceScopedReadAccess; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.FormattedMessage; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.SequenceBuilder; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.processor.RawBytesHandler; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.core.data.LimitedPoolResource; import io.hyperfoil.core.data.Queue; import io.hyperfoil.core.handlers.ConditionalAction; import io.hyperfoil.core.handlers.ConditionalProcessor; import io.hyperfoil.core.steps.AwaitDelayStep; import io.hyperfoil.core.steps.PushQueueAction; import io.hyperfoil.core.steps.ScheduleDelayStep; import io.hyperfoil.core.util.Unique; import io.hyperfoil.function.SerializableToLongFunction; import io.hyperfoil.http.api.FollowRedirect; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.HttpCache; import io.hyperfoil.http.api.HttpRequest; import io.hyperfoil.http.api.HttpResponseHandlers; import io.hyperfoil.http.api.StatusHandler; import io.hyperfoil.http.config.HttpErgonomics; import io.hyperfoil.http.config.HttpPluginBuilder; import io.hyperfoil.http.cookie.CookieRecorder; import io.hyperfoil.http.handlers.ConditionalHeaderHandler; import io.hyperfoil.http.handlers.Location; import io.hyperfoil.http.handlers.RangeStatusValidator; import io.hyperfoil.http.handlers.Redirect; import io.hyperfoil.http.html.HtmlHandler; import io.hyperfoil.http.html.MetaRefreshHandler; import io.hyperfoil.http.html.RefreshHandler; import io.hyperfoil.http.statistics.HttpStats; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.util.AsciiString; public class HttpResponseHandlersImpl implements HttpResponseHandlers, Serializable { private static final Logger log = LogManager.getLogger(HttpResponseHandlersImpl.class); private static final boolean trace = log.isTraceEnabled(); final StatusHandler[] statusHandlers; final HeaderHandler[] headerHandlers; final Processor[] bodyHandlers; final Action[] completionHandlers; final RawBytesHandler[] rawBytesHandlers; private HttpResponseHandlersImpl(StatusHandler[] statusHandlers, HeaderHandler[] headerHandlers, Processor[] bodyHandlers, Action[] completionHandlers, RawBytesHandler[] rawBytesHandlers) { this.statusHandlers = statusHandlers; this.headerHandlers = headerHandlers; this.bodyHandlers = bodyHandlers; this.completionHandlers = completionHandlers; this.rawBytesHandlers = rawBytesHandlers; } @Override public boolean requiresHandlingHeaders(HttpRequest request) { return (headerHandlers != null && headerHandlers.length > 0) || request.hasCacheControl() || trace; } @Override public void handleStatus(HttpRequest request, int status, String reason) { Session session = request.session; if (request.isCompleted()) { if (trace) { log.trace("#{} Ignoring status {} as the request has been marked completed (failed).", session.uniqueId(), status); } return; } if (trace) { log.trace("#{} Received status {}: {}", session.uniqueId(), status, reason); } try { switch (request.method) { case GET: case HEAD: // TODO: should we store 203, 300, 301 and 410? // TODO: partial response 206 if (status != 200 && request.hasCacheControl()) { request.cacheControl.noStore = true; } break; case POST: case PUT: case DELETE: case PATCH: if (request.hasCacheControl()) { if (status >= 200 && status <= 399) { HttpCache.get(request.session).invalidate(request.authority, request.path); request.cacheControl.invalidate = true; } request.cacheControl.noStore = true; } break; } HttpStats.addStatus(request.statistics(), request.startTimestampMillis(), status); if (statusHandlers != null) { for (StatusHandler handler : statusHandlers) { handler.handleStatus(request, status); } } if (headerHandlers != null) { for (HeaderHandler handler : headerHandlers) { handler.beforeHeaders(request); } } if (bodyHandlers != null) { for (Processor handler : bodyHandlers) { handler.before(request.session); } } } catch (SessionStopException e) { throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} Response status processing failed on {}", session.uniqueId(), this), t); request.statistics().incrementInternalErrors(request.startTimestampMillis()); request.markInvalid(); session.stop(); } } @Override public void handleHeader(HttpRequest request, CharSequence header, CharSequence value) { Session session = request.session; if (request.isCompleted()) { if (trace) { log.trace("#{} Ignoring header on a failed request: {}: {}", session.uniqueId(), header, value); } return; } if (trace) { log.trace("#{} Received header {}: {}", session.uniqueId(), header, value); } try { HttpCache httpCache = request.hasCacheControl() ? HttpCache.get(session) : null; if (httpCache != null && request.cacheControl.invalidate) { if (AsciiString.contentEqualsIgnoreCase(header, HttpHeaderNames.LOCATION) || AsciiString.contentEqualsIgnoreCase(header, HttpHeaderNames.CONTENT_LOCATION)) { httpCache.invalidate(request.authority, value); } } if (headerHandlers != null) { for (HeaderHandler handler : headerHandlers) { handler.handleHeader(request, header, value); } } if (httpCache != null) { httpCache.responseHeader(request, header, value); } } catch (SessionStopException e) { throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} Response header processing failed on {}", session.uniqueId(), this), t); request.statistics().incrementInternalErrors(request.startTimestampMillis()); request.markInvalid(); session.stop(); } } @Override public void handleThrowable(HttpRequest request, Throwable throwable) { Session session = request.session; if (log.isDebugEnabled()) { log.debug(new FormattedMessage("#{} {} Received exception", session.uniqueId(), request), throwable); } if (request.isCompleted()) { if (trace) { log.trace("#{} Request has been already completed", session.uniqueId()); } return; } if (request.isValid()) { // Do not mark as invalid when timed out request.markInvalid(); } try { if (request.isRunning()) { request.statistics().incrementConnectionErrors(request.startTimestampMillis()); request.setCompleting(); if (completionHandlers != null) { for (Action handler : completionHandlers) { handler.run(session); } } } } catch (SessionStopException e) { throw e; } catch (Throwable t) { t.addSuppressed(throwable); log.error(new FormattedMessage("#{} Exception {} thrown while handling another exception: ", session.uniqueId(), throwable.toString()), t); request.statistics().incrementInternalErrors(request.startTimestampMillis()); session.stop(); } finally { request.setCompleted(); } } @Override public void handleBodyPart(HttpRequest request, ByteBuf data, int offset, int length, boolean isLastPart) { Session session = request.session; if (request.isCompleted()) { if (trace) { log.trace("#{} Ignoring body part ({} bytes) on a failed request.", session.uniqueId(), data.readableBytes()); } return; } if (trace) { log.trace("#{} Received part ({} bytes):\n{}", session.uniqueId(), length, data.toString(offset, length, StandardCharsets.UTF_8)); } try { int dataStartIndex = data.readerIndex(); if (bodyHandlers != null) { for (Processor handler : bodyHandlers) { handler.process(request.session, data, offset, length, isLastPart); data.readerIndex(dataStartIndex); } } } catch (SessionStopException e) { throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} Response body processing failed on {}", session.uniqueId(), this), t); request.statistics().incrementInternalErrors(request.startTimestampMillis()); request.markInvalid(); session.stop(); } } @Override public void handleEnd(HttpRequest request, boolean executed) { Session session = request.session; if (request.isCompleted()) { if (trace) { log.trace("#{} Request has been already completed.", session.uniqueId()); } return; } if (trace) { log.trace("#{} Completed request on {}", session.uniqueId(), request.connection()); } try { if (request.isRunning()) { request.setCompleting(); if (executed) { request.recordResponse(System.nanoTime()); if (headerHandlers != null) { for (HeaderHandler handler : headerHandlers) { handler.afterHeaders(request); } } if (bodyHandlers != null) { for (Processor handler : bodyHandlers) { handler.after(request.session); } } if (request.hasCacheControl()) { HttpCache.get(request.session).tryStore(request); } } if (completionHandlers != null) { for (Action handler : completionHandlers) { handler.run(session); } } } } catch (SessionStopException e) { throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} Response completion failed on {}, stopping the session.", request.session.uniqueId(), this), t); request.statistics().incrementInternalErrors(request.startTimestampMillis()); request.markInvalid(); session.stop(); } finally { // When one of the handlers calls Session.stop() it may terminate the phase completely, // sending stats before this finally-block may run. In that case this request gets completed // when cancelling all the request (including the current request) and we record the invalid // request directly there. if (executed && !request.isValid() && !request.isCompleted()) { request.statistics().addInvalid(request.startTimestampMillis()); } request.setCompleted(); } } @Override public void handleRawRequest(HttpRequest request, ByteBuf data, int offset, int length) { if (rawBytesHandlers == null) { return; } try { for (RawBytesHandler rawBytesHandler : rawBytesHandlers) { rawBytesHandler.onRequest(request, data, offset, length); } } catch (SessionStopException e) { throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} Raw request processing failed on {}", request.session.uniqueId(), this), t); request.markInvalid(); request.session.stop(); } } @Override public void handleRawResponse(HttpRequest request, ByteBuf data, int offset, int length, boolean isLastPart) { if (rawBytesHandlers == null) { return; } try { for (RawBytesHandler rawBytesHandler : rawBytesHandlers) { rawBytesHandler.onResponse(request, data, offset, length, isLastPart); } } catch (SessionStopException e) { throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} Raw response processing failed on {}", request.session.uniqueId(), this), t); request.markInvalid(); request.session.stop(); } } /** * Manages processing of HTTP responses. */ public static class Builder implements BuilderBase<Builder> { private final HttpRequestStepBuilder parent; private Boolean autoRangeCheck; private Boolean stopOnInvalid; private FollowRedirect followRedirect; private List<StatusHandler.Builder> statusHandlers = new ArrayList<>(); private List<HeaderHandler.Builder> headerHandlers = new ArrayList<>(); private List<Processor.Builder> bodyHandlers = new ArrayList<>(); private List<Action.Builder> completionHandlers = new ArrayList<>(); private List<RawBytesHandler.Builder> rawBytesHandlers = new ArrayList<>(); public static Builder forTesting() { return new Builder(null); } public Builder(HttpRequestStepBuilder parent) { this.parent = parent; } public Builder status(StatusHandler.Builder builder) { statusHandlers.add(builder); return this; } public Builder status(StatusHandler handler) { statusHandlers.add(() -> handler); return this; } /** * Handle HTTP response status. * * @return Builder. */ public ServiceLoadedBuilderProvider<StatusHandler.Builder> status() { return new ServiceLoadedBuilderProvider<>(StatusHandler.Builder.class, statusHandlers::add); } public Builder header(HeaderHandler handler) { return header(() -> handler); } public Builder header(HeaderHandler.Builder builder) { headerHandlers.add(builder); return this; } /** * Handle HTTP response headers. * * @return Builder. */ public ServiceLoadedBuilderProvider<HeaderHandler.Builder> header() { return new ServiceLoadedBuilderProvider<>(HeaderHandler.Builder.class, headerHandlers::add); } public Builder body(Processor.Builder builder) { bodyHandlers.add(builder); return this; } /** * Handle HTTP response body. * * @return Builder. */ public ServiceLoadedBuilderProvider<Processor.Builder> body() { return new ServiceLoadedBuilderProvider<>(Processor.Builder.class, bodyHandlers::add); } public Builder onCompletion(Action handler) { return onCompletion(() -> handler); } public Builder onCompletion(Action.Builder builder) { completionHandlers.add(builder); return this; } /** * Action executed when the HTTP response is fully received. * * @return Builder. */ public ServiceLoadedBuilderProvider<Action.Builder> onCompletion() { return new ServiceLoadedBuilderProvider<>(Action.Builder.class, completionHandlers::add); } public Builder rawBytes(RawBytesHandler handler) { rawBytesHandlers.add(() -> handler); return this; } public Builder rawBytes(RawBytesHandler.Builder builder) { rawBytesHandlers.add(builder); return this; } /** * Handler processing HTTP response before parsing. * * @return Builder. */ public ServiceLoadedBuilderProvider<RawBytesHandler.Builder> rawBytes() { return new ServiceLoadedBuilderProvider<>(RawBytesHandler.Builder.class, this::rawBytes); } /** * Inject status handler that marks the request as invalid on status 4xx or 5xx. * Default value depends on <code>ergonomics.autoRangeCheck</code> * (see <a href="https://hyperfoil.io/docs/user-guide/benchmark/ergonomics">User Guide</a>). * * @param autoRangeCheck True for inserting the handler, false otherwise. * @return Self. */ public Builder autoRangeCheck(boolean autoRangeCheck) { this.autoRangeCheck = autoRangeCheck; return this; } /** * Inject completion handler that will stop the session if the request has been marked as invalid. * Default value depends on <code>ergonomics.stopOnInvalid</code> * (see <a href="https://hyperfoil.io/userguide/benchmark/ergonomics.html">User Guide</a>). * * @param stopOnInvalid Do inject the handler. * @return Self. */ public Builder stopOnInvalid(boolean stopOnInvalid) { this.stopOnInvalid = stopOnInvalid; return this; } /** * Automatically fire requests when the server responds with redirection. * Default value depends on <code>ergonomics.followRedirect</code> * (see <a href="https://hyperfoil.io/userguide/benchmark/ergonomics.html">User Guide</a>). * * @param followRedirect Types of server response that will trigger the request. * @return Self. */ public Builder followRedirect(FollowRedirect followRedirect) { this.followRedirect = followRedirect; return this; } public HttpRequestStepBuilder endHandler() { return parent; } public Builder wrapBodyHandlers(Function<Collection<Processor.Builder>, Processor.Builder> func) { Processor.Builder wrapped = func.apply(bodyHandlers); this.bodyHandlers = new ArrayList<>(); this.bodyHandlers.add(wrapped); return this; } public void prepareBuild() { HttpErgonomics ergonomics = Locator.current().benchmark().plugin(HttpPluginBuilder.class).ergonomics(); if (ergonomics.repeatCookies()) { header(new CookieRecorder()); } // TODO: we might need defensive copies here statusHandlers.forEach(StatusHandler.Builder::prepareBuild); headerHandlers.forEach(HeaderHandler.Builder::prepareBuild); bodyHandlers.forEach(Processor.Builder::prepareBuild); completionHandlers.forEach(Action.Builder::prepareBuild); rawBytesHandlers.forEach(RawBytesHandler.Builder::prepareBuild); if (autoRangeCheck != null ? autoRangeCheck : ergonomics.autoRangeCheck()) { statusHandlers.add(new RangeStatusValidator.Builder().min(200).max(399)); } // We must add this as the very last action since after calling session.stop() there other handlers won't be called if (stopOnInvalid != null ? stopOnInvalid : ergonomics.stopOnInvalid()) { completionHandlers.add(() -> StopOnInvalidAction.INSTANCE); } FollowRedirect followRedirect = this.followRedirect != null ? this.followRedirect : ergonomics.followRedirect(); switch (followRedirect) { case LOCATION_ONLY: applyRedirect(true, false); break; case HTML_ONLY: applyRedirect(false, true); break; case ALWAYS: applyRedirect(true, true); break; } } private void applyRedirect(boolean location, boolean html) { Locator locator = Locator.current(); // Not sequence-scoped as queue output var, requesting sequence-scoped access explicitly where needed Unique coordsVar = new Unique(); String redirectSequenceName = String.format("%s_redirect_%08x", locator.sequence().name(), ThreadLocalRandom.current().nextInt()); String delaySequenceName = String.format("%s_delay_%08x", locator.sequence().name(), ThreadLocalRandom.current().nextInt()); Queue.Key queueKey = new Queue.Key(); Queue.Key delayedQueueKey = new Queue.Key(); Unique delayedCoordVar = new Unique(); int concurrency = Math.max(1, locator.sequence().rootSequence().concurrency()); if (html) { Unique delay = new Unique(); SequenceBuilder delaySequence = locator.scenario().sequence(delaySequenceName); delaySequence.concurrency(Math.max(1, concurrency)) .step(() -> { ReadAccess inputVar = sequenceScopedReadAccess(delayedCoordVar); ObjectAccess delayVar = sequenceScopedObjectAccess(delay); SerializableToLongFunction<Session> delayFunc = session -> TimeUnit.SECONDS .toNanos(((Redirect.Coords) inputVar.getObject(session)).delay); return new ScheduleDelayStep(delayVar, ScheduleDelayStep.Type.FROM_NOW, delayFunc); }) .step(() -> new AwaitDelayStep(sequenceScopedReadAccess(delay))) .stepBuilder(new StepBuilder.ActionAdapter(() -> new PushQueueAction( sequenceScopedReadAccess(delayedCoordVar), queueKey))) .step(session -> { session.getResource(delayedQueueKey).consumed(session); return true; }); Locator.push(null, delaySequence); delaySequence.prepareBuild(); Locator.pop(); } // The redirect sequence (and queue) needs to have twice the concurrency of the original sequence // because while executing one redirect it might activate a second redirect int redirectConcurrency = 2 * concurrency; LimitedPoolResource.Key<Redirect.Coords> poolKey = new LimitedPoolResource.Key<>(); { // Note: there's a lot of copy-paste between current handler because we need to use // different method variable for current sequence and new sequence since these have incompatible // indices - had we used the same var one sequence would overwrite other's var. Unique newTempCoordsVar = new Unique(true); HttpRequestStepBuilder step = (HttpRequestStepBuilder) locator.step(); HttpRequestStepBuilder.BodyGeneratorBuilder bodyBuilder = step.bodyBuilder(); HttpRequestStepBuilder httpRequest = new HttpRequestStepBuilder() .method(() -> new Redirect.GetMethod(sequenceScopedReadAccess(coordsVar))) .path(() -> new Location.GetPath(sequenceScopedReadAccess(coordsVar))) .authority(() -> new Location.GetAuthority(sequenceScopedReadAccess(coordsVar))) .headerAppenders(step.headerAppenders()) .body(bodyBuilder == null ? null : bodyBuilder.copy(null)) .sync(false) // we want to reuse the same sequence for subsequent requests .handler().followRedirect(FollowRedirect.NEVER).endHandler(); if (location) { httpRequest.handler() .status(new Redirect.StatusHandler.Builder() .poolKey(poolKey).concurrency(redirectConcurrency).coordsVar(newTempCoordsVar) .handlers(statusHandlers)) .header(new Redirect.LocationRecorder.Builder() .originalSequenceSupplier( () -> new Redirect.GetOriginalSequence(sequenceScopedReadAccess(coordsVar))) .concurrency(redirectConcurrency).inputVar(newTempCoordsVar).outputVar(coordsVar) .queueKey(queueKey).sequence(redirectSequenceName)); } if (!headerHandlers.isEmpty()) { Redirect.WrappingHeaderHandler.Builder wrappingHandler = new Redirect.WrappingHeaderHandler.Builder() .coordVar(coordsVar).handlers(headerHandlers); if (location) { httpRequest.handler().header(new ConditionalHeaderHandler.Builder() .condition().stringCondition().fromVar(newTempCoordsVar).isSet(false).end() .handler(wrappingHandler)); } else { httpRequest.handler().header(wrappingHandler); } } if (!bodyHandlers.isEmpty() || html) { Consumer<Processor.Builder> handlerConsumer; ConditionalProcessor.Builder conditionalBodyHandler; Redirect.WrappingProcessor.Builder wrappingProcessor = new Redirect.WrappingProcessor.Builder() .coordVar(coordsVar).processors(bodyHandlers); if (location) { if (!bodyHandlers.isEmpty() || html) { conditionalBodyHandler = new ConditionalProcessor.Builder() .condition().stringCondition().fromVar(newTempCoordsVar).isSet(false).end() .processor(wrappingProcessor); handlerConsumer = conditionalBodyHandler::processor; httpRequest.handler().body(conditionalBodyHandler); } else { handlerConsumer = null; } } else { assert html; httpRequest.handler().body(wrappingProcessor); handlerConsumer = httpRequest.handler()::body; } if (html) { handlerConsumer.accept(new HtmlHandler.Builder().handler(new MetaRefreshHandler.Builder() .processor(fragmented -> new RefreshHandler( queueKey, delayedQueueKey, poolKey, redirectConcurrency, objectAccess(coordsVar), objectAccess(delayedCoordVar), redirectSequenceName, delaySequenceName, objectAccess(newTempCoordsVar), new Redirect.GetOriginalSequence(sequenceScopedReadAccess(coordsVar)))))); } } if (!completionHandlers.isEmpty()) { httpRequest.handler().onCompletion(new ConditionalAction.Builder() .condition().stringCondition().fromVar(newTempCoordsVar).isSet(false).end() .action(new Redirect.WrappingAction.Builder().coordVar(coordsVar).actions(completionHandlers))); } httpRequest.handler() .onCompletion(() -> new Location.Complete<>(poolKey, queueKey, sequenceScopedObjectAccess(coordsVar))); SequenceBuilder redirectSequence = locator.scenario().sequence(redirectSequenceName) .concurrency(redirectConcurrency) .stepBuilder(httpRequest) .rootSequence(); Locator.push(null, redirectSequence); redirectSequence.prepareBuild(); Locator.pop(); } Unique tempCoordsVar = new Unique(locator.sequence().rootSequence().concurrency() > 0); if (location) { statusHandlers = Collections.singletonList( new Redirect.StatusHandler.Builder().poolKey(poolKey).concurrency(redirectConcurrency) .coordsVar(tempCoordsVar).handlers(statusHandlers)); List<HeaderHandler.Builder> headerHandlers = new ArrayList<>(); headerHandlers.add(new Redirect.LocationRecorder.Builder() .originalSequenceSupplier(() -> Session::currentSequence) .concurrency(redirectConcurrency).inputVar(tempCoordsVar).outputVar(coordsVar).queueKey(queueKey) .sequence(redirectSequenceName)); if (!this.headerHandlers.isEmpty()) { // Note: we are using stringCondition.isSet despite the variable is not a string - it doesn't matter for the purpose of this check headerHandlers.add(new ConditionalHeaderHandler.Builder() .condition().stringCondition().fromVar(tempCoordsVar).isSet(false).end() .handlers(this.headerHandlers)); } this.headerHandlers = headerHandlers; } if (!bodyHandlers.isEmpty() || html) { Consumer<Processor.Builder> handlerConsumer; ConditionalProcessor.Builder conditionalBodyHandler = null; if (location) { conditionalBodyHandler = new ConditionalProcessor.Builder() .condition().stringCondition().fromVar(tempCoordsVar).isSet(false).end() .processors(bodyHandlers); handlerConsumer = conditionalBodyHandler::processor; } else { handlerConsumer = bodyHandlers::add; } if (html) { handlerConsumer.accept(new HtmlHandler.Builder().handler(new MetaRefreshHandler.Builder() .processor(fragmented -> new RefreshHandler( queueKey, delayedQueueKey, poolKey, redirectConcurrency, objectAccess(coordsVar), objectAccess(delayedCoordVar), redirectSequenceName, delaySequenceName, objectAccess(tempCoordsVar), Session::currentSequence)))); } if (location) { bodyHandlers = Collections.singletonList(conditionalBodyHandler); } } if (!completionHandlers.isEmpty()) { completionHandlers = Collections.singletonList( new ConditionalAction.Builder() .condition().stringCondition().fromVar(tempCoordsVar).isSet(false).end() .actions(completionHandlers)); } } public HttpResponseHandlersImpl build() { return new HttpResponseHandlersImpl( toArray(statusHandlers, StatusHandler.Builder::build, StatusHandler[]::new), toArray(headerHandlers, HeaderHandler.Builder::build, HeaderHandler[]::new), toArray(bodyHandlers, b -> b.build(true), Processor[]::new), toArray(completionHandlers, Action.Builder::build, Action[]::new), toArray(rawBytesHandlers, RawBytesHandler.Builder::build, RawBytesHandler[]::new)); } private static <B, T> T[] toArray(List<B> list, Function<B, T> build, IntFunction<T[]> generator) { if (list.isEmpty()) { return null; } else { return list.stream().map(build).toArray(generator); } } } private static class StopOnInvalidAction implements Action { // prevents some weird serialization incompatibility private static final Action INSTANCE = new StopOnInvalidAction(); @Override public void run(Session session) { Request request = session.currentRequest(); if (!request.isValid()) { log.info("#{} Stopping session due to invalid response {} on connection {}", session.uniqueId(), request, request.connection()); session.stop(); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/steps/PrepareHttpRequestStep.java
http/src/main/java/io/hyperfoil/http/steps/PrepareHttpRequestStep.java
package io.hyperfoil.http.steps; import java.util.Arrays; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.core.metric.MetricSelector; import io.hyperfoil.core.steps.StatisticsStep; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.http.HttpRequestPool; import io.hyperfoil.http.HttpUtil; import io.hyperfoil.http.api.HttpConnectionPool; import io.hyperfoil.http.api.HttpDestinationTable; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.api.HttpRequest; public class PrepareHttpRequestStep extends StatisticsStep implements ResourceUtilizer { private static final Logger log = LogManager.getLogger(PrepareHttpRequestStep.class); final HttpRequestContext.Key contextKey; final SerializableFunction<Session, HttpMethod> method; final SerializableFunction<Session, String> endpoint; final SerializableFunction<Session, String> authority; final SerializableFunction<Session, String> pathGenerator; final MetricSelector metricSelector; final HttpResponseHandlersImpl handler; public PrepareHttpRequestStep(int stepId, HttpRequestContext.Key contextKey, SerializableFunction<Session, HttpMethod> method, SerializableFunction<Session, String> endpoint, SerializableFunction<Session, String> authority, SerializableFunction<Session, String> pathGenerator, MetricSelector metricSelector, HttpResponseHandlersImpl handler) { super(stepId); this.contextKey = contextKey; this.method = method; this.endpoint = endpoint; this.authority = authority; this.pathGenerator = pathGenerator; this.metricSelector = metricSelector; this.handler = handler; } @Override public boolean invoke(Session session) { SequenceInstance sequence = session.currentSequence(); HttpRequestContext context = session.getResource(contextKey); if (context.request == null) { context.request = HttpRequestPool.get(session).acquire(); if (context.request == null) { log.warn("#{} Request pool too small; increase it to prevent blocking.", session.uniqueId()); return false; } } HttpDestinationTable destinations = HttpDestinationTable.get(session); try { HttpRequest request = context.request; request.method = method.apply(session); String path = pathGenerator.apply(session); boolean isHttp = path.startsWith(HttpUtil.HTTP_PREFIX); boolean isUrl = isHttp || path.startsWith(HttpUtil.HTTPS_PREFIX); if (isUrl) { int pathIndex = path.indexOf('/', HttpUtil.prefixLength(isHttp)); if (pathIndex < 0) { request.path = "/"; } else { request.path = path.substring(pathIndex); } } else { request.path = path; } HttpConnectionPool connectionPool = getConnectionPool(session, destinations, path, isHttp, isUrl); if (connectionPool == null) { session.fail(new IllegalStateException("Connection pool must not be null.")); return false; } request.authority = connectionPool.clientPool().authority(); String metric = destinations.hasSingleDestination() ? metricSelector.apply(null, request.path) : metricSelector.apply(request.authority, request.path); Statistics statistics = session.statistics(id(), metric); request.start(connectionPool, handler, session.currentSequence(), statistics); connectionPool.acquire(false, context); } catch (Throwable t) { // If any error happens we still need to release the request // The request is either IDLE or RUNNING - we need to make it running, otherwise we could not release it if (!context.request.isRunning()) { context.request.start(sequence, null); } context.request.setCompleted(); context.request.release(); context.reset(); throw t; } return true; } private HttpConnectionPool getConnectionPool(Session session, HttpDestinationTable destinations, String path, boolean isHttp, boolean isUrl) { String endpoint = this.endpoint == null ? null : this.endpoint.apply(session); if (endpoint != null) { HttpConnectionPool connectionPool = destinations.getConnectionPoolByName(endpoint); if (connectionPool == null) { throw new IllegalStateException("There is no HTTP destination '" + endpoint + "'"); } return connectionPool; } String authority = this.authority == null ? null : this.authority.apply(session); if (authority == null && isUrl) { for (String hostPort : destinations.authorities()) { if (HttpUtil.authorityMatch(path, hostPort, isHttp)) { authority = hostPort; break; } } if (authority == null) { throw new IllegalStateException("Cannot access " + path + ": no destination configured"); } } HttpConnectionPool connectionPool = destinations.getConnectionPoolByAuthority(authority); if (connectionPool == null) { if (authority == null) { throw new IllegalStateException( "There is no default authority and it was not set neither explicitly nor through URL in path."); } else { throw new IllegalStateException("There is no connection pool with authority '" + authority + "', available pools are: " + Arrays.asList(destinations.authorities())); } } return connectionPool; } @Override public void reserve(Session session) { session.declareResource(contextKey, HttpRequestContext::new); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/parser/HttpParser.java
http/src/main/java/io/hyperfoil/http/parser/HttpParser.java
package io.hyperfoil.http.parser; import org.yaml.snakeyaml.events.ScalarEvent; import org.yaml.snakeyaml.events.SequenceStartEvent; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.core.parser.AbstractParser; import io.hyperfoil.core.parser.Context; import io.hyperfoil.core.parser.Parser; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.core.parser.PropertyParser; import io.hyperfoil.core.parser.ReflectionParser; import io.hyperfoil.http.config.ConnectionStrategy; import io.hyperfoil.http.config.HttpBuilder; import io.hyperfoil.http.config.HttpPluginBuilder; import io.hyperfoil.http.config.Protocol; public class HttpParser extends AbstractParser<BenchmarkBuilder, HttpBuilder> { private static final AddressParser ADDRESS_PARSER = new AddressParser(); public HttpParser() { register("name", new PropertyParser.String<>(HttpBuilder::name)); register("protocol", new PropertyParser.String<>((builder, scheme) -> builder.protocol(Protocol.fromScheme(scheme)))); register("host", new PropertyParser.String<>(HttpBuilder::host)); register("port", new PropertyParser.Int<>(HttpBuilder::port)); register("allowHttp1x", new PropertyParser.Boolean<>(HttpBuilder::allowHttp1x)); register("allowHttp2", new PropertyParser.Boolean<>(HttpBuilder::allowHttp2)); register("maxHttp2Streams", new PropertyParser.Int<>(HttpBuilder::maxHttp2Streams)); register("sharedConnections", new ConnectionPoolConfigParser()); register("pipeliningLimit", new PropertyParser.Int<>(HttpBuilder::pipeliningLimit)); register("directHttp2", new PropertyParser.Boolean<>(HttpBuilder::directHttp2)); register("requestTimeout", new PropertyParser.String<>(HttpBuilder::requestTimeout)); register("sslHandshakeTimeout", new PropertyParser.String<>(HttpBuilder::sslHandshakeTimeout)); register("addresses", HttpParser::parseAddresses); register("rawBytesHandlers", new PropertyParser.Boolean<>(HttpBuilder::rawBytesHandlers)); register("keyManager", new ReflectionParser<>(HttpBuilder::keyManager)); register("trustManager", new ReflectionParser<>(HttpBuilder::trustManager)); register("connectionStrategy", new PropertyParser.Enum<>(ConnectionStrategy.values(), HttpBuilder::connectionStrategy)); register("useHttpCache", new PropertyParser.Boolean<>(HttpBuilder::useHttpCache)); } @Override public void parse(Context ctx, BenchmarkBuilder target) throws ParserException { HttpPluginBuilder plugin = target.addPlugin(HttpPluginBuilder::new); if (ctx.peek() instanceof SequenceStartEvent) { ctx.parseList(plugin, (ctx1, builder) -> { HttpBuilder http = builder.decoupledHttp(); callSubBuilders(ctx1, http); builder.addHttp(http); }); } else { callSubBuilders(ctx, plugin.http()); } } private static void parseAddresses(Context ctx, HttpBuilder builder) throws ParserException { if (ctx.peek() instanceof ScalarEvent) { String value = ctx.expectEvent(ScalarEvent.class).getValue(); if (value != null && !value.isEmpty()) { builder.addAddress(value); } } else { ctx.parseList(builder, ADDRESS_PARSER); } } private static class AddressParser implements Parser<HttpBuilder> { @Override public void parse(Context ctx, HttpBuilder target) throws ParserException { ScalarEvent event = ctx.expectEvent(ScalarEvent.class); target.addAddress(event.getValue()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/http/src/main/java/io/hyperfoil/http/parser/ConnectionPoolConfigParser.java
http/src/main/java/io/hyperfoil/http/parser/ConnectionPoolConfigParser.java
package io.hyperfoil.http.parser; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.events.MappingStartEvent; import org.yaml.snakeyaml.events.ScalarEvent; import io.hyperfoil.core.parser.AbstractParser; import io.hyperfoil.core.parser.Context; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.core.parser.PropertyParser; import io.hyperfoil.http.config.ConnectionPoolConfig; import io.hyperfoil.http.config.HttpBuilder; public class ConnectionPoolConfigParser extends AbstractParser<HttpBuilder, ConnectionPoolConfig.Builder> { public ConnectionPoolConfigParser() { register("core", new PropertyParser.Int<>(ConnectionPoolConfig.Builder::core)); register("max", new PropertyParser.Int<>(ConnectionPoolConfig.Builder::max)); register("buffer", new PropertyParser.Int<>(ConnectionPoolConfig.Builder::buffer)); register("keepAliveTime", new PropertyParser.TimeMillis<>(ConnectionPoolConfig.Builder::keepAliveTime)); } @Override public void parse(Context ctx, HttpBuilder http) throws ParserException { Event event = ctx.peek(); if (event instanceof ScalarEvent) { String value = ((ScalarEvent) event).getValue(); try { http.sharedConnections(Integer.parseInt(value)); } catch (NumberFormatException e) { throw new ParserException(event, "Failed to parse as integer: " + value); } ctx.consumePeeked(event); } else if (event instanceof MappingStartEvent) { callSubBuilders(ctx, http.sharedConnections()); } else { throw ctx.unexpectedEvent(event); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
acmeair-webapp/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
package com.acmeair.config; import java.util.ArrayList; import java.util.Map; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import com.acmeair.service.BookingService; import com.acmeair.service.CustomerService; import com.acmeair.service.FlightService; import com.acmeair.service.ServiceLocator; @Path("/config") public class AcmeAirConfiguration { @Inject BeanManager beanManager; Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName()); private BookingService bs = ServiceLocator.instance().getService(BookingService.class); private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); public AcmeAirConfiguration() { super(); } @PostConstruct private void initialization() { if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/BeanManager"); } } if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/env/BeanManager "); } } } @GET @Path("/dataServices") @Produces("application/json") public ArrayList<ServiceData> getDataServiceInfo() { try { ArrayList<ServiceData> list = new ArrayList<ServiceData>(); Map<String, String> services = ServiceLocator.instance().getServices(); logger.fine("Get data service configuration info"); for (Map.Entry<String, String> entry : services.entrySet()){ ServiceData data = new ServiceData(); data.name = entry.getKey(); data.description = entry.getValue(); list.add(data); } return list; } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/activeDataService") @Produces("application/json") public Response getActiveDataServiceInfo() { try { logger.fine("Get active Data Service info"); return Response.ok(ServiceLocator.instance().getServiceType()).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok("Unknown").build(); } } @GET @Path("/runtime") @Produces("application/json") public ArrayList<ServiceData> getRuntimeInfo() { try { logger.fine("Getting Runtime info"); ArrayList<ServiceData> list = new ArrayList<ServiceData>(); ServiceData data = new ServiceData(); data.name = "Runtime"; data.description = "Java"; list.add(data); data = new ServiceData(); data.name = "Version"; data.description = System.getProperty("java.version"); list.add(data); data = new ServiceData(); data.name = "Vendor"; data.description = System.getProperty("java.vendor"); list.add(data); return list; } catch (Exception e) { e.printStackTrace(); return null; } } class ServiceData { public String name = ""; public String description = ""; } @GET @Path("/countBookings") @Produces("application/json") public Response countBookings() { try { Long count = bs.count(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countCustomers") @Produces("application/json") public Response countCustomer() { try { Long customerCount = customerService.count(); return Response.ok(customerCount).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countSessions") @Produces("application/json") public Response countCustomerSessions() { try { Long customerCount = customerService.countSessions(); return Response.ok(customerCount).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countFlights") @Produces("application/json") public Response countFlights() { try { Long count = flightService.countFlights(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countFlightSegments") @Produces("application/json") public Response countFlightSegments() { try { Long count = flightService.countFlightSegments(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countAirports") @Produces("application/json") public Response countAirports() { try { Long count = flightService.countAirports(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/config/LoaderREST.java
acmeair-webapp/src/main/java/com/acmeair/config/LoaderREST.java
package com.acmeair.config; import javax.inject.Inject; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import com.acmeair.loader.Loader; @Path("/loader") public class LoaderREST { // private static Logger logger = Logger.getLogger(LoaderREST.class.getName()); @Inject private Loader loader; @GET @Path("/query") @Produces("text/plain") public Response queryLoader() { String response = loader.queryLoader(); return Response.ok(response).build(); } @GET @Path("/load") @Produces("text/plain") public Response loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) { String response = loader.loadDB(numCustomers); return Response.ok(response).build(); } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java
acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import java.io.IOException; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.acmeair.entities.CustomerSession; import com.acmeair.service.CustomerService; import com.acmeair.service.ServiceLocator; import com.acmeair.service.TransactionService; public class RESTCookieSessionFilter implements Filter { static final String LOGIN_USER = "acmeair.login_user"; private static final String LOGIN_PATH = "/rest/api/login"; private static final String LOGOUT_PATH = "/rest/api/login/logout"; private static final String LOADDB_PATH = "/rest/api/loaddb"; private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); private TransactionService transactionService = ServiceLocator.instance().getService(TransactionService.class);; @Inject BeanManager beanManager; @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; String path = request.getContextPath() + request.getServletPath() + request.getPathInfo(); // The following code is to ensure that OG is always set on the thread try{ if (transactionService!=null) transactionService.prepareForTransaction(); }catch( Exception e) { e.printStackTrace(); } if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH)) { // if logging in, logging out, or loading the database, let the request flow chain.doFilter(req, resp); return; } Cookie cookies[] = request.getCookies(); Cookie sessionCookie = null; if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) { sessionCookie = c; } if (sessionCookie!=null) break; } String sessionId = ""; if (sessionCookie!=null) // We need both cookie to work sessionId= sessionCookie.getValue().trim(); // did this check as the logout currently sets the cookie value to "" instead of aging it out // see comment in LogingREST.java if (sessionId.equals("")) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Need the URLDecoder so that I can get @ not %40 CustomerSession cs = customerService.validateSession(sessionId); if (cs != null) { request.setAttribute(LOGIN_USER, cs.getCustomerid()); chain.doFilter(req, resp); return; } else { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } // if we got here, we didn't detect the session cookie, so we need to return 404 response.sendError(HttpServletResponse.SC_FORBIDDEN); } @Override public void init(FilterConfig config) throws ServletException { } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/CustomerREST.java
acmeair-webapp/src/main/java/com/acmeair/web/CustomerREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.*; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; import com.acmeair.service.*; import com.acmeair.web.dto.*; import javax.ws.rs.core.Context; @Path("/customer") public class CustomerREST { private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); @Context private HttpServletRequest request; private boolean validate(String customerid) { String loginUser = (String) request.getAttribute(RESTCookieSessionFilter.LOGIN_USER); return customerid.equals(loginUser); } @GET @Path("/byid/{custid}") @Produces("application/json") public Response getCustomer(@CookieParam("sessionid") String sessionid, @PathParam("custid") String customerid) { try { // make sure the user isn't trying to update a customer other than the one currently logged in if (!validate(customerid)) { return Response.status(Response.Status.FORBIDDEN).build(); } Customer customer = customerService.getCustomerByUsername(customerid); CustomerInfo customerDTO = new CustomerInfo(customer); return Response.ok(customerDTO).build(); } catch (Exception e) { e.printStackTrace(); return null; } } @POST @Path("/byid/{custid}") @Produces("application/json") public /* Customer */ Response putCustomer(@CookieParam("sessionid") String sessionid, CustomerInfo customer) { if (!validate(customer.getUsername())) { return Response.status(Response.Status.FORBIDDEN).build(); } Customer customerFromDB = customerService.getCustomerByUsernameAndPassword(customer.getUsername(), customer.getPassword()); if (customerFromDB == null) { // either the customer doesn't exist or the password is wrong return Response.status(Response.Status.FORBIDDEN).build(); } CustomerAddress addressFromDB = customerFromDB.getAddress(); addressFromDB.setStreetAddress1(customer.getAddress().getStreetAddress1()); if (customer.getAddress().getStreetAddress2() != null) { addressFromDB.setStreetAddress2(customer.getAddress().getStreetAddress2()); } addressFromDB.setCity(customer.getAddress().getCity()); addressFromDB.setStateProvince(customer.getAddress().getStateProvince()); addressFromDB.setCountry(customer.getAddress().getCountry()); addressFromDB.setPostalCode(customer.getAddress().getPostalCode()); customerFromDB.setPhoneNumber(customer.getPhoneNumber()); customerFromDB.setPhoneNumberType(Customer.PhoneType.valueOf(customer.getPhoneNumberType())); customerService.updateCustomer(customerFromDB); customerFromDB.setPassword(null); return Response.ok(customerFromDB).build(); } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/FlightsREST.java
acmeair-webapp/src/main/java/com/acmeair/web/FlightsREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import java.util.ArrayList; import java.util.List; import java.util.Date; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import com.acmeair.entities.Flight; import com.acmeair.service.FlightService; import com.acmeair.service.ServiceLocator; import com.acmeair.web.dto.TripFlightOptions; import com.acmeair.web.dto.TripLegInfo; @Path("/flights") public class FlightsREST { private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); // TODO: Consider a pure GET implementation of this service, but maybe not much value due to infrequent similar searches @POST @Path("/queryflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") public TripFlightOptions getTripFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("fromDate") Date fromDate, @FormParam("returnDate") Date returnDate, @FormParam("oneWay") boolean oneWay ) { TripFlightOptions options = new TripFlightOptions(); ArrayList<TripLegInfo> legs = new ArrayList<TripLegInfo>(); TripLegInfo toInfo = new TripLegInfo(); List<Flight> toFlights = flightService.getFlightByAirportsAndDepartureDate(fromAirport, toAirport, fromDate); toInfo.setFlightsOptions(toFlights); legs.add(toInfo); toInfo.setCurrentPage(0); toInfo.setHasMoreOptions(false); toInfo.setNumPages(1); toInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); if (!oneWay) { TripLegInfo retInfo = new TripLegInfo(); List<Flight> retFlights = flightService.getFlightByAirportsAndDepartureDate(toAirport, fromAirport, returnDate); retInfo.setFlightsOptions(retFlights); legs.add(retInfo); retInfo.setCurrentPage(0); retInfo.setHasMoreOptions(false); retInfo.setNumPages(1); retInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); options.setTripLegs(2); } else { options.setTripLegs(1); } options.setTripFlights(legs); return options; } @POST @Path("/browseflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") public TripFlightOptions browseFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("oneWay") boolean oneWay ) { TripFlightOptions options = new TripFlightOptions(); ArrayList<TripLegInfo> legs = new ArrayList<TripLegInfo>(); TripLegInfo toInfo = new TripLegInfo(); List<Flight> toFlights = flightService.getFlightByAirports(fromAirport, toAirport); toInfo.setFlightsOptions(toFlights); legs.add(toInfo); toInfo.setCurrentPage(0); toInfo.setHasMoreOptions(false); toInfo.setNumPages(1); toInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); if (!oneWay) { TripLegInfo retInfo = new TripLegInfo(); List<Flight> retFlights = flightService.getFlightByAirports(toAirport, fromAirport); retInfo.setFlightsOptions(retFlights); legs.add(retInfo); retInfo.setCurrentPage(0); retInfo.setHasMoreOptions(false); retInfo.setNumPages(1); retInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); options.setTripLegs(2); } else { options.setTripLegs(1); } options.setTripFlights(legs); return options; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/AcmeAirApp.java
acmeair-webapp/src/main/java/com/acmeair/web/AcmeAirApp.java
package com.acmeair.web; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.ApplicationPath; @ApplicationPath("/rest/api") public class AcmeAirApp extends Application { public Set<Class<?>> getClasses() { return new HashSet<Class<?>>(Arrays.asList(BookingsREST.class, CustomerREST.class, FlightsREST.class, LoginREST.class)); } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/BookingsREST.java
acmeair-webapp/src/main/java/com/acmeair/web/BookingsREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import java.util.*; import javax.ws.rs.*; import javax.ws.rs.core.*; import javax.ws.rs.core.Response.Status; import com.acmeair.entities.Booking; import com.acmeair.service.BookingService; import com.acmeair.service.ServiceLocator; import com.acmeair.web.dto.BookingInfo; import com.acmeair.web.dto.BookingReceiptInfo; @Path("/bookings") public class BookingsREST { private BookingService bs = ServiceLocator.instance().getService(BookingService.class); @POST @Consumes({"application/x-www-form-urlencoded"}) @Path("/bookflights") @Produces("application/json") public /*BookingInfo*/ Response bookFlights( @FormParam("userid") String userid, @FormParam("toFlightId") String toFlightId, @FormParam("toFlightSegId") String toFlightSegId, @FormParam("retFlightId") String retFlightId, @FormParam("retFlightSegId") String retFlightSegId, @FormParam("oneWayFlight") boolean oneWay) { try { String bookingIdTo = bs.bookFlight(userid, toFlightSegId, toFlightId); String bookingIdReturn = null; if (!oneWay) { bookingIdReturn = bs.bookFlight(userid, retFlightSegId, retFlightId); } // YL. BookingInfo will only contains the booking generated keys as customer info is always available from the session BookingReceiptInfo bi; if (!oneWay) bi = new BookingReceiptInfo(bookingIdTo, bookingIdReturn, oneWay); else bi = new BookingReceiptInfo(bookingIdTo, null, oneWay); return Response.ok(bi).build(); } catch (Exception e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } @GET @Path("/bybookingnumber/{userid}/{number}") @Produces("application/json") public BookingInfo getBookingByNumber( @PathParam("number") String number, @PathParam("userid") String userid) { try { Booking b = bs.getBooking(userid, number); BookingInfo bi = null; if(b != null){ bi = new BookingInfo(b); } return bi; } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/byuser/{user}") @Produces("application/json") public List<BookingInfo> getBookingsByUser(@PathParam("user") String user) { try { List<Booking> list = bs.getBookingsByUser(user); List<BookingInfo> newList = new ArrayList<BookingInfo>(); for(Booking b : list){ newList.add(new BookingInfo(b)); } return newList; } catch (Exception e) { e.printStackTrace(); return null; } } @POST @Consumes({"application/x-www-form-urlencoded"}) @Path("/cancelbooking") @Produces("application/json") public Response cancelBookingsByNumber( @FormParam("number") String number, @FormParam("userid") String userid) { try { bs.cancelBooking(userid, number); return Response.ok("booking " + number + " deleted.").build(); } catch (Exception e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/AppConfig.java
acmeair-webapp/src/main/java/com/acmeair/web/AppConfig.java
package com.acmeair.web; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import javax.ws.rs.ApplicationPath; import com.acmeair.config.AcmeAirConfiguration; import com.acmeair.config.LoaderREST; @ApplicationPath("/rest/info") public class AppConfig extends Application { public Set<Class<?>> getClasses() { return new HashSet<Class<?>>(Arrays.asList(LoaderREST.class, AcmeAirConfiguration.class)); } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/LoginREST.java
acmeair-webapp/src/main/java/com/acmeair/web/LoginREST.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web; import javax.ws.rs.*; import javax.ws.rs.core.*; import com.acmeair.entities.CustomerSession; import com.acmeair.service.*; @Path("/login") public class LoginREST { public static String SESSIONID_COOKIE_NAME = "sessionid"; private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); @POST @Consumes({"application/x-www-form-urlencoded"}) @Produces("text/plain") public Response login(@FormParam("login") String login, @FormParam("password") String password) { try { boolean validCustomer = customerService.validateCustomer(login, password); if (!validCustomer) { return Response.status(Response.Status.FORBIDDEN).build(); } CustomerSession session = customerService.createSession(login); // TODO: Need to fix the security issues here - they are pretty gross likely NewCookie sessCookie = new NewCookie(SESSIONID_COOKIE_NAME, session.getId()); // TODO: The mobile client app requires JSON in the response. // To support the mobile client app, choose one of the following designs: // - Change this method to return JSON, and change the web app javascript to handle a JSON response. // example: return Response.ok("{\"status\":\"logged-in\"}").cookie(sessCookie).build(); // - Or create another method which is identical to this one, except returns JSON response. // Have the web app use the original method, and the mobile client app use the new one. return Response.ok("logged in").cookie(sessCookie).build(); } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/logout") @Produces("text/plain") public Response logout(@QueryParam("login") String login, @CookieParam("sessionid") String sessionid) { try { customerService.invalidateSession(sessionid); // The following call will trigger query against all partitions, disable for now // customerService.invalidateAllUserSessions(login); // TODO: Want to do this with setMaxAge to zero, but to do that I need to have the same path/domain as cookie // created in login. Unfortunately, until we have a elastic ip and domain name its hard to do that for "localhost". // doing this will set the cookie to the empty string, but the browser will still send the cookie to future requests // and the server will need to detect the value is invalid vs actually forcing the browser to time out the cookie and // not send it to begin with NewCookie sessCookie = new NewCookie(SESSIONID_COOKIE_NAME, ""); return Response.ok("logged out").cookie(sessCookie).build(); } catch (Exception e) { e.printStackTrace(); return null; } } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/AddressInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/AddressInfo.java
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.CustomerAddress; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="CustomerAddress") public class AddressInfo implements Serializable{ private static final long serialVersionUID = 1L; private String streetAddress1; private String streetAddress2; private String city; private String stateProvince; private String country; private String postalCode; public AddressInfo() { } public AddressInfo(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode) { super(); this.streetAddress1 = streetAddress1; this.streetAddress2 = streetAddress2; this.city = city; this.stateProvince = stateProvince; this.country = country; this.postalCode = postalCode; } public AddressInfo(CustomerAddress address) { super(); this.streetAddress1 = address.getStreetAddress1(); this.streetAddress2 = address.getStreetAddress2(); this.city = address.getCity(); this.stateProvince = address.getStateProvince(); this.country = address.getCountry(); this.postalCode = address.getPostalCode(); } public String getStreetAddress1() { return streetAddress1; } public void setStreetAddress1(String streetAddress1) { this.streetAddress1 = streetAddress1; } public String getStreetAddress2() { return streetAddress2; } public void setStreetAddress2(String streetAddress2) { this.streetAddress2 = streetAddress2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStateProvince() { return stateProvince; } public void setStateProvince(String stateProvince) { this.stateProvince = stateProvince; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "CustomerAddress [streetAddress1=" + streetAddress1 + ", streetAddress2=" + streetAddress2 + ", city=" + city + ", stateProvince=" + stateProvince + ", country=" + country + ", postalCode=" + postalCode + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AddressInfo other = (AddressInfo) obj; if (city == null) { if (other.city != null) return false; } else if (!city.equals(other.city)) return false; if (country == null) { if (other.country != null) return false; } else if (!country.equals(other.country)) return false; if (postalCode == null) { if (other.postalCode != null) return false; } else if (!postalCode.equals(other.postalCode)) return false; if (stateProvince == null) { if (other.stateProvince != null) return false; } else if (!stateProvince.equals(other.stateProvince)) return false; if (streetAddress1 == null) { if (other.streetAddress1 != null) return false; } else if (!streetAddress1.equals(other.streetAddress1)) return false; if (streetAddress2 == null) { if (other.streetAddress2 != null) return false; } else if (!streetAddress2.equals(other.streetAddress2)) return false; return true; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightSegmentInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightSegmentInfo.java
package com.acmeair.web.dto; import com.acmeair.entities.FlightSegment; public class FlightSegmentInfo { private String _id; private String originPort; private String destPort; private int miles; public FlightSegmentInfo() { } public FlightSegmentInfo(FlightSegment flightSegment) { this._id = flightSegment.getFlightName(); this.originPort = flightSegment.getOriginPort(); this.destPort = flightSegment.getDestPort(); this.miles = flightSegment.getMiles(); } public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getOriginPort() { return originPort; } public void setOriginPort(String originPort) { this.originPort = originPort; } public String getDestPort() { return destPort; } public void setDestPort(String destPort) { this.destPort = destPort; } public int getMiles() { return miles; } public void setMiles(int miles) { this.miles = miles; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingPKInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingPKInfo.java
package com.acmeair.web.dto; import javax.xml.bind.annotation.XmlElement; public class BookingPKInfo { @XmlElement(name="id") private String id; @XmlElement(name="customerId") private String customerId; public BookingPKInfo() { } public BookingPKInfo(String customerId,String id) { this.id = id; this.customerId = customerId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/TripFlightOptions.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/TripFlightOptions.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * TripFlightOptions is the main return type when searching for flights. * * The object will return as many tripLeg's worth of Flight options as requested. So if the user * requests a one way flight they will get a List that has only one TripLegInfo and it will have * a list of flights that are options for that flight. If a user selects round trip, they will * have a List of two TripLegInfo objects. If a user does a multi-leg flight then the list will * be whatever size they requested. For now, only supporting one way and return flights so the * list should always be of size one or two. * * * @author aspyker * */ @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement public class TripFlightOptions { private int tripLegs; private List<TripLegInfo> tripFlights; public int getTripLegs() { return tripLegs; } public void setTripLegs(int tripLegs) { this.tripLegs = tripLegs; } public List<TripLegInfo> getTripFlights() { return tripFlights; } public void setTripFlights(List<TripLegInfo> tripFlights) { this.tripFlights = tripFlights; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingInfo.java
package com.acmeair.web.dto; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.Booking; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="Booking") public class BookingInfo { @XmlElement(name="bookingId") private String bookingId; @XmlElement(name="flightId") private String flightId; @XmlElement(name="customerId") private String customerId; @XmlElement(name="dateOfBooking") private Date dateOfBooking; @XmlElement(name="pkey") private BookingPKInfo pkey; public BookingInfo() { } public BookingInfo(Booking booking){ this.bookingId = booking.getBookingId(); this.flightId = booking.getFlightId(); this.customerId = booking.getCustomerId(); this.dateOfBooking = booking.getDateOfBooking(); this.pkey = new BookingPKInfo(this.customerId, this.bookingId); } public String getBookingId() { return bookingId; } public void setBookingId(String bookingId) { this.bookingId = bookingId; } public String getFlightId() { return flightId; } public void setFlightId(String flightId) { this.flightId = flightId; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public Date getDateOfBooking() { return dateOfBooking; } public void setDateOfBooking(Date dateOfBooking) { this.dateOfBooking = dateOfBooking; } public BookingPKInfo getPkey(){ return pkey; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightInfo.java
package com.acmeair.web.dto; import java.math.BigDecimal; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.Flight; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="Flight") public class FlightInfo { @XmlElement(name="_id") private String _id; private String flightSegmentId; private Date scheduledDepartureTime; private Date scheduledArrivalTime; private BigDecimal firstClassBaseCost; private BigDecimal economyClassBaseCost; private int numFirstClassSeats; private int numEconomyClassSeats; private String airplaneTypeId; private FlightSegmentInfo flightSegment; @XmlElement(name="pkey") private FlightPKInfo pkey; public FlightInfo(){ } public FlightInfo(Flight flight){ this._id = flight.getFlightId(); this.flightSegmentId = flight.getFlightSegmentId(); this.scheduledDepartureTime = flight.getScheduledDepartureTime(); this.scheduledArrivalTime = flight.getScheduledArrivalTime(); this.firstClassBaseCost = flight.getFirstClassBaseCost(); this.economyClassBaseCost = flight.getEconomyClassBaseCost(); this.numFirstClassSeats = flight.getNumFirstClassSeats(); this.numEconomyClassSeats = flight.getNumEconomyClassSeats(); this.airplaneTypeId = flight.getAirplaneTypeId(); if(flight.getFlightSegment() != null){ this.flightSegment = new FlightSegmentInfo(flight.getFlightSegment()); } else { this.flightSegment = null; } this.pkey = new FlightPKInfo(this.flightSegmentId, this._id); } public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getFlightSegmentId() { return flightSegmentId; } public void setFlightSegmentId(String flightSegmentId) { this.flightSegmentId = flightSegmentId; } public Date getScheduledDepartureTime() { return scheduledDepartureTime; } public void setScheduledDepartureTime(Date scheduledDepartureTime) { this.scheduledDepartureTime = scheduledDepartureTime; } public Date getScheduledArrivalTime() { return scheduledArrivalTime; } public void setScheduledArrivalTime(Date scheduledArrivalTime) { this.scheduledArrivalTime = scheduledArrivalTime; } public BigDecimal getFirstClassBaseCost() { return firstClassBaseCost; } public void setFirstClassBaseCost(BigDecimal firstClassBaseCost) { this.firstClassBaseCost = firstClassBaseCost; } public BigDecimal getEconomyClassBaseCost() { return economyClassBaseCost; } public void setEconomyClassBaseCost(BigDecimal economyClassBaseCost) { this.economyClassBaseCost = economyClassBaseCost; } public int getNumFirstClassSeats() { return numFirstClassSeats; } public void setNumFirstClassSeats(int numFirstClassSeats) { this.numFirstClassSeats = numFirstClassSeats; } public int getNumEconomyClassSeats() { return numEconomyClassSeats; } public void setNumEconomyClassSeats(int numEconomyClassSeats) { this.numEconomyClassSeats = numEconomyClassSeats; } public String getAirplaneTypeId() { return airplaneTypeId; } public void setAirplaneTypeId(String airplaneTypeId) { this.airplaneTypeId = airplaneTypeId; } public FlightSegmentInfo getFlightSegment() { return flightSegment; } public void setFlightSegment(FlightSegmentInfo flightSegment) { this.flightSegment = flightSegment; } public FlightPKInfo getPkey(){ return pkey; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/CustomerInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/CustomerInfo.java
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.acmeair.entities.Customer; @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement(name="Customer") public class CustomerInfo implements Serializable{ private static final long serialVersionUID = 1L; @XmlElement(name="_id") private String _id; @XmlElement(name="password") private String password; @XmlElement(name="status") private String status; @XmlElement(name="total_miles") private int total_miles; @XmlElement(name="miles_ytd") private int miles_ytd; @XmlElement(name="address") private AddressInfo address; @XmlElement(name="phoneNumber") private String phoneNumber; @XmlElement(name="phoneNumberType") private String phoneNumberType; public CustomerInfo() { } public CustomerInfo(String username, String password, String status, int total_miles, int miles_ytd, AddressInfo address, String phoneNumber, String phoneNumberType) { this._id = username; this.password = password; this.status = status; this.total_miles = total_miles; this.miles_ytd = miles_ytd; this.address = address; this.phoneNumber = phoneNumber; this.phoneNumberType = phoneNumberType; } public CustomerInfo(Customer c) { this._id = c.getUsername(); this.password = c.getPassword(); this.status = c.getStatus().toString(); this.total_miles = c.getTotal_miles(); this.miles_ytd = c.getMiles_ytd(); this.address = new AddressInfo(c.getAddress()); this.phoneNumber = c.getPhoneNumber(); this.phoneNumberType = c.getPhoneNumberType().toString(); } public String getUsername() { return _id; } public void setUsername(String username) { this._id = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getTotal_miles() { return total_miles; } public void setTotal_miles(int total_miles) { this.total_miles = total_miles; } public int getMiles_ytd() { return miles_ytd; } public void setMiles_ytd(int miles_ytd) { this.miles_ytd = miles_ytd; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPhoneNumberType() { return phoneNumberType; } public void setPhoneNumberType(String phoneNumberType) { this.phoneNumberType = phoneNumberType; } public AddressInfo getAddress() { return address; } public void setAddress(AddressInfo address) { this.address = address; } @Override public String toString() { return "Customer [id=" + _id + ", password=" + password + ", status=" + status + ", total_miles=" + total_miles + ", miles_ytd=" + miles_ytd + ", address=" + address + ", phoneNumber=" + phoneNumber + ", phoneNumberType=" + phoneNumberType + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerInfo other = (CustomerInfo) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (_id == null) { if (other._id != null) return false; } else if (!_id.equals(other._id)) return false; if (miles_ytd != other.miles_ytd) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (phoneNumber == null) { if (other.phoneNumber != null) return false; } else if (!phoneNumber.equals(other.phoneNumber)) return false; if (phoneNumberType != other.phoneNumberType) return false; if (status != other.status) return false; if (total_miles != other.total_miles) return false; return true; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightPKInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/FlightPKInfo.java
package com.acmeair.web.dto; public class FlightPKInfo { private String id; private String flightSegmentId; FlightPKInfo(){} FlightPKInfo(String flightSegmentId,String id){ this.id = id; this.flightSegmentId = flightSegmentId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFlightSegmentId() { return flightSegmentId; } public void setFlightSegmentId(String flightSegmentId) { this.flightSegmentId = flightSegmentId; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; public class BookingReceiptInfo { private String departBookingId; private String returnBookingId; private boolean oneWay; public BookingReceiptInfo(String departBookingId, String returnBookingId, boolean oneWay) { this.departBookingId = departBookingId; this.returnBookingId = returnBookingId; this.oneWay = oneWay; } public BookingReceiptInfo() { } public String getDepartBookingId() { return departBookingId; } public void setDepartBookingId(String departBookingId) { this.departBookingId = departBookingId; } public String getReturnBookingId() { return returnBookingId; } public void setReturnBookingId(String returnBookingId) { this.returnBookingId = returnBookingId; } public boolean isOneWay() { return oneWay; } public void setOneWay(boolean oneWay) { this.oneWay = oneWay; } @Override public String toString() { return "BookingInfo [departBookingId=" + departBookingId + ", returnBookingId=" + returnBookingId + ", oneWay=" + oneWay + "]"; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-webapp/src/main/java/com/acmeair/web/dto/TripLegInfo.java
acmeair-webapp/src/main/java/com/acmeair/web/dto/TripLegInfo.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.web.dto; import java.util.ArrayList; import java.util.List; import com.acmeair.entities.Flight; /** * The TripLegInfo object contains a list of flights that satisfy the query request for any one * leg of a trip. Also, it supports paging so a query can't return too many requests. * @author aspyker * */ public class TripLegInfo { public static int DEFAULT_PAGE_SIZE = 10; private boolean hasMoreOptions; private int numPages; private int pageSize; private int currentPage; private List<FlightInfo> flightsOptions; public boolean isHasMoreOptions() { return hasMoreOptions; } public void setHasMoreOptions(boolean hasMoreOptions) { this.hasMoreOptions = hasMoreOptions; } public int getNumPages() { return numPages; } public void setNumPages(int numPages) { this.numPages = numPages; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public List<FlightInfo> getFlightsOptions() { return flightsOptions; } public void setFlightsOptions(List<Flight> flightsOptions) { List<FlightInfo> flightInfoOptions = new ArrayList<FlightInfo>(); for(Flight info : flightsOptions){ flightInfoOptions.add(new FlightInfo(info)); } this.flightsOptions = flightInfoOptions; } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/KeyGenerator.java
acmeair-services/src/main/java/com/acmeair/service/KeyGenerator.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; public class KeyGenerator { public Object generate() { return java.util.UUID.randomUUID().toString(); } }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/DataService.java
acmeair-services/src/main/java/com/acmeair/service/DataService.java
package com.acmeair.service; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface DataService { String name() default "none"; String description() default "none"; }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/TransactionService.java
acmeair-services/src/main/java/com/acmeair/service/TransactionService.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; public interface TransactionService { void prepareForTransaction() throws Exception; }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/FlightService.java
acmeair-services/src/main/java/com/acmeair/service/FlightService.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.acmeair.entities.Flight; import com.acmeair.entities.FlightSegment; import com.acmeair.entities.AirportCodeMapping; public abstract class FlightService { protected Logger logger = Logger.getLogger(FlightService.class.getName()); //TODO:need to find a way to invalidate these maps protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache = new ConcurrentHashMap<String,FlightSegment>(); protected static ConcurrentHashMap<String, List<Flight>> flightSegmentAndDataToFlightCache = new ConcurrentHashMap<String,List<Flight>>(); protected static ConcurrentHashMap<String, Flight> flightPKtoFlightCache = new ConcurrentHashMap<String, Flight>(); public Flight getFlightByFlightId(String flightId, String flightSegment) { try { Flight flight = flightPKtoFlightCache.get(flightId); if (flight == null) { flight = getFlight(flightId, flightSegment); if (flightId != null && flight != null) { flightPKtoFlightCache.putIfAbsent(flightId, flight); } } return flight; } catch (Exception e) { throw new RuntimeException(e); } } protected abstract Flight getFlight(String flightId, String flightSegment); public List<Flight> getFlightByAirportsAndDepartureDate(String fromAirport, String toAirport, Date deptDate) { if(logger.isLoggable(Level.FINE)) logger.fine("Search for flights from "+ fromAirport + " to " + toAirport + " on " + deptDate.toString()); String originPortAndDestPortQueryString= fromAirport+toAirport; FlightSegment segment = originAndDestPortToSegmentCache.get(originPortAndDestPortQueryString); if (segment == null) { segment = getFlightSegment(fromAirport, toAirport); originAndDestPortToSegmentCache.putIfAbsent(originPortAndDestPortQueryString, segment); } // cache flights that not available (checks against sentinel value above indirectly) if (segment.getFlightName() == null) { return new ArrayList<Flight>(); } String segId = segment.getFlightName(); String flightSegmentIdAndScheduledDepartureTimeQueryString = segId + deptDate.toString(); List<Flight> flights = flightSegmentAndDataToFlightCache.get(flightSegmentIdAndScheduledDepartureTimeQueryString); if (flights == null) { flights = getFlightBySegment(segment, deptDate); flightSegmentAndDataToFlightCache.putIfAbsent(flightSegmentIdAndScheduledDepartureTimeQueryString, flights); } if(logger.isLoggable(Level.FINEST)) logger.finest("Returning "+ flights); return flights; } // NOTE: This is not cached public List<Flight> getFlightByAirports(String fromAirport, String toAirport) { FlightSegment segment = getFlightSegment(fromAirport, toAirport); if (segment == null) { return new ArrayList<Flight>(); } return getFlightBySegment(segment, null); } protected abstract FlightSegment getFlightSegment(String fromAirport, String toAirport); protected abstract List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate); public abstract void storeAirportMapping(AirportCodeMapping mapping); public abstract AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName); public abstract Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId); public abstract void storeFlightSegment(FlightSegment flightSeg); public abstract void storeFlightSegment(String flightName, String origPort, String destPort, int miles); public abstract Long countFlightSegments(); public abstract Long countFlights(); public abstract Long countAirports(); }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/BookingService.java
acmeair-services/src/main/java/com/acmeair/service/BookingService.java
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.util.List; import com.acmeair.entities.Booking; public interface BookingService { //String bookFlight(String customerId, FlightPK flightId); // String bookFlight(String customerId, String flightId); String bookFlight(String customerId, String flightSegmentId, String FlightId); Booking getBooking(String user, String id); List<Booking> getBookingsByUser(String user); void cancelBooking(String user, String id); Long count(); }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false
acmeair/acmeair
https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/CustomerService.java
acmeair-services/src/main/java/com/acmeair/service/CustomerService.java
/******************************************************************************* * Copyright (c) 2013-2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.acmeair.service; import java.util.Calendar; import java.util.Date; import javax.inject.Inject; import com.acmeair.entities.Customer; import com.acmeair.entities.CustomerAddress; import com.acmeair.entities.Customer.MemberShipStatus; import com.acmeair.entities.Customer.PhoneType; import com.acmeair.entities.CustomerSession; public abstract class CustomerService { protected static final int DAYS_TO_ALLOW_SESSION = 1; @Inject protected KeyGenerator keyGenerator; public abstract Customer createCustomer( String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddress address); public abstract CustomerAddress createAddress (String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode); public abstract Customer updateCustomer(Customer customer); protected abstract Customer getCustomer(String username); public Customer getCustomerByUsername(String username) { Customer c = getCustomer(username); if (c != null) { c.setPassword(null); } return c; } public boolean validateCustomer(String username, String password) { boolean validatedCustomer = false; Customer customerToValidate = getCustomer(username); if (customerToValidate != null) { validatedCustomer = password.equals(customerToValidate.getPassword()); } return validatedCustomer; } public Customer getCustomerByUsernameAndPassword(String username, String password) { Customer c = getCustomer(username); if (!c.getPassword().equals(password)) { return null; } // Should we also set the password to null? return c; } public CustomerSession validateSession(String sessionid) { CustomerSession cSession = getSession(sessionid); if (cSession == null) { return null; } Date now = new Date(); if (cSession.getTimeoutTime().before(now)) { removeSession(cSession); return null; } return cSession; } protected abstract CustomerSession getSession(String sessionid); protected abstract void removeSession(CustomerSession session); public CustomerSession createSession(String customerId) { String sessionId = keyGenerator.generate().toString(); Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION); Date expiration = c.getTime(); return createSession(sessionId, customerId, now, expiration); } protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration); public abstract void invalidateSession(String sessionid); public abstract Long count(); public abstract Long countSessions(); }
java
Apache-2.0
f16122729873ef0449ea276dfb2d2a1d45bebb40
2026-01-05T02:38:07.986560Z
false