<commit_before>package org.keycloak.adapters.servlet;

import org.keycloak.adapters.spi.AdapterSessionStore;
import org.keycloak.adapters.spi.HttpFacade;
import org.keycloak.adapters.spi.KeycloakAccount;
import org.keycloak.common.util.Encode;
import org.keycloak.common.util.MultivaluedHashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Revision: 1 $
 */
public class FilterSessionStore implements AdapterSessionStore {
    public static final String REDIRECT_URI = "__REDIRECT_URI";
    public static final String SAVED_METHOD = "__SAVED_METHOD";
    public static final String SAVED_HEADERS = "__SAVED_HEADERS";
    public static final String SAVED_BODY = "__SAVED_BODY";
    protected final HttpServletRequest request;
    protected final HttpFacade facade;
    protected final int maxBuffer;
    protected byte[] restoredBuffer = null;
    protected boolean needRequestRestore;

    public FilterSessionStore(HttpServletRequest request, HttpFacade facade, int maxBuffer) {
        this.request = request;
        this.facade = facade;
        this.maxBuffer = maxBuffer;
    }

    public void clearSavedRequest(HttpSession session) {
        session.removeAttribute(REDIRECT_URI);
        session.removeAttribute(SAVED_METHOD);
        session.removeAttribute(SAVED_HEADERS);
        session.removeAttribute(SAVED_BODY);
    }

    public void servletRequestLogout() {

    }

    public static String getCharsetFromContentType(String contentType) {

        if (contentType == null)
            return (null);
        int start = contentType.indexOf("charset=");
        if (start < 0)
            return (null);
        String encoding = contentType.substring(start + 8);
        int end = encoding.indexOf(';');
        if (end >= 0)
            encoding = encoding.substring(0, end);
        encoding = encoding.trim();
        if ((encoding.length() > 2) && (encoding.startsWith("\""))
                && (encoding.endsWith("\"")))
            encoding = encoding.substring(1, encoding.length() - 1);
        return (encoding.trim());

    }


    public HttpServletRequestWrapper buildWrapper(HttpSession session, final KeycloakAccount account) {
        if (needRequestRestore) {
            final String method = (String)session.getAttribute(SAVED_METHOD);
            final byte[] body = (byte[])session.getAttribute(SAVED_BODY);
            final MultivaluedHashMap<String, String> headers = (MultivaluedHashMap<String, String>)session.getAttribute(SAVED_HEADERS);
            clearSavedRequest(session);
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                protected MultivaluedHashMap<String, String> parameters;

                MultivaluedHashMap<String, String> getParams() {
                    if (parameters != null) return parameters;
                    String contentType = getContentType();
                    contentType = contentType.toLowerCase();
                    if (contentType.startsWith("application/x-www-form-urlencoded")) {
                        ByteArrayInputStream is = new ByteArrayInputStream(body);
                        try {
                            parameters = parseForm(is);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return parameters;

                }
                @Override
                public boolean isUserInRole(String role) {
                    return account.getRoles().contains(role);
                }

                @Override
                public Principal getUserPrincipal() {<commit_msg>KEYCLOAK-2068 - Fix Potential NPE when using Servlet-Filter Adapter.<commit_after>package org.keycloak.adapters.servlet;

import org.keycloak.adapters.spi.AdapterSessionStore;
import org.keycloak.adapters.spi.HttpFacade;
import org.keycloak.adapters.spi.KeycloakAccount;
import org.keycloak.common.util.Encode;
import org.keycloak.common.util.MultivaluedHashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Revision: 1 $
 */
public class FilterSessionStore implements AdapterSessionStore {
    public static final String REDIRECT_URI = "__REDIRECT_URI";
    public static final String SAVED_METHOD = "__SAVED_METHOD";
    public static final String SAVED_HEADERS = "__SAVED_HEADERS";
    public static final String SAVED_BODY = "__SAVED_BODY";
    protected final HttpServletRequest request;
    protected final HttpFacade facade;
    protected final int maxBuffer;
    protected byte[] restoredBuffer = null;
    protected boolean needRequestRestore;

    public FilterSessionStore(HttpServletRequest request, HttpFacade facade, int maxBuffer) {
        this.request = request;
        this.facade = facade;
        this.maxBuffer = maxBuffer;
    }

    public void clearSavedRequest(HttpSession session) {
        session.removeAttribute(REDIRECT_URI);
        session.removeAttribute(SAVED_METHOD);
        session.removeAttribute(SAVED_HEADERS);
        session.removeAttribute(SAVED_BODY);
    }

    public void servletRequestLogout() {

    }

    public static String getCharsetFromContentType(String contentType) {

        if (contentType == null)
            return (null);
        int start = contentType.indexOf("charset=");
        if (start < 0)
            return (null);
        String encoding = contentType.substring(start + 8);
        int end = encoding.indexOf(';');
        if (end >= 0)
            encoding = encoding.substring(0, end);
        encoding = encoding.trim();
        if ((encoding.length() > 2) && (encoding.startsWith("\""))
                && (encoding.endsWith("\"")))
            encoding = encoding.substring(1, encoding.length() - 1);
        return (encoding.trim());

    }


    public HttpServletRequestWrapper buildWrapper(HttpSession session, final KeycloakAccount account) {
        if (needRequestRestore) {
            final String method = (String)session.getAttribute(SAVED_METHOD);
            final byte[] body = (byte[])session.getAttribute(SAVED_BODY);
            final MultivaluedHashMap<String, String> headers = (MultivaluedHashMap<String, String>)session.getAttribute(SAVED_HEADERS);
            clearSavedRequest(session);
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                protected MultivaluedHashMap<String, String> parameters;

                MultivaluedHashMap<String, String> getParams() {
                    if (parameters != null) return parameters;

                    if (body == null) return new MultivaluedHashMap<String, String>();

                    String contentType = getContentType();
                    contentType = contentType.toLowerCase();
                    if (contentType.startsWith("application/x-www-form-urlencoded")) {
                        ByteArrayInputStream is = new ByteArrayInputStream(body);
                        try {
                            parameters = parseForm(is);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return parameters;

                }
                @Override
                public boolean isUserInRole(String role) {
                    return account.getRoles().contains(role);
                }

                @Override
                public Principal getUserPrincipal() {
{'fraction_non_alphanumeric': 0.0925379904740304, 'fraction_numerical': 0.0022680880018144706, 'mean_word_length': 2.6822546972860124, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '145731', 'n_tokens_mistral': 2322, 'n_tokens_neox': 2259, 'n_words': 508}