Java Code Examples for io.undertow.server.HttpServerExchange#getAttachment()

The following examples show how to use io.undertow.server.HttpServerExchange#getAttachment() . 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: ServletSessionAttribute.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (context != null) {
        ServletRequest req = context.getServletRequest();
        if (req instanceof HttpServletRequest) {
            HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                Object result = session.getAttribute(attributeName);
                if (result != null) {
                    return result.toString();
                }
            }
        }
    }
    return null;
}
 
Example 2
Source File: FilterHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest request = servletRequestContext.getServletRequest();
    ServletResponse response = servletRequestContext.getServletResponse();
    DispatcherType dispatcher = servletRequestContext.getDispatcherType();
    Boolean supported = asyncSupported.get(dispatcher);
    if(supported != null && ! supported) {
        servletRequestContext.setAsyncSupported(false);
    }

    final List<ManagedFilter> filters = this.filters.get(dispatcher);
    if(filters == null) {
        next.handleRequest(exchange);
    } else {
        final FilterChainImpl filterChain = new FilterChainImpl(exchange, filters, next, allowNonStandardWrappers);
        filterChain.doFilter(request, response);
    }
}
 
Example 3
Source File: ServletInitialHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (System.getSecurityManager() == null) {
        dispatchRequest(exchange, servletRequestContext, servletRequestContext.getOriginalServletPathMatch().getServletChain(), DispatcherType.REQUEST);
    } else {
        //sometimes thread pools inherit some random
        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                dispatchRequest(exchange, servletRequestContext, servletRequestContext.getOriginalServletPathMatch().getServletChain(), DispatcherType.REQUEST);
                return null;
            }
        });
    }
}
 
Example 4
Source File: AuthenticationHandler.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Attachment attachment = exchange.getAttachment(RequestUtils.getAttachmentKey());
    
    if (attachment.hasAuthentication()) {
        Authentication authentication = attachment.getAuthentication();
        
        if (!authentication.isValid() || ( authentication.isValid() && authentication.isTwoFactor() )) {
            String redirect = this.config.getString(Key.AUTHENTICATION_REDIRECT.toString());
            if (StringUtils.isNotBlank(redirect)) {
                endRequest(exchange, redirect);
            } else {
                endRequest(exchange);
            }
        } else {
            nextHandler(exchange);
        }
    } else {
        nextHandler(exchange); 
    }
}
 
Example 5
Source File: SavedRequest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange, final byte[] buffer, int length) {
    int maxSize = exchange.getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE);
    if (maxSize > 0) {
        if (length > maxSize) {
            UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
            return;//failed to save the request, we just return
        }
        //TODO: we should really be used pooled buffers
        //TODO: we should probably limit the number of saved requests at any given time
        HttpHeaders headers = new DefaultHttpHeaders();
        for (String entry : exchange.getRequestHeaderNames()) {
            if (entry.equals(HttpHeaderNames.CONTENT_LENGTH) ||
                    entry.equals(HttpHeaderNames.TRANSFER_ENCODING) ||
                    entry.equals(HttpHeaderNames.CONNECTION)) {
                continue;
            }
            headers.set(entry, exchange.getRequestHeaders(entry));
        }
        SavedRequest request = new SavedRequest(buffer, length, exchange.getRequestMethod(), exchange.getRelativePath(), headers);
        final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = session.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        underlyingSession.setAttribute(SESSION_KEY, request);
    }
}
 
Example 6
Source File: CachedAuthenticatedSessionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void clearSession(HttpServerExchange exchange) {
    SessionManager sessionManager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if (sessionManager == null || sessionConfig == null) {
        return;
    }
    Session httpSession = sessionManager.getSession(exchange, sessionConfig);
    if (httpSession != null) {
        httpSession.removeAttribute(ATTRIBUTE_NAME);
    }
}
 
Example 7
Source File: ServletSessionAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (context != null) {
        ServletRequest req = context.getServletRequest();
        if (req instanceof HttpServletRequest) {
            HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                session.setAttribute(attributeName, newValue);
            }
        }
    }
}
 
Example 8
Source File: ServletContextAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (context != null) {
        context.getCurrentServletContext().setAttribute(attributeName, newValue);
    }
}
 
Example 9
Source File: ServletRequestLocaleAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (context != null) {
        ServletRequest req = context.getServletRequest();
        return req.getLocale().toString();
    }
    return null;
}
 
