/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2013 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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 io.undertow.server.handlers;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import io.undertow.server.ExchangeCompletionListener;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpHandlers;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.CopyOnWriteMap;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.StreamConnection;

/**
 * An HTTP request handler which upgrades the HTTP request and hands it off as a socket to any XNIO consumer.
 *
 * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
 * @author Stuart Douglas
 */
public final class ChannelUpgradeHandler implements HttpHandler {
    private final CopyOnWriteMap<String, List<Holder>> handlers = new CopyOnWriteMap<>();
    private volatile HttpHandler nonUpgradeHandler = ResponseCodeHandler.HANDLE_404;

    /**
     * Add a protocol to this handler.
     *
     * @param productString the product string to match
     * @param openListener  the open listener to call
     * @param handshake     a handshake implementation that can be used to verify the client request and modify the response
     */
    public synchronized void addProtocol(String productString, ChannelListener<? super StreamConnection> openListener, final HttpUpgradeHandshake handshake) {
        if (productString == null) {
            throw new IllegalArgumentException("productString is null");
        }
        if (openListener == null) {
            throw new IllegalArgumentException("openListener is null");
        }
        List<Holder> list = handlers.get(productString);
        if (list == null) {
            handlers.put(productString, list = new ArrayList<>());
        }
        list.add(new Holder(openListener, handshake));
    }

    /**
     * Add a protocol to this handler.
     *
     * @param productString the product string to match
     * @param openListener  the open listener to call
     */
    public void addProtocol(String productString, ChannelListener<? super StreamConnection> openListener) {
        addProtocol(productString, openListener, null);
    }

    /**
     * Remove a protocol from this handler. This will remove all upgrade handlers that match the product string
     *
     * @param productString the product string to match
     */
    public synchronized void removeProtocol(String productString) {
        handlers.remove(productString);
    }

    /**
     * Remove a protocol from this handler.
     *
     * @param productString the product string to match
     * @param openListener  The open listener
     */
    public synchronized void removeProtocol(String productString, ChannelListener<? super StreamConnection> openListener) {
        List<Holder> holders = handlers.get(productString);
        if (holders == null) {
            return;
        }
        Iterator<Holder> it = holders.iterator();
        while (it.hasNext()) {
            Holder holder = it.next();
            if (holder.listener == openListener) {
                it.remove();
                break;
            }
        }
        if (holders.isEmpty()) {
            handlers.remove(productString);
        }
    }

    /**
     * Get the non-upgrade delegate handler.
     *
     * @return the non-upgrade delegate handler
     */
    public HttpHandler getNonUpgradeHandler() {
        return nonUpgradeHandler;
    }

    /**
     * Set the non-upgrade delegate handler.
     *
     * @param nonUpgradeHandler the non-upgrade delegate handler
     */
    public ChannelUpgradeHandler setNonUpgradeHandler(final HttpHandler nonUpgradeHandler) {
        HttpHandlers.handlerNotNull(nonUpgradeHandler);
        this.nonUpgradeHandler = nonUpgradeHandler;
        return this;
    }

    public void handleRequest(final HttpServerExchange exchange) throws Exception {
        final List<String> upgradeStrings = exchange.getRequestHeaders().get(Headers.UPGRADE);
        if (upgradeStrings != null && exchange.getRequestMethod().equals(Methods.GET)) {
            for (String string : upgradeStrings) {
                final List<Holder> holders = handlers.get(string);
                for (Holder holder : holders) {
                    final ChannelListener<? super StreamConnection> listener = holder.listener;
                    if (holder.handshake != null) {
                        if (!holder.handshake.handleUpgrade(exchange)) {
                            //handshake did not match, try again
                            continue;
                        }
                    }

                    exchange.upgradeChannel(string, new ExchangeCompletionListener() {
                        @Override
                        public void exchangeEvent(final HttpServerExchange exchange, final NextListener nextListener) {
                            ChannelListeners.invokeChannelListener(exchange.getConnection().getChannel(), listener);
                        }
                    });
                    exchange.endExchange();
                    return;
                }
            }
        }
        final HttpHandler handler = nonUpgradeHandler;
        HttpHandlers.executeHandler(handler, exchange);
    }


    private static final class Holder {
        final ChannelListener<? super StreamConnection> listener;
        final HttpUpgradeHandshake handshake;

        private Holder(final ChannelListener<? super StreamConnection> listener, final HttpUpgradeHandshake handshake) {
            this.listener = listener;
            this.handshake = handshake;
        }
    }
}

@@ -4931,32 +4931,75 @@
 rs.get(string);%0A
+                if (holders != null) %7B%0A    
                 
@@ -5026,24 +5026,28 @@
  holders) %7B%0A
+    
             
@@ -5142,32 +5142,36 @@
                 
+ 
+   
 if (holder.hands
@@ -5178,32 +5178,36 @@
 hake != null) %7B%0A
+    
                 
@@ -5291,16 +5291,20 @@
         
+    
 //handsh
@@ -5360,16 +5360,20 @@
         
+ 
+   
 continue
@@ -5374,16 +5374,20 @@
 ntinue;%0A
+    
         
@@ -5420,24 +5420,28 @@
             
+    
 %7D%0A%0A         
@@ -5443,32 +5443,36 @@
                 
+ 
+   
 exchange.upgrade
@@ -5546,16 +5546,20 @@
         
+    
 @Overrid
@@ -5560,16 +5560,20 @@
 verride%0A
+    
         
@@ -5712,16 +5712,20 @@
         
+ 
+   
 ChannelL
@@ -5821,34 +5821,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -5875,32 +5875,36 @@
                 
+    
 exchange.endExch
@@ -5927,32 +5927,36 @@
             
+    
 return;%0A
             
@@ -5935,32 +5935,36 @@
         return;%0A
+    
                 
@@ -5969,34 +5969,42 @@
   %7D%0A            
-%7D%0A
+    %7D%0A    
         %7D%0A      
@@ -6009,100 +6009,50 @@
     
-final HttpHandler handler = nonUpgradeHandler;%0A        HttpHandlers.executeHandler(handler, 
+%7D%0A        nonUpgradeHandler.handleRequest(
 exch

Fix NPE