Java Code Examples for io.undertow.server.HttpServerExchange#putAttachment()
The following examples show how to use
io.undertow.server.HttpServerExchange#putAttachment() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocaleHandler.java From mangooio with Apache License 2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { Locale locale = Locale.forLanguageTag(this.config.getApplicationLanguage()); Attachment attachment = exchange.getAttachment(RequestUtils.getAttachmentKey()); Cookie i18nCookie = exchange.getRequestCookies().get(this.config.getI18nCookieName()); if (i18nCookie == null) { final HeaderValues headerValues = exchange.getRequestHeaders().get(Header.ACCEPT_LANGUAGE.toHttpString()); if (headerValues != null) { String acceptLanguage = headerValues.element(); if (StringUtils.isNotBlank(acceptLanguage)) { locale = LocaleUtils.getLocaleFromString(acceptLanguage); } } } else { locale = LocaleUtils.getLocaleFromString(i18nCookie.getValue()); } attachment.getMessages().reload(locale); attachment.withLocale(locale); exchange.putAttachment(RequestUtils.getAttachmentKey(), attachment); nextHandler(exchange); }
Example 2
Source File: PathTemplateHandler.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { PathTemplateMatcher.PathMatchResult<HttpHandler> match = pathTemplateMatcher.match(exchange.getRelativePath()); if (match == null) { next.handleRequest(exchange); return; } exchange.putAttachment(PATH_TEMPLATE_MATCH, new PathTemplateMatch(match.getMatchedTemplate(), match.getParameters())); exchange.putAttachment(io.undertow.util.PathTemplateMatch.ATTACHMENT_KEY, new io.undertow.util.PathTemplateMatch(match.getMatchedTemplate(), match.getParameters())); if (rewriteQueryParameters) { for (Map.Entry<String, String> entry : match.getParameters().entrySet()) { exchange.addQueryParam(entry.getKey(), entry.getValue()); } } match.getValue().handleRequest(exchange); }
Example 3
Source File: RegularExpressionPredicate.java From quarkus-http with Apache License 2.0 | 6 votes |
@Override public boolean resolve(final HttpServerExchange value) { String input = matchAttribute.readAttribute(value); if(input == null) { return false; } Matcher matcher = pattern.matcher(input); final boolean matches; if (requireFullMatch) { matches = matcher.matches(); } else { matches = matcher.find(); } if (matches) { Map<String, Object> context = value.getAttachment(PREDICATE_CONTEXT); if(context == null) { value.putAttachment(PREDICATE_CONTEXT, context = new TreeMap<>()); } int count = matcher.groupCount(); for (int i = 0; i <= count; ++i) { context.put(Integer.toString(i), matcher.group(i)); } } return matches; }
Example 4
Source File: HttpContinue.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Sends a continue response using blocking IO * * @param exchange The exchange */ public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException { if (!exchange.isResponseChannelAvailable()) { throw UndertowMessages.MESSAGES.cannotSendContinueResponse(); } if(exchange.getAttachment(ALREADY_SENT) != null) { return; } HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange); exchange.putAttachment(ALREADY_SENT, true); newExchange.setStatusCode(StatusCodes.CONTINUE); newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0); newExchange.startBlocking(); newExchange.getOutputStream().close(); newExchange.getInputStream().close(); }
Example 5
Source File: PathTemplatePredicate.java From quarkus-http with Apache License 2.0 | 6 votes |
@Override public boolean resolve(final HttpServerExchange exchange) { final Map<String, String> params = new HashMap<>(); String path = attribute.readAttribute(exchange); if(path == null) { return false; } boolean result = this.value.matches(path, params); if (result) { Map<String, Object> context = exchange.getAttachment(PREDICATE_CONTEXT); if(context == null) { exchange.putAttachment(PREDICATE_CONTEXT, context = new TreeMap<>()); } context.putAll(params); } return result; }
Example 6
Source File: SimpleUndertowLoadBalancer.java From keycloak with Apache License 2.0 | 5 votes |
@Override protected Host selectHost(HttpServerExchange exchange) { Host host = super.selectHost(exchange); if (host != null) { log.debugf("Selected host: %s, host available: %b", host.getUri().toString(), host.isAvailable()); } else { log.warn("No host available"); } exchange.putAttachment(SELECTED_HOST, host); return host; }
Example 7
Source File: RewriteCorrectingHandlerWrappers.java From quarkus with Apache License 2.0 | 5 votes |
@Override public HttpHandler wrap(final HttpHandler handler) { return new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.putAttachment(OLD_RELATIVE_PATH, exchange.getRelativePath()); handler.handleRequest(exchange); } }; }
Example 8
Source File: ResponseTimeAttribute.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public String readAttribute(HttpServerExchange exchange) { long requestStartTime = exchange.getRequestStartTime(); if(requestStartTime == -1) { return null; } final long nanos; Long first = exchange.getAttachment(FIRST_RESPONSE_TIME_NANOS); if(first != null) { nanos = first; } else { nanos = System.nanoTime() - requestStartTime; if(exchange.isResponseComplete()) { //save the response time so it is consistent exchange.putAttachment(FIRST_RESPONSE_TIME_NANOS, nanos); } } if(timeUnit == TimeUnit.SECONDS) { StringBuilder buf = new StringBuilder(); long milis = TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS); buf.append(Long.toString(milis / 1000)); buf.append('.'); int remains = (int) (milis % 1000); buf.append(Long.toString(remains / 100)); remains = remains % 100; buf.append(Long.toString(remains / 10)); buf.append(Long.toString(remains % 10)); return buf.toString(); } else { return String.valueOf(timeUnit.convert(nanos, TimeUnit.NANOSECONDS)); } }
Example 9
Source File: InboundCookiesHandler.java From mangooio with Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { Attachment attachment = exchange.getAttachment(RequestUtils.getAttachmentKey()); attachment.setSession(getSessionCookie(exchange)); attachment.setAuthentication(getAuthenticationCookie(exchange)); attachment.setFlash(getFlashCookie(exchange)); attachment.setForm(this.form); exchange.putAttachment(RequestUtils.getAttachmentKey(), attachment); nextHandler(exchange); }
Example 10
Source File: FormHandler.java From mangooio with Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { final Attachment attachment = exchange.getAttachment(RequestUtils.getAttachmentKey()); if (attachment.getForm() == null) { attachment.setForm(getForm(exchange)); } exchange.putAttachment(RequestUtils.getAttachmentKey(), attachment); nextHandler(exchange); }
Example 11
Source File: CachedAuthenticatedSessionHandler.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { SecurityContext securityContext = exchange.getSecurityContext(); securityContext.registerNotificationReceiver(NOTIFICATION_RECEIVER); HttpSession session = servletContext.getSession(exchange, false); // If there was no existing HttpSession then there could not be a cached AuthenticatedSession so don't bother setting // the AuthenticatedSessionManager. if (session != null) { exchange.putAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY, SESSION_MANAGER); SavedRequest.tryRestoreRequest(exchange, session); //not sure if this is where it belongs } next.handleRequest(exchange); }
Example 12
Source File: DigestAuthenticationMechanism.java From lams with GNU General Public License v2.0 | 5 votes |
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) { List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION); if (authHeaders != null) { for (String current : authHeaders) { if (current.startsWith(DIGEST_PREFIX)) { String digestChallenge = current.substring(PREFIX_LENGTH); try { DigestContext context = new DigestContext(); Map<DigestAuthorizationToken, String> parsedHeader = parseHeader(digestChallenge); context.setMethod(exchange.getRequestMethod().toString()); context.setParsedHeader(parsedHeader); // Some form of Digest authentication is going to occur so get the DigestContext set on the exchange. exchange.putAttachment(DigestContext.ATTACHMENT_KEY, context); UndertowLogger.SECURITY_LOGGER.debugf("Found digest header %s in %s", current, exchange); return handleDigestHeader(exchange, securityContext); } catch (Exception e) { e.printStackTrace(); } } // By this point we had a header we should have been able to verify but for some reason // it was not correctly structured. return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } } // No suitable header has been found in this request, return AuthenticationMechanismOutcome.NOT_ATTEMPTED; }
Example 13
Source File: ClientStatisticsMarker.java From galeb with Apache License 2.0 | 5 votes |
void stamp(final Host host, final HttpServerExchange exchange) { int openConnections = 0; if (sendOpenconnCounter) { openConnections = host.getOpenConnection(); exchange.putAttachment(TARGET_CONN, openConnections); } if (logger.isDebugEnabled()) { final String uri = host.getUri().toString(); logger.debug("{\"client_statistic\": { \"uri\": \"" + uri + "\", \"open_connections\": " + openConnections + "} }"); } }
Example 14
Source File: EncodingHandler.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { AllowedContentEncodings encodings = contentEncodingRepository.getContentEncodings(exchange); if (encodings == null || !exchange.isResponseChannelAvailable()) { next.handleRequest(exchange); } else if (encodings.isNoEncodingsAllowed()) { noEncodingHandler.handleRequest(exchange); } else { exchange.addResponseWrapper(encodings); exchange.putAttachment(AllowedContentEncodings.ATTACHMENT_KEY, encodings); next.handleRequest(exchange); } }
Example 15
Source File: MappingTestServer.java From divolte-collector with Apache License 2.0 | 4 votes |
private void handleEvent(final HttpServerExchange exchange) throws Exception { try (final ChannelInputStream cis = new ChannelInputStream(exchange.getRequestChannel())) { final JsonNode payload = EVENT_PARAMETERS_READER.readTree(cis); final String generatedPageViewId = DivolteIdentifier.generate().value; final DivolteEvent.BrowserEventData browserEventData = new DivolteEvent.BrowserEventData( get(payload, "page_view_id", String.class).orElse(generatedPageViewId), get(payload, "location", String.class), get(payload, "referer", String.class), get(payload, "viewport_pixel_width", Integer.class), get(payload, "viewport_pixel_height", Integer.class), get(payload, "screen_pixel_width", Integer.class), get(payload, "screen_pixel_height", Integer.class), get(payload, "device_pixel_ratio", Integer.class)); final Instant now = Instant.now(); final DivolteEvent divolteEvent = DivolteEvent.createBrowserEvent( exchange, get(payload, "corrupt", Boolean.class).orElse(false), get(payload, "party_id", String.class).flatMap(DivolteIdentifier::tryParse).orElse(DivolteIdentifier.generate()), get(payload, "session_id", String.class).flatMap(DivolteIdentifier::tryParse).orElse(DivolteIdentifier.generate()), get(payload, "event_id", String.class).orElse(generatedPageViewId + "0"), now, now, get(payload, "new_party_id", Boolean.class).orElse(false), get(payload, "first_in_session", Boolean.class).orElse(false), get(payload, "event_type", String.class), () -> get(payload, "parameters", JsonNode.class), browserEventData); get(payload, "remote_host", String.class) .ifPresent(ip -> { try { final InetAddress address = InetAddress.getByName(ip); // We have no way of knowing the port exchange.setSourceAddress(new InetSocketAddress(address, 0)); } catch (final UnknownHostException e) { log.warn("Could not parse remote host: " + ip, e); } }); exchange.putAttachment(DUPLICATE_EVENT_KEY, get(payload, "duplicate", Boolean.class).orElse(false)); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseChannel().write(ByteBuffer.wrap(mapper.newRecordFromExchange(divolteEvent).toString().getBytes(StandardCharsets.UTF_8))); exchange.endExchange(); } }
Example 16
Source File: InMemorySessionManager.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public Session createSession(final HttpServerExchange serverExchange, final SessionConfig config) { if (maxSize > 0) { if(expireOldestUnusedSessionOnMax) { while (sessions.size() >= maxSize && !evictionQueue.isEmpty()) { String key = evictionQueue.poll(); UndertowLogger.REQUEST_LOGGER.debugf("Removing session %s as max size has been hit", key); SessionImpl toRemove = sessions.get(key); if (toRemove != null) { toRemove.invalidate(null, SessionListener.SessionDestroyedReason.TIMEOUT); //todo: better reason } } } else if(sessions.size() >= maxSize) { if(statisticsEnabled) { rejectedSessionCount.incrementAndGet(); } throw UndertowMessages.MESSAGES.tooManySessions(maxSize); } } if (config == null) { throw UndertowMessages.MESSAGES.couldNotFindSessionCookieConfig(); } String sessionID = config.findSessionId(serverExchange); int count = 0; while (sessionID == null) { sessionID = sessionIdGenerator.createSessionId(); if(sessions.containsKey(sessionID)) { sessionID = null; } if(count++ == 100) { //this should never happen //but we guard against pathalogical session id generators to prevent an infinite loop throw UndertowMessages.MESSAGES.couldNotGenerateUniqueSessionId(); } } Object evictionToken; if (evictionQueue != null) { evictionToken = evictionQueue.offerLastAndReturnToken(sessionID); } else { evictionToken = null; } final SessionImpl session = new SessionImpl(this, sessionID, config, serverExchange.getIoThread(), serverExchange.getConnection().getWorker(), evictionToken, defaultSessionTimeout); UndertowLogger.SESSION_LOGGER.debugf("Created session with id %s for exchange %s", sessionID, serverExchange); sessions.put(sessionID, session); config.setSessionId(serverExchange, session.getId()); session.bumpTimeout(); sessionListeners.sessionCreated(session, serverExchange); serverExchange.putAttachment(NEW_SESSION, session); if(statisticsEnabled) { createdSessionCount.incrementAndGet(); int highest; int sessionSize; do { highest = highestSessionCount.get(); sessionSize = sessions.size(); if(sessionSize <= highest) { break; } } while (!highestSessionCount.compareAndSet(highest, sessionSize)); } return session; }
Example 17
Source File: MarkSecureHandler.java From quarkus-http with Apache License 2.0 | 4 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.putAttachment(HttpServerExchange.SECURE_REQUEST, Boolean.TRUE); next.handleRequest(exchange); }
Example 18
Source File: SecureExchangeAttribute.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public void writeAttribute(HttpServerExchange exchange, String newValue) throws ReadOnlyAttributeException { exchange.putAttachment(HttpServerExchange.SECURE_REQUEST, Boolean.parseBoolean(newValue)); }
Example 19
Source File: AbstractSamlAuthMech.java From keycloak with Apache License 2.0 | 4 votes |
/** * Call this inside your authenticate method. */ public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) { UndertowHttpFacade facade = createFacade(exchange); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); if (!deployment.isConfigured()) { return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } SamlSessionStore sessionStore = getTokenStore(exchange, facade, deployment, securityContext); SamlAuthenticator authenticator = null; if (exchange.getRequestPath().endsWith("/saml")) { authenticator = new UndertowSamlEndpoint(facade, deploymentContext.resolveDeployment(facade), sessionStore); } else { authenticator = new UndertowSamlAuthenticator(securityContext, facade, deploymentContext.resolveDeployment(facade), sessionStore); } AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { registerNotifications(securityContext); return AuthenticationMechanismOutcome.AUTHENTICATED; } if (outcome == AuthOutcome.NOT_AUTHENTICATED) { // we are in passive mode and user is not authenticated, let app server to try another auth mechanism // See KEYCLOAK-2107, AbstractSamlAuthenticationHandler return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } if (outcome == AuthOutcome.LOGGED_OUT) { securityContext.logout(); if (deployment.getLogoutPage() != null) { redirectLogout(deployment, exchange); } return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, challenge); if (authenticator instanceof UndertowSamlEndpoint) { exchange.getSecurityContext().setAuthenticationRequired(); } } if (outcome == AuthOutcome.FAILED) { return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } return AuthenticationMechanismOutcome.NOT_ATTEMPTED; }
Example 20
Source File: HttpContinue.java From lams with GNU General Public License v2.0 | 2 votes |
/** * Marks a continue response as already having been sent. In general this should only be used * by low level handlers than need fine grained control over the continue response. * * @param exchange The exchange */ public static void markContinueResponseSent(HttpServerExchange exchange) { exchange.putAttachment(ALREADY_SENT, true); }