/*
 * Copyright 2015-2016 Canoo Engineering AG.
 *
 * 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.canoo.dolphin.server.context;

import com.canoo.dolphin.impl.PlatformConstants;
import com.canoo.dolphin.server.DolphinSessionListener;
import com.canoo.dolphin.server.config.DolphinPlatformConfiguration;
import com.canoo.dolphin.server.container.ContainerManager;
import com.canoo.dolphin.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class DolphinContextFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(DolphinContextFilter.class);

    private final DolphinPlatformConfiguration configuration;

    private final ContainerManager containerManager;

    private final DolphinContextFactory dolphinContextFactory;

    private final DolphinSessionListenerProvider dolphinSessionListenerProvider;

    public DolphinContextFilter(final DolphinPlatformConfiguration configuration, final ContainerManager containerManager, final DolphinContextFactory dolphinContextFactory, final DolphinSessionListenerProvider dolphinSessionListenerProvider) {
        this.configuration = Assert.requireNonNull(configuration, "configuration");
        this.containerManager = Assert.requireNonNull(containerManager, "containerManager");
        this.dolphinContextFactory = Assert.requireNonNull(dolphinContextFactory, "dolphinContextFactory");
        this.dolphinSessionListenerProvider = Assert.requireNonNull(dolphinSessionListenerProvider, "dolphinSessionListenerProvider");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        DolphinContextUtils.setContextForCurrentThread(null);
        final HttpServletRequest servletRequest = (HttpServletRequest) request;
        final HttpServletResponse servletResponse = (HttpServletResponse) response;
        final HttpSession httpSession = Assert.requireNonNull(servletRequest.getSession(), "request.getSession()");

        try {
            DolphinContext dolphinContext;
            final String clientId = servletRequest.getHeader(PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME);
            if (clientId == null || clientId.trim().isEmpty()) {
                if(DolphinContextUtils.getOrCreateContextMapInSession(httpSession).size() >= configuration.getMaxClientsPerSession()) {
                    servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Maximum size for clients in session is reached");
                    LOG.info("Maximum size for clients in session " + servletRequest.getSession().getId() +" is reached");
                    return;
                }
                dolphinContext = createNewContext(httpSession);
                DolphinContextUtils.storeInSession(servletRequest.getSession(), dolphinContext);
                for(DolphinSessionListener listener : dolphinSessionListenerProvider.getAllListeners()) {
                    listener.sessionCreated(dolphinContext.getCurrentDolphinSession());
                }
                LOG.trace("Created new DolphinContext {} in http session {}", dolphinContext.getId(), httpSession.getId());
            } else {
                dolphinContext = DolphinContextUtils.getClientInSession(servletRequest.getSession(), clientId);
                if(dolphinContext == null) {
                    LOG.warn("Can not find requested client for id {} in session {}", clientId, servletRequest.getSession().getId());
                    servletResponse.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, "Can not find requested client!");
                    return;
                }
            }
            DolphinContextUtils.setContextForCurrentThread(dolphinContext);
            servletResponse.setHeader(PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME, dolphinContext.getId());
            chain.doFilter(request, response);
        } finally {
            DolphinContextUtils.setContextForCurrentThread(null);
        }
    }

    private DolphinContext createNewContext(final HttpSession httpSession) {
        Assert.requireNonNull(httpSession, "httpSession");
        return dolphinContextFactory.create(httpSession, dolphinSessionListenerProvider);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Nothing to do here
    }

    @Override
    public void destroy() {
    }
}

@@ -1492,24 +1492,142 @@
 er.class);%0A%0A
+    private static final String DOLPHIN_PLATFORM_INITIALIZED_IN_SESSION = %22DOLPHIN_PLATFORM_INITIALIZED_IN_SESSION%22;%0A%0A
     private 
@@ -3616,11 +3616,23 @@
 ion 
-%22 +
+%7B%7D is reached%22,
  ser
@@ -3667,23 +3667,8 @@
 Id()
- +%22 is reached%22
 );%0A 
@@ -4201,32 +4201,309 @@
 ssion.getId());%0A
+%0A                Object init = servletRequest.getSession().getAttribute(DOLPHIN_PLATFORM_INITIALIZED_IN_SESSION);%0A                if(init == null) %7B%0A                    servletRequest.getSession().setAttribute(DOLPHIN_PLATFORM_INITIALIZED_IN_SESSION, true);%0A                %7D%0A%0A
             %7D el
@@ -4656,32 +4656,192 @@
 text == null) %7B%0A
+                    Object init = servletRequest.getSession().getAttribute(DOLPHIN_PLATFORM_INITIALIZED_IN_SESSION);%0A                    if(init == null) %7B%0A    
                 
@@ -4907,16 +4907,34 @@
 ssion %7B%7D
+ (session timeout)
 %22, clien
@@ -4968,32 +4968,36 @@
 ion().getId());%0A
+    
                 
@@ -5100,12 +5100,382 @@
 ient
-!%22);
+ (session timeout)!%22);%0A                    %7D else %7B%0A                        LOG.warn(%22Can not find requested client for id %7B%7D in session %7B%7D (unknown error)%22, clientId, servletRequest.getSession().getId());%0A                        servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, %22Can not find requested client (unknown error)!%22);%0A                    %7D
 %0A   

Check no client error