Example 10
Source File: DigestAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ChallengeResult sendChallenge(final HttpServerExchange exchange, final SecurityContext securityContext) {
    DigestContext context = exchange.getAttachment(DigestContext.ATTACHMENT_KEY);
    boolean stale = context == null ? false : context.isStale();

    StringBuilder rb = new StringBuilder(DIGEST_PREFIX);
    rb.append(Headers.REALM.toString()).append("=\"").append(realmName).append("\",");
    rb.append(Headers.DOMAIN.toString()).append("=\"").append(domain).append("\",");
    // based on security constraints.
    rb.append(Headers.NONCE.toString()).append("=\"").append(nonceManager.nextNonce(null, exchange)).append("\",");
    // Not currently using OPAQUE as it offers no integrity, used for session data leaves it vulnerable to
    // session fixation type issues as well.
    rb.append(Headers.OPAQUE.toString()).append("=\"00000000000000000000000000000000\"");
    if (stale) {
        rb.append(",stale=true");
    }
    if (supportedAlgorithms.size() > 0) {
        // This header will need to be repeated once for each algorithm.
        rb.append(",").append(Headers.ALGORITHM.toString()).append("=%s");
    }
    if (qopString != null) {
        rb.append(",").append(Headers.QOP.toString()).append("=\"").append(qopString).append("\"");
    }

    String theChallenge = rb.toString();
    HeaderMap responseHeader = exchange.getResponseHeaders();
    if (supportedAlgorithms.isEmpty()) {
        responseHeader.add(WWW_AUTHENTICATE, theChallenge);
    } else {
        for (DigestAlgorithm current : supportedAlgorithms) {
            responseHeader.add(WWW_AUTHENTICATE, String.format(theChallenge, current.getToken()));
        }
    }

    return new ChallengeResult(true, UNAUTHORIZED);
}
 
Example 11
Source File: CachedAuthenticatedSessionMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    AuthenticatedSessionManager sessionManager = exchange.getAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY);
    if (sessionManager != null) {
        return runCached(exchange, securityContext, sessionManager);
    } else {
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
}
 
Example 12
Source File: ServletSingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Session getSession(HttpServerExchange exchange) {
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    final HttpSessionImpl session = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
    if(System.getSecurityManager() == null) {
        return session.getSession();
    } else {
        return AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }
}
 
Example 13
Source File: ServletSessionAttribute.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (context != null) {
        ServletRequest req = context.getServletRequest();
        if (req instanceof HttpServletRequest) {
            HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                session.setAttribute(attributeName, newValue);
            }
        }
    }
}
 
Example 14
Source File: InMemorySessionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void requestDone(final HttpServerExchange serverExchange) {
    Long existing = serverExchange.getAttachment(FIRST_REQUEST_ACCESS);
    if(existing != null) {
        lastAccessed = existing;
    }
}
 
Example 15
Source File: LearningPushHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
protected Session getSession(HttpServerExchange exchange) {
    SessionConfig sc = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    if (sc == null || sm == null) {
        return null;
    }
    Session session = sm.getSession(exchange, sc);
    if (session == null) {
        return sm.createSession(exchange, sc);
    }
    return session;
}
 
Example 16
Source File: ServletNameAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    return src.getCurrentServlet().getManagedServlet().getServletInfo().getName();
}
 
Example 17
Source File: ServletNameAttribute.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    return src.getCurrentServlet().getManagedServlet().getServletInfo().getName();
}
 
Example 18
Source File: AccessLogCompletionListener.java    From galeb with Apache License 2.0 4 votes vote down vote up
public JsonObject getJsonObject(HttpServerExchange exchange) {
    final String remoteAddr = remoteIp().readAttribute(exchange);
    final String host = localServerName().readAttribute(exchange);
    final String requestElements[] = requestList().readAttribute(exchange).split(" ");
    final String method = exchange.getRequestMethod().toString();
    final String requestUri = exchange.getRequestURI();
    final String proto = exchange.getProtocol().toString();
    final String httpReferer = requestElements.length > 3 ? requestElements[3] : null;
    final String xMobileGroup = requestElements.length > 4 ? requestElements[4] : null;
    final int originalStatusCode = Integer.parseInt(responseCode().readAttribute(exchange));
    final long responseBytesSent = exchange.getResponseBytesSent();
    final String bytesSent = Long.toString(responseBytesSent);
    final String bytesSentOrDash = responseBytesSent == 0L ? "-" : bytesSent;
    final Integer responseTime = Math.round(Float.parseFloat(responseTimeAttribute.readAttribute(exchange)));
    final String realDestAttached = exchange.getAttachment(HostSelector.REAL_DEST);
    final String realDest = realDestAttached != null ? realDestAttached : extractXGalebErrorHeader(exchange.getResponseHeaders());
    final String userAgent = requestHeader(Headers.USER_AGENT).readAttribute(exchange);
    final String requestId = !"".equals(REQUESTID_HEADER) ? requestHeader(RequestIDHandler.requestIdHeader()).readAttribute(exchange) : null;
    final String xForwardedFor = requestHeader(Headers.X_FORWARDED_FOR).readAttribute(exchange);

    final int fakeStatusCode = getFakeStatusCode(realDestAttached, originalStatusCode, responseBytesSent, responseTime, MAX_REQUEST_TIME);
    final int statusCode = fakeStatusCode != ProcessorLocalStatusCode.NOT_MODIFIED ? fakeStatusCode : originalStatusCode;

    JsonObject json = new JsonObject();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX"); // ISO-8601
    json.addProperty("@timestamp", dateFormat.format(new Date()));
    json.addProperty("@version", "1");
    json.addProperty("host", SystemEnv.HOSTNAME.getValue());
    json.addProperty("short_message", SHORT_MESSAGE);
    json.addProperty("vhost", host);
    json.addProperty("_tags", SystemEnv.LOGGING_TAGS.getValue() + ",ACCESS");
    json.addProperty("remote_addr", remoteAddr);
    json.addProperty("request_method", method);
    json.addProperty("request_uri", requestUri);
    json.addProperty("server_protocol", proto);
    json.addProperty("http_referer", (httpReferer != null ? httpReferer : "-"));
    json.addProperty("http_x_mobile_group", (xMobileGroup != null ? xMobileGroup : "-"));
    json.addProperty("status", Integer.toString(statusCode));
    json.addProperty("body_bytes_sent", bytesSent);
    json.addProperty("request_time", Integer.toString(responseTime));
    json.addProperty("upstream_addr", realDest);
    json.addProperty("upstream_status", Integer.toString(originalStatusCode));
    json.addProperty("upstream_response_length", bytesSentOrDash);
    json.addProperty("http_user_agent", (userAgent != null ? userAgent : "-"));
    json.addProperty("request_id_final",(requestId != null ? requestId : "-"));
    json.addProperty("http_x_forwarded_for", (xForwardedFor != null ? xForwardedFor : "-"));
    return json;
}
 
