下面列出了javax.servlet.http.HttpUpgradeHandler#io.undertow.server.HttpServerExchange 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void handleRequest(HttpServerExchange exchange) {
JsonObject body = parseJsonObject(exchange);
_MatrixID mxid = MatrixID.asAcceptable(GsonUtil.getStringOrThrow(body, "mxid"));
String token = GsonUtil.getStringOrThrow(body, "token");
String privKey = GsonUtil.getStringOrThrow(body, "private_key");
IThreePidInviteReply reply = invMgr.getInvite(token, privKey);
_MatrixID sender = reply.getInvite().getSender();
JsonObject res = new JsonObject();
res.addProperty("token", token);
res.addProperty("sender", sender.getId());
res.addProperty("mxid", mxid.getId());
res.add("signatures", signMgr.signMessageGson(cfg.getServer().getName(), MatrixJson.encodeCanonical(res)));
log.info("Signed data for invite using token {}", token);
respondJson(exchange, res);
}
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());
LikePredicate likePredicate = new LikePredicate("userId", userId);
PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new UserComparator(), pageSize);
pagingPredicate.setPage(page);
Collection<User> values = users.values(pagingPredicate);
for (User value : values) {
value.setPassword(null);
}
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
processAudit(exchange);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
List<Map<String, Object>> body = (List)exchange.getAttachment(BodyHandler.REQUEST_BODY);
String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
if(logger.isDebugEnabled()) logger.debug("post serviceEndpoints for serviceId " + serviceId);
// ensure that the serviceId exists
IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
if(services.get(serviceId) == null) {
setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
processAudit(exchange);
return;
}
IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
List<ServiceEndpoint> list = new ArrayList<>();
for(Map<String, Object> m: body) {
list.add(Config.getInstance().getMapper().convertValue(m, ServiceEndpoint.class));
}
serviceEndpoints.set(serviceId, list);
processAudit(exchange);
}
public static Map<String, ?> getHeaderParameters(final HttpServerExchange exchange, final boolean deserializedValueOnly){
Map<String, Object> deserializedHeaderParamters = exchange.getAttachment(DESERIALIZED_HEADER_PARAMETERS);
if (!deserializedValueOnly) {
HeaderMap headers = exchange.getRequestHeaders();
if (null==headers) {
return Collections.emptyMap();
}
Map<String, HeaderValues> headerMap = new HashMap<>();
for (HttpString headerName: headers.getHeaderNames()) {
headerMap.put(headerName.toString(), headers.get(headerName));
}
return mergeMaps(deserializedHeaderParamters, headerMap);
}
return nonNullMap(deserializedHeaderParamters);
}
public static String changeSessionId(HttpServerExchange exchange, boolean create) {
final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
ServletContextImpl currentServletContext = sc.getCurrentServletContext();
HttpSessionImpl session = currentServletContext.getSession(exchange, create);
if (session == null) {
return null;
}
Session underlyingSession;
if(System.getSecurityManager() == null) {
underlyingSession = session.getSession();
} else {
underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
}
return underlyingSession.changeSessionId(exchange, currentServletContext.getSessionConfig());
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final String hostHeader = exchange.getRequestHeader(HttpHeaderNames.HOST);
if (hostHeader != null) {
String host;
if (hostHeader.contains(":")) { //header can be in host:port format
host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
} else {
host = hostHeader;
}
//most hosts will be lowercase, so we do the host
HttpHandler handler = hosts.get(host);
if (handler != null) {
handler.handleRequest(exchange);
return;
}
//do a cache insensitive match
handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
if (handler != null) {
handler.handleRequest(exchange);
return;
}
}
defaultHandler.handleRequest(exchange);
}
@Override
public void failed(final HttpServerExchange exchange) {
final long time = System.currentTimeMillis();
if (tries++ < maxRetryAttempts) {
if (timeout > 0 && time > timeout) {
cancel(exchange);
} else {
target = proxyClient.findTarget(exchange);
if (target != null) {
final long remaining = timeout > 0 ? timeout - time : -1;
proxyClient.getConnection(target, exchange, this, remaining, TimeUnit.MILLISECONDS);
} else {
couldNotResolveBackend(exchange); // The context was registered when we started, so return 503
}
}
} else {
couldNotResolveBackend(exchange);
}
}
@Override
public boolean handleDefaultResponse(final HttpServerExchange exchange) {
if (!exchange.isResponseChannelAvailable()) {
return false;
}
Set<Integer> codes = responseCodes;
if (codes == null ? exchange.getStatusCode() >= StatusCodes.BAD_REQUEST : codes.contains(Integer.valueOf(exchange.getStatusCode()))) {
final String errorPage = "<html><head><title>Error</title></head><body>" + exchange.getStatusCode() + " - " + StatusCodes.getReason(exchange.getStatusCode()) + "</body></html>";
exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + errorPage.length());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
Sender sender = exchange.getResponseSender();
sender.send(errorPage);
return true;
}
return false;
}
/**
* undertow consider path parts following ';' as path parameters and tries to parse them too.
* the below code simulates the parsing results in light-4j handler chains.
*/
@Test
public void test_matrix_primitive() {
Schema schema = new PojoSchema();
schema.setType("string");
Parameter parameter = new PoJoParameter(PARAM_NAME,
ParameterType.PATH.name().toLowerCase(),
PathParameterStyle.MATRIX.name().toLowerCase(),
true,
schema);
HttpServerExchange exchange = new HttpServerExchange(null);
exchange.addPathParam(PARAM_NAME, "5");
exchange.addPathParam(PARAM_NAME, "");
checkString(exchange, parameter, "5");
}
private MultiPartUploadHandler(final HttpServerExchange exchange, final String boundary, final long maxIndividualFileSize, final String defaultEncoding) {
this.exchange = exchange;
this.maxIndividualFileSize = maxIndividualFileSize;
this.defaultEncoding = defaultEncoding;
this.data = new FormData(exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_PARAMETERS, 1000));
String charset = defaultEncoding;
String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if (contentType != null) {
String value = Headers.extractQuotedValueFromHeader(contentType, "charset");
if (value != null) {
charset = value;
}
}
this.parser = MultipartParser.beginParse(exchange.getConnection().getByteBufferPool(), this, boundary.getBytes(StandardCharsets.US_ASCII), charset);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
Deque<String> clientNameDeque = exchange.getQueryParameters().get("clientName");
String clientName = clientNameDeque == null? "%" : clientNameDeque.getFirst() + "%";
int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());
LikePredicate likePredicate = new LikePredicate("clientName", clientName);
PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ClientComparator(), pageSize);
pagingPredicate.setPage(page);
Collection<Client> values = clients.values(pagingPredicate);
List results = new ArrayList();
for (Client value : values) {
Client c = Client.copyClient(value);
c.setClientSecret(null);
results.add(c);
}
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(results));
processAudit(exchange);
}
/**
* Test of defaultOrigin method, of class CorsUtil.
*/
@Test
public void testDefaultOrigin() {
HeaderMap headerMap = new HeaderMap();
headerMap.add(HOST, "localhost:80");
HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
exchange.setRequestScheme("http");
assertThat(CorsUtil.defaultOrigin(exchange), is("http://localhost"));
headerMap.clear();
headerMap.add(HOST, "www.example.com:8080");
assertThat(CorsUtil.defaultOrigin(exchange), is("http://www.example.com:8080"));
headerMap.clear();
headerMap.add(HOST, "www.example.com:443");
exchange.setRequestScheme("https");
assertThat(CorsUtil.defaultOrigin(exchange), is("https://www.example.com"));
headerMap.clear();
exchange.setRequestScheme("http");
headerMap.add(HOST, "[::1]:80");
assertThat(CorsUtil.defaultOrigin(exchange), is("http://[::1]"));
}
static DivolteEvent createBrowserEvent(
final HttpServerExchange originatingExchange,
final boolean corruptEvent,
final DivolteIdentifier partyCookie,
final DivolteIdentifier sessionCookie,
final String eventId,
final Instant requestStartTime,
final Instant clientUtcOffset,
final boolean newPartyId,
final boolean firstInSession,
final Optional<String> eventType,
final Supplier<Optional<JsonNode>> eventParametersProducer,
final BrowserEventData browserEvent) {
return new DivolteEvent(
originatingExchange,
corruptEvent,
partyCookie,
sessionCookie,
eventId,
BrowserSource.EVENT_SOURCE_NAME,
requestStartTime,
clientUtcOffset,
newPartyId,
firstInSession,
eventType,
eventParametersProducer,
Optional.of(browserEvent),
Optional.empty()
);
}
@NotNull
@Override
public JsonWrapper handleWithUserInGame(User user, Game game, Parameters params, HttpServerExchange exchange) {
JsonWrapper obj = new JsonWrapper();
obj.add(Consts.GameInfoData.INFO, game.getInfoJson(user, true));
obj.add(Consts.GamePlayerInfo.INFO, game.getAllPlayersInfoJson());
return obj;
}
public UndertowRequest(HttpServerExchange exchange, AppConfig config) {
super(config);
E.NPE(exchange);
hse = exchange;
headerOverwrite = config.allowHeaderOverwrite();
keywordMatching = config.paramBindingKeywordMatching();
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
Failsafe.with(circuitBreaker)
.withFallback(() -> failureHandler.handleRequest(exchange))
// We need to call get here instead of execute so we can return the
// mutated exchange to run checks on it
.get(() -> {
delegate.handleRequest(exchange);
return exchange;
});
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
Server.headers()
.entrySet()
.stream()
.filter(entry -> StringUtils.isNotBlank(entry.getValue()))
.forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
exchange.getResponseHeaders().put(Header.CONTENT_TYPE.toHttpString(), Default.CONTENT_TYPE.toString());
exchange.setStatusCode(StatusCodes.NOT_FOUND);
exchange.getResponseSender().send(Template.DEFAULT.notFound());
}
@Override
public void sessionDestroyed(Session session, HttpServerExchange exchange, SessionDestroyedReason reason) {
String ssoId = (String) session.getAttribute(SSO_SESSION_ATTRIBUTE);
if (ssoId != null) {
if(log.isTraceEnabled()) {
log.tracef("Removing SSO ID %s from destroyed session %s.", ssoId, session.getId());
}
List<Session> sessionsToRemove = new LinkedList<>();
try (SingleSignOn sso = singleSignOnManager.findSingleSignOn(ssoId)) {
if (sso != null) {
sso.remove(session);
if (reason == SessionDestroyedReason.INVALIDATED) {
for (Session associatedSession : sso) {
sso.remove(associatedSession);
sessionsToRemove.add(associatedSession);
}
}
// If there are no more associated sessions, remove the SSO altogether
if (!sso.iterator().hasNext()) {
singleSignOnManager.removeSingleSignOn(sso);
}
}
}
// Any consequential session invalidations will trigger this listener recursively,
// so make sure we don't attempt to invalidate session until after the sso is removed.
for (Session sessionToRemove : sessionsToRemove) {
sessionToRemove.invalidate(null);
}
}
}
@GET
@Path("exchange/plaintext")
@Produces((MediaType.TEXT_PLAIN))
@ApiOperation(value = "Plaintext endpoint" )
public void exchangePlaintext(HttpServerExchange exchange)
{
response("Hello, World!").textPlain().send(exchange);
}
@Override
public boolean resolve(final HttpServerExchange value) {
String location = this.location.readAttribute(value);
ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if(src == null) {
return false;
}
ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
if(manager == null) {
return false;
}
try {
Resource resource = manager.getResource(location);
if(resource == null) {
return false;
}
if(resource.isDirectory()) {
return false;
}
if(requireContent){
return resource.getContentLength() != null && resource.getContentLength() > 0;
} else {
return true;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean resolve(final HttpServerExchange value) {
for (final Predicate predicate : predicates) {
if (predicate.resolve(value)) {
return true;
}
}
return false;
}
public void logMessage(String pattern, HttpServerExchange exchange) {
JDBCLogAttribute jdbcLogAttribute = new JDBCLogAttribute();
if (pattern.equals("combined")) {
jdbcLogAttribute.pattern = pattern;
}
jdbcLogAttribute.remoteHost = ((InetSocketAddress) exchange.getSourceAddress()).getAddress().getHostAddress();
SecurityContext sc = exchange.getSecurityContext();
if (sc == null || !sc.isAuthenticated()) {
jdbcLogAttribute.user = null;
} else {
jdbcLogAttribute.user = sc.getAuthenticatedAccount().getPrincipal().getName();
}
jdbcLogAttribute.query = exchange.getQueryString();
jdbcLogAttribute.bytes = exchange.getResponseContentLength();
if (jdbcLogAttribute.bytes < 0) {
jdbcLogAttribute.bytes = 0;
}
jdbcLogAttribute.status = exchange.getStatusCode();
if (jdbcLogAttribute.pattern.equals("combined")) {
jdbcLogAttribute.virtualHost = exchange.getRequestHeader(HttpHeaderNames.HOST);
jdbcLogAttribute.method = exchange.getRequestMethod();
jdbcLogAttribute.referer = exchange.getRequestHeader(HttpHeaderNames.REFERER);
jdbcLogAttribute.userAgent = exchange.getRequestHeader(HttpHeaderNames.USER_AGENT);
}
this.pendingMessages.add(jdbcLogAttribute);
int state = stateUpdater.get(this);
if (state == 0) {
if (stateUpdater.compareAndSet(this, 0, 1)) {
this.executor = exchange.getWorker();
this.executor.execute(this);
}
}
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
if (!maybeApiPath.isPresent()) {
setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
return;
}
final NormalisedPath openApiPathString = maybeApiPath.get();
final Path path = OpenApiHelper.openApi3.getPath(openApiPathString.original());
final String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
final Operation operation = path.getOperation(httpMethod);
if (operation == null) {
setExchangeStatus(exchange, STATUS_METHOD_NOT_ALLOWED);
return;
}
// This handler can identify the openApiOperation and endpoint only. Other info will be added by JwtVerifyHandler.
final OpenApiOperation openApiOperation = new OpenApiOperation(openApiPathString, path, httpMethod, operation);
try {
ParameterDeserializer.deserialize(exchange, openApiOperation);
}catch (Throwable t) {// do not crash the handler
logger.error(t.getMessage(), t);
}
String endpoint = openApiPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
Map<String, Object> auditInfo = new HashMap<>();
auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
auditInfo.put(Constants.OPENAPI_OPERATION_STRING, openApiOperation);
exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);
Handler.next(exchange, next);
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
String qs = exchange.getQueryString();
if(qs.isEmpty() || !includeQuestionMark) {
return qs;
}
return '?' + qs;
}
public static void robots(HttpServerExchange exchange) {
String host = Exchange.urls().host(exchange).toString();
List<String> sitemaps = StubbornJavaSitemapGenerator.getSitemap().getIndexNames();
Response response = Response.fromExchange(exchange)
.with("sitemaps", sitemaps)
.with("host", host);
Exchange.body().sendText(exchange, Templating.instance().renderTemplate("templates/src/pages/robots.txt", response));
}
@GET
@Path("/json")
@ApiOperation(value = "Json serialization endpoint", httpMethod = "GET" )
public void json(HttpServerExchange exchange)
{
exchange.getResponseHeaders().put(CONTENT_TYPE, "application/json");
ByteArrayOutputStream os = new ByteArrayOutputStream(128);
MessageEncoder.encodeRaw( new Message("Hello, World!"), os);
exchange.getResponseSender().send( ByteBuffer.wrap(os.toByteArray()) );
}
@Override
protected boolean confidentialityRequired(HttpServerExchange exchange) {
TransportGuaranteeType transportGuarantee = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getTransportGuarenteeType();
// TODO - We may be able to add more flexibility here especially with authentication mechanisms such as Digest for
// INTEGRAL - for now just use SSL.
return (TransportGuaranteeType.CONFIDENTIAL == transportGuarantee || TransportGuaranteeType.INTEGRAL == transportGuarantee);
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
Object ret) {
if (isExceptionHandler(objInst)) {
HttpServerExchange exchange = (HttpServerExchange) allArguments[0];
if (Config.Plugin.Light4J.TRACE_HANDLER_CHAIN && !exchange.isInIoThread()) {
ContextManager.stopSpan();
}
} else if (Config.Plugin.Light4J.TRACE_HANDLER_CHAIN && (isMiddlewareHandler(objInst) || isBusinessHandler(objInst))) {
ContextManager.stopSpan();
}
return ret;
}
@Test
public void blockingParser() throws Exception {
final BlockingHandler blocking = new BlockingHandler();
blocking.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final FormParserFactory parserFactory = FormParserFactory.builder().build();
final FormDataParser parser = parserFactory.createParser(exchange);
try {
FormData data = parser.parseBlocking();
Iterator<String> it = data.iterator();
while (it.hasNext()) {
String fd = it.next();
for (FormData.FormValue val : data.get(fd)) {
exchange.addResponseHeader("res", fd + ":" + val.getValue());
}
}
} catch (IOException e) {
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
}
}
});
DefaultServer.setRootHandler(blocking);
testCase();
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if(HttpContinue.requiresContinueResponse(exchange)) {
if(accept.resolve(exchange)) {
exchange.send1ContinueIfRequired();
next.handleRequest(exchange);
} else {
HttpContinue.rejectExchange(exchange);
}
} else {
next.handleRequest(exchange);
}
}