Example 19
Source File: PredicatesHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final int length = handlers.length;
    Integer current = exchange.getAttachment(CURRENT_POSITION);
    do {
        int pos;
        if (current == null) {
            if (outerHandler) {
                exchange.removeAttachment(RESTART);
                exchange.removeAttachment(DONE);
                if (exchange.getAttachment(Predicate.PREDICATE_CONTEXT) == null) {
                    exchange.putAttachment(Predicate.PREDICATE_CONTEXT, new TreeMap<String, Object>());
                }
            }
            pos = 0;
        } else {
            //if it has been marked as done
            if (exchange.getAttachment(DONE) != null) {
                exchange.removeAttachment(CURRENT_POSITION);
                next.handleRequest(exchange);
                return;
            }
            pos = current;
        }
        for (; pos < length; ++pos) {
            final Holder handler = handlers[pos];
            if (handler.predicate.resolve(exchange)) {
                exchange.putAttachment(CURRENT_POSITION, pos + 1);
                handler.handler.handleRequest(exchange);
                if(shouldRestart(exchange, current)) {
                    break;
                } else {
                    return;
                }
            } else if(handler.elseBranch != null) {
                exchange.putAttachment(CURRENT_POSITION, pos + 1);
                handler.elseBranch.handleRequest(exchange);
                if(shouldRestart(exchange, current)) {
                    break;
                } else {
                    return;
                }
            }
        }
    } while (shouldRestart(exchange, current));
    next.handleRequest(exchange);

}
 
Example 20
Source File: Oauth2UserPostHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    User user = Config.getInstance().getMapper().convertValue(body, User.class);

    String email = user.getEmail();
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    // make sure that email is not duplicated in users.
    Predicate predicate = new SqlPredicate(String.format("email = %s", email));
    Set<User> set = (Set<User>) users.values(predicate);
    if(set != null && set.size() > 0) {
        setExchangeStatus(exchange, EMAIL_EXISTS, email);
        processAudit(exchange);
        return;
    }

    String password = user.getPassword();
    String passwordConfirm = user.getPasswordConfirm();
    if(password != null && password.length() > 0 && passwordConfirm != null && passwordConfirm.length() > 0) {
        // check if there are the same
        if(password.equals(passwordConfirm)) {
            // hash the password with salt.
            String hashedPass = HashUtil.generateStrongPasswordHash(password);
            user.setPassword(hashedPass);
            user.setPasswordConfirm(null);
            String userId = user.getUserId();
            if(users.get(userId) == null) {
                users.set(userId, user);
            } else {
                setExchangeStatus(exchange, USER_ID_EXISTS, userId);
            }
        } else {
            // password and passwordConfirm not match.
            setExchangeStatus(exchange, PASSWORD_PASSWORDCONFIRM_NOT_MATCH, password, passwordConfirm);
        }
    } else {
        // error password or passwordConform is empty
        setExchangeStatus(exchange, PASSWORD_OR_PASSWORDCONFIRM_EMPTY, password, passwordConfirm);
    }
    processAudit(exchange);
}