/**
     * Sets up the handlers in the servlet chain. We setup a chain for every path + extension match possibility.
     * (i.e. if there a m path mappings and n extension mappings we have n*m chains).
     *

     * If a chain consists of only the default servlet then we add it as an async handler, so that resources can be
     * served up directly without using blocking operations.
     *

     * TODO: this logic is a bit convoluted at the moment, we should look at simplifying it
     */
    private ServletPathMatchesData setupServletChains() {
        //create the default servlet
        ServletHandler defaultServlet = null;
        final ManagedServlets servlets = deployment.getServlets();
        final ManagedFilters filters = deployment.getFilters();

        final Map<String, ServletHandler> extensionServlets = new HashMap<>();
        final Map<String, ServletHandler> pathServlets = new HashMap<>();

        final Set<String> pathMatches = new HashSet<>();
        final Set<String> extensionMatches = new HashSet<>();

        DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();

        //loop through all filter mappings, and add them to the set of known paths
        for (FilterMappingInfo mapping : deploymentInfo.getFilterMappings()) {
            if (mapping.getMappingType() == FilterMappingInfo.MappingType.URL) {
                String path = mapping.getMapping();
                if (path.equals("*")) {
                    //UNDERTOW-95, support this non-standard filter mapping
                    path = "/*";
                }
                if (!path.startsWith("*.")) {
                    pathMatches.add(path);
                } else {
                    extensionMatches.add(path.substring(2));
                }
            }
        }

        //now loop through all servlets.
        for (Map.Entry<String, ServletHandler> entry : servlets.getServletHandlers().entrySet()) {
            final ServletHandler handler = entry.getValue();
            //add the servlet to the appropriate path maps
            for (String path : handler.getManagedServlet().getServletInfo().getMappings()) {
                if (path.equals("/")) {
                    //the default servlet
                    pathMatches.add("/*");
                    if (defaultServlet != null) {
                        throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                    }
                    defaultServlet = handler;
                } else if (!path.startsWith("*.")) {
                    //either an exact or a /* based path match
                    if (path.isEmpty()) {
                        path = "/";
                    }
                    pathMatches.add(path);
                    if (pathServlets.containsKey(path)) {
                        throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                    }
                    pathServlets.put(path, handler);
                } else {
                    //an extension match based servlet
                    String ext = path.substring(2);
                    extensionMatches.add(ext);
                    if(extensionServlets.containsKey(ext)) {
                        throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                    }
                    extensionServlets.put(ext, handler);
                }
            }
        }
        ServletHandler managedDefaultServlet = servlets.getServletHandler(DEFAULT_SERVLET_NAME);
        if(managedDefaultServlet == null) {
            //we always create a default servlet, even if it is not going to have any path mappings registered
            managedDefaultServlet = servlets.addServlet(new ServletInfo(DEFAULT_SERVLET_NAME, DefaultServlet.class));
        }

        if (defaultServlet == null) {
            //no explicit default servlet was specified, so we register our mapping
            pathMatches.add("/*");
            defaultServlet = managedDefaultServlet;
        }

        final ServletPathMatchesData.Builder builder = ServletPathMatchesData.builder();

        //we now loop over every path in the application, and build up the patches based on this path
        //these paths contain both /* and exact matches.
        for (final String path : pathMatches) {
            //resolve the target servlet, will return null if this is the default servlet
            MatchData targetServletMatch = resolveServletForPath(path, pathServlets, extensionServlets, defaultServlet);

            final Map<DispatcherType, List<ManagedFilter>> noExtension = new EnumMap<>(DispatcherType.class);
            final Map<String, Map<DispatcherType, List<ManagedFilter>>> extension = new HashMap<>();
            //initialize the extension map. This contains all the filers in the noExtension map, plus
            //any filters that match the extension key
            for (String ext : extensionMatches) {
                extension.put(ext, new EnumMap<>(DispatcherType.class));
            }

            //loop over all the filters, and add them to the appropriate map in the correct order
            for (final FilterMappingInfo filterMapping : deploymentInfo.getFilterMappings()) {
                ManagedFilter filter = filters.getManagedFilter(filterMapping.getFilterName());
                if (filterMapping.getMappingType() == FilterMappingInfo.MappingType.SERVLET) {
                    if (targetServletMatch.handler != null) {
                        if (filterMapping.getMapping().equals(targetServletMatch.handler.getManagedServlet().getServletInfo().getName()) || filterMapping.getMapping().equals("*")) {
                            addToListMap(noExtension, filterMapping.getDispatcher(), filter);
                        }
                    }
                    for (Map.Entry<String, Map<DispatcherType, List<ManagedFilter>>> entry : extension.entrySet()) {
                        ServletHandler pathServlet = targetServletMatch.handler;
                        boolean defaultServletMatch = targetServletMatch.defaultServlet;
                        if (defaultServletMatch && extensionServlets.containsKey(entry.getKey())) {
                            pathServlet = extensionServlets.get(entry.getKey());
                        }

                        if (filterMapping.getMapping().equals(pathServlet.getManagedServlet().getServletInfo().getName()) || filterMapping.getMapping().equals("*")) {
                            addToListMap(extension.get(entry.getKey()), filterMapping.getDispatcher(), filter);
                        }
                    }
                } else {
                    if (filterMapping.getMapping().isEmpty() || !filterMapping.getMapping().startsWith("*.")) {
                        if (isFilterApplicable(path, filterMapping.getMapping())) {
                            addToListMap(noExtension, filterMapping.getDispatcher(), filter);
                            for (Map<DispatcherType, List<ManagedFilter>> l : extension.values()) {
                                addToListMap(l, filterMapping.getDispatcher(), filter);
                            }
                        }
                    } else {
                        addToListMap(extension.get(filterMapping.getMapping().substring(2)), filterMapping.getDispatcher(), filter);
                    }
                }
            }
            //resolve any matches and add them to the builder
            if (path.endsWith("/*")) {
                String prefix = path.substring(0, path.length() - 2);
                //add the default non-extension match
                builder.addPrefixMatch(prefix, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath), targetServletMatch.defaultServlet || targetServletMatch.handler.getManagedServlet().getServletInfo().isRequireWelcomeFileMapping());

                //build up the chain for each non-extension match
                for (Map.Entry<String, Map<DispatcherType, List<ManagedFilter>>> entry : extension.entrySet()) {
                    ServletHandler pathServlet = targetServletMatch.handler;
                    String pathMatch = targetServletMatch.matchedPath;

                    final boolean defaultServletMatch;
                    final String servletMatchPattern;
                    final MappingMatch mappingMatch;
                    if (targetServletMatch.defaultServlet) {
                        // Path matches always take precedence over extension matches, however the default servlet is matched
                        // at a lower priority, after extension matches. The "/*" pattern is applied implicitly onto the
                        // default servlet. If there's an extension match in addition to a non-default servlet path match,
                        // the servlet path match is higher priority. However if the path match is the default servlets
                        // default catch-all path, the extension match is a higher priority.
                        ServletHandler extensionServletHandler = extensionServlets.get(entry.getKey());
                        if (extensionServletHandler != null) {
                            defaultServletMatch = false;
                            pathServlet = extensionServletHandler;
                            servletMatchPattern = "*." + entry.getKey();
                            mappingMatch = MappingMatch.EXTENSION;
                        } else {
                            defaultServletMatch = true;
                            servletMatchPattern = "/";
                            mappingMatch = MappingMatch.DEFAULT;
                        }
                    } else {
                        defaultServletMatch = false;
                        servletMatchPattern = path;
                        mappingMatch = MappingMatch.PATH;
                    }
                    HttpHandler handler = pathServlet;
                    if (!entry.getValue().isEmpty()) {
                        handler = new FilterHandler(entry.getValue(), deploymentInfo.isAllowNonStandardWrappers(), handler);
                    }
                    builder.addExtensionMatch(prefix, entry.getKey(), servletChain(handler, pathServlet.getManagedServlet(), entry.getValue(), pathMatch, deploymentInfo, defaultServletMatch, mappingMatch, servletMatchPattern));
                }
            } else if (path.isEmpty()) {
                //the context root match
                builder.addExactMatch("/", createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
            } else {
                //we need to check for an extension match, so paths like /exact.txt will have the correct filter applied
                int lastSegmentIndex = path.lastIndexOf('/');
                String lastSegment;
                if(lastSegmentIndex > 0) {
                    lastSegment = path.substring(lastSegmentIndex);
                } else {
                    lastSegment = path;
                }
                if (lastSegment.contains(".")) {
                    String ext = lastSegment.substring(lastSegment.lastIndexOf('.') + 1);
                    if (extension.containsKey(ext)) {
                        Map<DispatcherType, List<ManagedFilter>> extMap = extension.get(ext);
                        builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, extMap, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                    } else {
                        builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                    }
                } else {
                    builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                }

            }
        }

        //now setup name based mappings
        //these are used for name based dispatch
        for (Map.Entry<String, ServletHandler> entry : servlets.getServletHandlers().entrySet()) {
            final Map<DispatcherType, List<ManagedFilter>> filtersByDispatcher = new EnumMap<>(DispatcherType.class);
            for (final FilterMappingInfo filterMapping : deploymentInfo.getFilterMappings()) {
                ManagedFilter filter = filters.getManagedFilter(filterMapping.getFilterName());
                if (filterMapping.getMappingType() == FilterMappingInfo.MappingType.SERVLET) {
                    if (filterMapping.getMapping().equals(entry.getKey())) {
                        addToListMap(filtersByDispatcher, filterMapping.getDispatcher(), filter);
                    }
                }
            }
            if (filtersByDispatcher.isEmpty()) {
                builder.addNameMatch(entry.getKey(), servletChain(entry.getValue(), entry.getValue().getManagedServlet(), filtersByDispatcher, null, deploymentInfo, false, MappingMatch.EXACT, ""));
            } else {
                builder.addNameMatch(entry.getKey(), servletChain(new FilterHandler(filtersByDispatcher, deploymentInfo.isAllowNonStandardWrappers(), entry.getValue()), entry.getValue().getManagedServlet(), filtersByDispatcher, null, deploymentInfo, false, MappingMatch.EXACT, ""));
            }
        }

        return builder.build();
    }

/**
     * Sets up the handlers in the servlet chain. We setup a chain for every path + extension match possibility.
     * (i.e. if there a m path mappings and n extension mappings we have n*m chains).
     *

     * If a chain consists of only the default servlet then we add it as an async handler, so that resources can be
     * served up directly without using blocking operations.
     *

     * TODO: this logic is a bit convoluted at the moment, we should look at simplifying it
     */
    private ServletPathMatchesData setupServletChains() {
        //create the default servlet
        ServletHandler defaultServlet = null;
        final ManagedServlets servlets = deployment.getServlets();
        final ManagedFilters filters = deployment.getFilters();

        final Map<String, ServletHandler> extensionServlets = new HashMap<>();
        final Map<String, ServletHandler> pathServlets = new HashMap<>();

        final Set<String> pathMatches = new HashSet<>();
        final Set<String> extensionMatches = new HashSet<>();

        DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();

        //loop through all filter mappings, and add them to the set of known paths
        for (FilterMappingInfo mapping : deploymentInfo.getFilterMappings()) {
            if (mapping.getMappingType() == FilterMappingInfo.MappingType.URL) {
                String path = mapping.getMapping();
                if (path.equals("*")) {
                    //UNDERTOW-95, support this non-standard filter mapping
                    path = "/*";
                }
                if (!path.startsWith("*.")) {
                    pathMatches.add(path);
                } else {
                    extensionMatches.add(path.substring(2));
                }
            }
        }

        //now loop through all servlets.
        for (Map.Entry<String, ServletHandler> entry : servlets.getServletHandlers().entrySet()) {
            final ServletHandler handler = entry.getValue();
            //add the servlet to the appropriate path maps
            for (String path : handler.getManagedServlet().getServletInfo().getMappings()) {
                if (path.equals("/")) {
                    //the default servlet
                    pathMatches.add("/*");
                    if (defaultServlet != null) {
                        throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                    }
                    defaultServlet = handler;
                } else if (!path.startsWith("*.")) {
                    //either an exact or a /* based path match
                    if (path.isEmpty()) {
                        path = "/";
                    }
                    pathMatches.add(path);
                    if (pathServlets.containsKey(path)) {
                        throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                    }
                    pathServlets.put(path, handler);
                } else {
                    //an extension match based servlet
                    String ext = path.substring(2);
                    extensionMatches.add(ext);
                    if(extensionServlets.containsKey(ext)) {
                        throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                    }
                    extensionServlets.put(ext, handler);
                }
            }
        }
        ServletHandler managedDefaultServlet = servlets.getServletHandler(DEFAULT_SERVLET_NAME);
        if(managedDefaultServlet == null) {
            //we always create a default servlet, even if it is not going to have any path mappings registered
            managedDefaultServlet = servlets.addServlet(new ServletInfo(DEFAULT_SERVLET_NAME, DefaultServlet.class));
        }

        if (defaultServlet == null) {
            //no explicit default servlet was specified, so we register our mapping
            pathMatches.add("/*");
            defaultServlet = managedDefaultServlet;
        }

        final ServletPathMatchesData.Builder builder = ServletPathMatchesData.builder();

        //we now loop over every path in the application, and build up the patches based on this path
        //these paths contain both /* and exact matches.
        for (final String path : pathMatches) {
            //resolve the target servlet, will return null if this is the default servlet
            MatchData targetServletMatch = resolveServletForPath(path, pathServlets, extensionServlets, defaultServlet);

            final Map<DispatcherType, List<ManagedFilter>> noExtension = new EnumMap<>(DispatcherType.class);
            final Map<String, Map<DispatcherType, List<ManagedFilter>>> extension = new HashMap<>();
            //initialize the extension map. This contains all the filers in the noExtension map, plus
            //any filters that match the extension key
            for (String ext : extensionMatches) {
                extension.put(ext, new EnumMap<DispatcherType, List<ManagedFilter>>(DispatcherType.class));
            }

            //loop over all the filters, and add them to the appropriate map in the correct order
            for (final FilterMappingInfo filterMapping : deploymentInfo.getFilterMappings()) {
                ManagedFilter filter = filters.getManagedFilter(filterMapping.getFilterName());
                if (filterMapping.getMappingType() == FilterMappingInfo.MappingType.SERVLET) {
                    if (targetServletMatch.handler != null) {
                        if (filterMapping.getMapping().equals(targetServletMatch.handler.getManagedServlet().getServletInfo().getName()) || filterMapping.getMapping().equals("*")) {
                            addToListMap(noExtension, filterMapping.getDispatcher(), filter);
                        }
                    }
                    for (Map.Entry<String, Map<DispatcherType, List<ManagedFilter>>> entry : extension.entrySet()) {
                        ServletHandler pathServlet = targetServletMatch.handler;
                        boolean defaultServletMatch = targetServletMatch.defaultServlet;
                        if (defaultServletMatch && extensionServlets.containsKey(entry.getKey())) {
                            pathServlet = extensionServlets.get(entry.getKey());
                        }

                        if (filterMapping.getMapping().equals(pathServlet.getManagedServlet().getServletInfo().getName()) || filterMapping.getMapping().equals("*")) {
                            addToListMap(extension.get(entry.getKey()), filterMapping.getDispatcher(), filter);
                        }
                    }
                } else {
                    if (filterMapping.getMapping().isEmpty() || !filterMapping.getMapping().startsWith("*.")) {
                        if (isFilterApplicable(path, filterMapping.getMapping())) {
                            addToListMap(noExtension, filterMapping.getDispatcher(), filter);
                            for (Map<DispatcherType, List<ManagedFilter>> l : extension.values()) {
                                addToListMap(l, filterMapping.getDispatcher(), filter);
                            }
                        }
                    } else {
                        addToListMap(extension.get(filterMapping.getMapping().substring(2)), filterMapping.getDispatcher(), filter);
                    }
                }
            }
            //resolve any matches and add them to the builder
            if (path.endsWith("/*")) {
                String prefix = path.substring(0, path.length() - 2);
                //add the default non-extension match
                builder.addPrefixMatch(prefix, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath), targetServletMatch.defaultServlet || targetServletMatch.handler.getManagedServlet().getServletInfo().isRequireWelcomeFileMapping());

                //build up the chain for each non-extension match
                for (Map.Entry<String, Map<DispatcherType, List<ManagedFilter>>> entry : extension.entrySet()) {
                    ServletHandler pathServlet = targetServletMatch.handler;
                    String pathMatch = targetServletMatch.matchedPath;

                    final boolean defaultServletMatch;
                    final String servletMatchPattern;
                    final MappingMatch mappingMatch;
                    if (targetServletMatch.defaultServlet) {
                        // Path matches always take precedence over extension matches, however the default servlet is matched
                        // at a lower priority, after extension matches. The "/*" pattern is applied implicitly onto the
                        // default servlet. If there's an extension match in addition to a non-default servlet path match,
                        // the servlet path match is higher priority. However if the path match is the default servlets
                        // default catch-all path, the extension match is a higher priority.
                        ServletHandler extensionServletHandler = extensionServlets.get(entry.getKey());
                        if (extensionServletHandler != null) {
                            defaultServletMatch = false;
                            pathServlet = extensionServletHandler;
                            servletMatchPattern = "*." + entry.getKey();
                            mappingMatch = MappingMatch.EXTENSION;
                        } else {
                            defaultServletMatch = true;
                            servletMatchPattern = "/";
                            mappingMatch = MappingMatch.DEFAULT;
                        }
                    } else {
                        defaultServletMatch = false;
                        servletMatchPattern = path;
                        mappingMatch = MappingMatch.PATH;
                    }
                    HttpHandler handler = pathServlet;
                    if (!entry.getValue().isEmpty()) {
                        handler = new FilterHandler(entry.getValue(), deploymentInfo.isAllowNonStandardWrappers(), handler);
                    }
                    builder.addExtensionMatch(prefix, entry.getKey(), servletChain(handler, pathServlet.getManagedServlet(), entry.getValue(), pathMatch, deploymentInfo, defaultServletMatch, mappingMatch, servletMatchPattern));
                }
            } else if (path.isEmpty()) {
                //the context root match
                builder.addExactMatch("/", createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
            } else {
                //we need to check for an extension match, so paths like /exact.txt will have the correct filter applied
                int lastSegmentIndex = path.lastIndexOf('/');
                String lastSegment;
                if(lastSegmentIndex > 0) {
                    lastSegment = path.substring(lastSegmentIndex);
                } else {
                    lastSegment = path;
                }
                if (lastSegment.contains(".")) {
                    String ext = lastSegment.substring(lastSegment.lastIndexOf('.') + 1);
                    if (extension.containsKey(ext)) {
                        Map<DispatcherType, List<ManagedFilter>> extMap = extension.get(ext);
                        builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, extMap, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                    } else {
                        builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                    }
                } else {
                    builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                }

            }
        }

        //now setup name based mappings
        //these are used for name based dispatch
        for (Map.Entry<String, ServletHandler> entry : servlets.getServletHandlers().entrySet()) {
            final Map<DispatcherType, List<ManagedFilter>> filtersByDispatcher = new EnumMap<>(DispatcherType.class);
            for (final FilterMappingInfo filterMapping : deploymentInfo.getFilterMappings()) {
                ManagedFilter filter = filters.getManagedFilter(filterMapping.getFilterName());
                if (filterMapping.getMappingType() == FilterMappingInfo.MappingType.SERVLET) {
                    if (filterMapping.getMapping().equals(entry.getKey())) {
                        addToListMap(filtersByDispatcher, filterMapping.getDispatcher(), filter);
                    }
                }
            }
            if (filtersByDispatcher.isEmpty()) {
                builder.addNameMatch(entry.getKey(), servletChain(entry.getValue(), entry.getValue().getManagedServlet(), filtersByDispatcher, null, deploymentInfo, false, MappingMatch.EXACT, ""));
            } else {
                builder.addNameMatch(entry.getKey(), servletChain(new FilterHandler(filtersByDispatcher, deploymentInfo.isAllowNonStandardWrappers(), entry.getValue()), entry.getValue().getManagedServlet(), filtersByDispatcher, null, deploymentInfo, false, MappingMatch.EXACT, ""));
            }
        }

        return builder.build();
    }

Replace Generic With Diamond EnumMap<DispatcherType,List<ManagedFilter>> with EnumMap<> in method private setupServletChains() : ServletPathMatchesData from class io.undertow.servlet.handlers.ServletPathMatches


    @Override
    public <T extends EventListener> void addListener(final T t) {
        ensureNotInitialized();
        ensureNotProgramaticListener();
        if (ApplicationListeners.listenerState() != NO_LISTENER
                && ServletContextListener.class.isAssignableFrom(t.getClass())) {
            throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
        }
        ListenerInfo listener = new ListenerInfo(t.getClass(), new ImmediateInstanceFactory<>(t));
        getDeploymentInfo().addListener(listener);
        deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
    }

    @Override
    public <T extends EventListener> void addListener(final T t) {
        ensureNotInitialized();
        ensureNotProgramaticListener();
        if (ApplicationListeners.listenerState() != NO_LISTENER
                && ServletContextListener.class.isAssignableFrom(t.getClass())) {
            throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
        }
        ListenerInfo listener = new ListenerInfo(t.getClass(), new ImmediateInstanceFactory<EventListener>(t));
        getDeploymentInfo().addListener(listener);
        deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
    }

Replace Generic With Diamond ListenerInfo with ListenerInfo in method public addListener(t T) : void from class io.undertow.servlet.spec.ServletContextImpl


    public void doUpgrade(HttpServletRequest request,
                          HttpServletResponse response, final ServerEndpointConfig sec,
                          Map<String,String> pathParams)
            throws ServletException, IOException {
        ServerEndpointConfig.Configurator configurator = sec.getConfigurator();
        try {
            EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, sec.getDecoders(), sec.getEncoders());
            PathTemplate pt = PathTemplate.create(sec.getPath());

            InstanceFactory<?> instanceFactory = null;
            try {
                instanceFactory = classIntrospecter.createInstanceFactory(sec.getEndpointClass());
            } catch (Exception e) {
                //so it is possible that this is still valid if a custom configurator is in use
                if (configurator == null || configurator.getClass() == ServerEndpointConfig.Configurator.class) {
                    throw JsrWebSocketMessages.MESSAGES.couldNotDeploy(e);
                } else {
                    instanceFactory = new InstanceFactory<Object>() {
                        @Override
                        public InstanceHandle<Object> createInstance() throws InstantiationException {
                            throw JsrWebSocketMessages.MESSAGES.endpointDoesNotHaveAppropriateConstructor(sec.getEndpointClass());
                        }
                    };
                }
            }
            if (configurator == null) {
                configurator = DefaultContainerConfigurator.INSTANCE;
            }

            ServerEndpointConfig config = ServerEndpointConfig.Builder.create(sec.getEndpointClass(), sec.getPath())
                    .decoders(sec.getDecoders())
                    .encoders(sec.getEncoders())
                    .subprotocols(sec.getSubprotocols())
                    .extensions(sec.getExtensions())
                    .configurator(configurator)
                    .build();

            AnnotatedEndpointFactory annotatedEndpointFactory = null;
            if(!Endpoint.class.isAssignableFrom(sec.getEndpointClass())) {
                annotatedEndpointFactory = AnnotatedEndpointFactory.create(sec.getEndpointClass(), encodingFactory, pt.getParameterNames());
            }

            ConfiguredServerEndpoint confguredServerEndpoint;
            if(annotatedEndpointFactory == null) {
                confguredServerEndpoint = new ConfiguredServerEndpoint(config, instanceFactory, null, encodingFactory);
            } else {
                confguredServerEndpoint = new ConfiguredServerEndpoint(config, instanceFactory, null, encodingFactory, annotatedEndpointFactory, installedExtensions);
            }
            WebSocketHandshakeHolder hand;

            WebSocketDeploymentInfo info = (WebSocketDeploymentInfo)request.getServletContext().getAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
            if (info == null || info.getExtensions() == null) {
                hand = ServerWebSocketContainer.handshakes(confguredServerEndpoint);
            } else {
                hand = ServerWebSocketContainer.handshakes(confguredServerEndpoint, info.getExtensions());
            }

            final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(request, response, new HashSet<>());
            Handshake handshaker = null;
            for (Handshake method : hand.handshakes) {
                if (method.matches(facade)) {
                    handshaker = method;
                    break;
                }
            }

            if (handshaker != null) {
                if(isClosed()) {
                    response.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                    return;
                }
                facade.putAttachment(HandshakeUtil.PATH_PARAMS, pathParams);
                final Handshake selected = handshaker;
                facade.upgradeChannel(new HttpUpgradeListener() {
                    @Override
                    public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                        WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
                        new EndpointSessionHandler(ServerWebSocketContainer.this).onConnect(facade, channel);
                    }
                });
                handshaker.handshake(facade);
                return;
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    public void doUpgrade(HttpServletRequest request,
                          HttpServletResponse response, final ServerEndpointConfig sec,
                          Map<String,String> pathParams)
            throws ServletException, IOException {
        ServerEndpointConfig.Configurator configurator = sec.getConfigurator();
        try {
            EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, sec.getDecoders(), sec.getEncoders());
            PathTemplate pt = PathTemplate.create(sec.getPath());

            InstanceFactory<?> instanceFactory = null;
            try {
                instanceFactory = classIntrospecter.createInstanceFactory(sec.getEndpointClass());
            } catch (Exception e) {
                //so it is possible that this is still valid if a custom configurator is in use
                if (configurator == null || configurator.getClass() == ServerEndpointConfig.Configurator.class) {
                    throw JsrWebSocketMessages.MESSAGES.couldNotDeploy(e);
                } else {
                    instanceFactory = new InstanceFactory<Object>() {
                        @Override
                        public InstanceHandle<Object> createInstance() throws InstantiationException {
                            throw JsrWebSocketMessages.MESSAGES.endpointDoesNotHaveAppropriateConstructor(sec.getEndpointClass());
                        }
                    };
                }
            }
            if (configurator == null) {
                configurator = DefaultContainerConfigurator.INSTANCE;
            }

            ServerEndpointConfig config = ServerEndpointConfig.Builder.create(sec.getEndpointClass(), sec.getPath())
                    .decoders(sec.getDecoders())
                    .encoders(sec.getEncoders())
                    .subprotocols(sec.getSubprotocols())
                    .extensions(sec.getExtensions())
                    .configurator(configurator)
                    .build();

            AnnotatedEndpointFactory annotatedEndpointFactory = null;
            if(!Endpoint.class.isAssignableFrom(sec.getEndpointClass())) {
                annotatedEndpointFactory = AnnotatedEndpointFactory.create(sec.getEndpointClass(), encodingFactory, pt.getParameterNames());
            }

            ConfiguredServerEndpoint confguredServerEndpoint;
            if(annotatedEndpointFactory == null) {
                confguredServerEndpoint = new ConfiguredServerEndpoint(config, instanceFactory, null, encodingFactory);
            } else {
                confguredServerEndpoint = new ConfiguredServerEndpoint(config, instanceFactory, null, encodingFactory, annotatedEndpointFactory, installedExtensions);
            }
            WebSocketHandshakeHolder hand;

            WebSocketDeploymentInfo info = (WebSocketDeploymentInfo)request.getServletContext().getAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
            if (info == null || info.getExtensions() == null) {
                hand = ServerWebSocketContainer.handshakes(confguredServerEndpoint);
            } else {
                hand = ServerWebSocketContainer.handshakes(confguredServerEndpoint, info.getExtensions());
            }

            final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(request, response, new HashSet<WebSocketChannel>());
            Handshake handshaker = null;
            for (Handshake method : hand.handshakes) {
                if (method.matches(facade)) {
                    handshaker = method;
                    break;
                }
            }

            if (handshaker != null) {
                if(isClosed()) {
                    response.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                    return;
                }
                facade.putAttachment(HandshakeUtil.PATH_PARAMS, pathParams);
                final Handshake selected = handshaker;
                facade.upgradeChannel(new HttpUpgradeListener() {
                    @Override
                    public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                        WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
                        new EndpointSessionHandler(ServerWebSocketContainer.this).onConnect(facade, channel);
                    }
                });
                handshaker.handshake(facade);
                return;
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

Replace Generic With Diamond ServletWebSocketHttpExchange with ServletWebSocketHttpExchange in method public doUpgrade(request HttpServletRequest, response HttpServletResponse, sec ServerEndpointConfig, pathParams Map<String,String>) : void from class io.undertow.websockets.jsr.ServerWebSocketContainer


    @Test
    public void testSimpleBasic() throws Exception {
        //
        final UndertowClient client = createClient();

        final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
        final CountDownLatch latch = new CountDownLatch(10);
        final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
        try {
            connection.getIoThread().execute(() -> {
                for (int i = 0; i < 10; i++) {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    connection.sendRequest(request, createClientCallback(responses, latch));
                }
            });

            assertTrue(latch.await(10, TimeUnit.SECONDS));

            Assert.assertEquals(10, responses.size());
            for (final ClientResponse response : responses) {
                Assert.assertEquals(message, response.getAttachment(RESPONSE_BODY));
            }
        } finally {
            IoUtils.safeClose(connection);
        }
    }

    @Test
    public void testSimpleBasic() throws Exception {
        //
        final UndertowClient client = createClient();

        final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
        final CountDownLatch latch = new CountDownLatch(10);
        final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
        try {
            connection.getIoThread().execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                        request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                        connection.sendRequest(request, createClientCallback(responses, latch));
                    }
                }

            });

            latch.await(10, TimeUnit.SECONDS);

            Assert.assertEquals(10, responses.size());
            for (final ClientResponse response : responses) {
                Assert.assertEquals(message, response.getAttachment(RESPONSE_BODY));
            }
        } finally {
            IoUtils.safeClose(connection);
        }
    }

Replace Anonymous With Lambda io.undertow.client.http.AjpClientTestCase.testSimpleBasic.execute.new Runnable with () -> {for(int i=0; i < 10; i++){final ClientRequest request=new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE); in method public testSimpleBasic() : void from class io.undertow.client.http.AjpClientTestCase


    @Test
    public void testSendPing() throws Exception {
        //
        final UndertowClient client = createClient();

        final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
        final FutureResult<Boolean> result = new FutureResult<>();
        final CountDownLatch latch = new CountDownLatch(3);
        final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
        assertTrue(connection.isPingSupported());
        try {
            connection.getIoThread().execute(() -> {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    connection.sendRequest(request, createClientCallback(responses, latch));
                    connection.sendPing(new ClientConnection.PingListener() {
                        @Override
                        public void acknowledged() {
                            result.setResult(true);
                            latch.countDown();
                        }

                        @Override
                        public void failed(IOException e) {
                            result.setException(e);
                            latch.countDown();
                        }
                    }, 5, TimeUnit.SECONDS);
                    connection.sendRequest(request, createClientCallback(responses, latch));
                });

            assertTrue(latch.await(10, TimeUnit.SECONDS));

            Assert.assertEquals(2, responses.size());
            assertTrue(result.getIoFuture().get());
            for (final ClientResponse response : responses) {
                Assert.assertEquals(message, response.getAttachment(RESPONSE_BODY));
            }

            //now try a failed ping
            try {
                undertow.stop();

                final FutureResult<Boolean> failResult = new FutureResult<>();
                connection.getIoThread().execute(() -> connection.sendPing(new ClientConnection.PingListener() {
                    @Override
                    public void acknowledged() {
                        failResult.setResult(true);
                    }

                    @Override
                    public void failed(IOException e) {
                        failResult.setException(e);

                    }
                }, 4, TimeUnit.SECONDS));
                try {
                    failResult.getIoFuture().get();
                    Assert.fail("ping should have failed");
                } catch (IOException e) {
                    //ignored
                }

            } finally {
                undertow.start();
            }

        } finally {
            IoUtils.safeClose(connection);
        }
    }

    @Test
    public void testSendPing() throws Exception {
        //
        final UndertowClient client = createClient();

        final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
        final FutureResult<Boolean> result = new FutureResult<>();
        final CountDownLatch latch = new CountDownLatch(3);
        final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
        Assert.assertTrue(connection.isPingSupported());
        try {
            connection.getIoThread().execute(new Runnable() {
                @Override
                public void run() {
                        final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                        request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                        connection.sendRequest(request, createClientCallback(responses, latch));
                        connection.sendPing(new ClientConnection.PingListener() {
                            @Override
                            public void acknowledged() {
                                result.setResult(true);
                                latch.countDown();
                            }

                            @Override
                            public void failed(IOException e) {
                                result.setException(e);
                                latch.countDown();
                            }
                        }, 5, TimeUnit.SECONDS);
                        connection.sendRequest(request, createClientCallback(responses, latch));
                    }
                });

            latch.await(10, TimeUnit.SECONDS);

            Assert.assertEquals(2, responses.size());
            Assert.assertTrue(result.getIoFuture().get());
            for (final ClientResponse response : responses) {
                Assert.assertEquals(message, response.getAttachment(RESPONSE_BODY));
            }

            //now try a failed ping
            try {
                undertow.stop();

                final FutureResult<Boolean> failResult = new FutureResult<>();
                connection.getIoThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        connection.sendPing(new ClientConnection.PingListener() {
                            @Override
                            public void acknowledged() {
                                failResult.setResult(true);
                            }

                            @Override
                            public void failed(IOException e) {
                                failResult.setException(e);

                            }
                        }, 4, TimeUnit.SECONDS);
                    }
                });
                try {
                    failResult.getIoFuture().get();
                    Assert.fail("ping should have failed");
                } catch (IOException e) {
                    //ignored
                }

            } finally {
                undertow.start();
            }

        } finally {
            IoUtils.safeClose(connection);
        }
    }

Replace Anonymous With Lambda io.undertow.client.http.AjpClientTestCase.testSendPing.execute.new Runnable with () -> {final ClientRequest request=new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE); in method public testSendPing() : void from class io.undertow.client.http.AjpClientTestCase


    @Test
    public void testPostRequest() throws Exception {
        //
        final UndertowClient client = createClient();
        final String postMessage = "This is a post request";

        final List<String> responses = new CopyOnWriteArrayList<>();
        final CountDownLatch latch = new CountDownLatch(10);
        final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
        try {
            connection.getIoThread().execute(() -> {
                for (int i = 0; i < 10; i++) {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(POST);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                    connection.sendRequest(request, new ClientCallback<ClientExchange>() {
                        @Override
                        public void completed(ClientExchange result) {
                            new StringWriteChannelListener(postMessage).setup(result.getRequestChannel());
                            result.setResponseListener(new ClientCallback<ClientExchange>() {
                                @Override
                                public void completed(ClientExchange result) {
                                    new StringReadChannelListener(DefaultServer.getBufferPool()) {

                                        @Override
                                        protected void stringDone(String string) {
                                            responses.add(string);
                                            latch.countDown();
                                        }

                                        @Override
                                        protected void error(IOException e) {
                                            e.printStackTrace();
                                            latch.countDown();
                                        }
                                    }.setup(result.getResponseChannel());
                                }

                                @Override
                                public void failed(IOException e) {
                                    e.printStackTrace();
                                    latch.countDown();
                                }
                            });
                        }

                        @Override
                        public void failed(IOException e) {
                            e.printStackTrace();
                            latch.countDown();
                        }
                    });
                }
            });

            assertTrue(latch.await(10, TimeUnit.SECONDS));

            Assert.assertEquals(10, responses.size());
            for (final String response : responses) {
                Assert.assertEquals(postMessage, response);
            }
        } finally {
            IoUtils.safeClose(connection);
        }
    }

    @Test
    public void testPostRequest() throws Exception {
        //
        final UndertowClient client = createClient();
        final String postMessage = "This is a post request";

        final List<String> responses = new CopyOnWriteArrayList<>();
        final CountDownLatch latch = new CountDownLatch(10);
        final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
        try {
            connection.getIoThread().execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(POST);
                        request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                        request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                        connection.sendRequest(request, new ClientCallback<ClientExchange>() {
                            @Override
                            public void completed(ClientExchange result) {
                                new StringWriteChannelListener(postMessage).setup(result.getRequestChannel());
                                result.setResponseListener(new ClientCallback<ClientExchange>() {
                                    @Override
                                    public void completed(ClientExchange result) {
                                        new StringReadChannelListener(DefaultServer.getBufferPool()) {

                                            @Override
                                            protected void stringDone(String string) {
                                                responses.add(string);
                                                latch.countDown();
                                            }

                                            @Override
                                            protected void error(IOException e) {
                                                e.printStackTrace();
                                                latch.countDown();
                                            }
                                        }.setup(result.getResponseChannel());
                                    }

                                    @Override
                                    public void failed(IOException e) {
                                        e.printStackTrace();
                                        latch.countDown();
                                    }
                                });
                            }

                            @Override
                            public void failed(IOException e) {
                                e.printStackTrace();
                                latch.countDown();
                            }
                        });
                    }
                }

            });

            latch.await(10, TimeUnit.SECONDS);

            Assert.assertEquals(10, responses.size());
            for (final String response : responses) {
                Assert.assertEquals(postMessage, response);
            }
        } finally {
            IoUtils.safeClose(connection);
        }
    }

Replace Anonymous With Lambda io.undertow.client.http.AjpClientTestCase.testPostRequest.execute.new Runnable with () -> {for(int i=0; i < 10; i++){final ClientRequest request=new ClientRequest().setMethod(Methods.POST).setPath(POST); in method public testPostRequest() : void from class io.undertow.client.http.AjpClientTestCase


    private static ChannelListener<StreamConnection> wrapOpenListener(final ChannelListener<StreamConnection> listener) {
        if (!single) {
            return listener;
        }
        return (StreamConnection channel) -> {
            channel.getSinkChannel().setConduit(new SingleByteStreamSinkConduit(channel.getSinkChannel().getConduit(), 10000));
            channel.getSourceChannel().setConduit(new SingleByteStreamSourceConduit(channel.getSourceChannel().getConduit(), 10000));
            listener.handleEvent(channel);
        };
    }

    private static ChannelListener<StreamConnection> wrapOpenListener(final ChannelListener<StreamConnection> listener) {
        if (!single) {
            return listener;
        }
        return new ChannelListener<StreamConnection>() {
            @Override
            public void handleEvent(StreamConnection channel) {
                channel.getSinkChannel().setConduit(new SingleByteStreamSinkConduit(channel.getSinkChannel().getConduit(), 10000));
                channel.getSourceChannel().setConduit(new SingleByteStreamSourceConduit(channel.getSourceChannel().getConduit(), 10000));
                listener.handleEvent(channel);
            }
        };
    }

Replace Anonymous With Lambda io.undertow.testutils.DefaultServer.wrapOpenListener.new ChannelListener<StreamConnection> with (channel) -> {channel.getSinkChannel().setConduit(new SingleByteStreamSinkConduit(channel.getSinkChannel().getConduit(),10000)); in method private wrapOpenListener(listener ChannelListener<StreamConnection>) : ChannelListener<StreamConnection> from class io.undertow.testutils.DefaultServer


                    @Override
                    public void onMessage(String message) {
                        session.getAsyncRemote().sendText(message, result -> {
                            sendResult.set(result);
                            if (result.getException() != null) {
                                latch2.setException(new IOException(result.getException()));
                            } else {
                                latch2.setResult(null);
                            }
                        });
                    }

                    @Override
                    public void onMessage(String message) {
                        session.getAsyncRemote().sendText(message, new SendHandler() {
                            @Override
                            public void onResult(SendResult result) {
                                sendResult.set(result);
                                if (result.getException() != null) {
                                    latch2.setException(new IOException(result.getException()));
                                } else {
                                    latch2.setResult(null);
                                }
                            }
                        });
                    }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.JsrWebSocketServer07Test.testTextByCompletion.TestEndPoint.testTextByCompletion.onOpen.addMessageHandler.new MessageHandler.Whole<String>.onMessage.sendText.new SendHandler with result -> {sendResult.set(result); in method public onMessage(message String) : void from class io.undertow.websockets.jsr.test.JsrWebSocketServer07Test.testTextByCompletion.TestEndPoint.testTextByCompletion.onOpen.addMessageHandler.new MessageHandler.Whole<String>


                    @Override
                    public void onMessage(final byte[] message) {
                        DefaultServer.getWorker().execute(() -> {
                            try {
                                OutputStream out = session.getBasicRemote().getSendStream();
                                out.write(message);
                                out.flush();
                                out.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                cause.set(e);
                                latch.setException(e);
                            }
                        });
                    }

                    @Override
                    public void onMessage(final byte[] message) {
                        DefaultServer.getWorker().execute(new Runnable() {
                            @Override
                            public void run() {

                                try {
                                    OutputStream out = session.getBasicRemote().getSendStream();
                                    out.write(message);
                                    out.flush();
                                    out.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    cause.set(e);
                                    latch.setException(e);
                                }
                            }
                        });
                    }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.JsrWebSocketServer07Test.testBinaryWithByteArrayUsingStream.TestEndPoint.testBinaryWithByteArrayUsingStream.onOpen.addMessageHandler.new MessageHandler.Whole<byte[]>.onMessage.execute.new Runnable with () -> {tryOutputStream out=session.getBasicRemote().getSendStream(); in method public onMessage(message byte[]) : void from class io.undertow.websockets.jsr.test.JsrWebSocketServer07Test.testBinaryWithByteArrayUsingStream.TestEndPoint.testBinaryWithByteArrayUsingStream.onOpen.addMessageHandler.new MessageHandler.Whole<byte[]>


                    @Override
                    public void onMessage(final String message) {
                        DefaultServer.getWorker().execute(() -> {
                            try {
                                Writer writer = session.getBasicRemote().getSendWriter();
                                writer.write(message);
                                writer.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                cause.set(e);
                                latch.setException(e);
                            }
                        });
                    }

                    @Override
                    public void onMessage(final String message) {
                        DefaultServer.getWorker().execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Writer writer = session.getBasicRemote().getSendWriter();
                                    writer.write(message);
                                    writer.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    cause.set(e);
                                    latch.setException(e);
                                }
                            }
                        });
                    }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.JsrWebSocketServer07Test.testTextUsingWriter.TestEndPoint.testTextUsingWriter.onOpen.addMessageHandler.new MessageHandler.Whole<String>.onMessage.execute.new Runnable with () -> {tryWriter writer=session.getBasicRemote().getSendWriter(); in method public onMessage(message String) : void from class io.undertow.websockets.jsr.test.JsrWebSocketServer07Test.testTextUsingWriter.TestEndPoint.testTextUsingWriter.onOpen.addMessageHandler.new MessageHandler.Whole<String>


                @Override
                public Principal getUserPrincipal() {
                    return () -> "wrapped";
                }

                @Override
                public Principal getUserPrincipal() {
                    return new Principal() {
                        @Override
                        public String getName() {
                            return "wrapped";
                        }
                    };
                }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.security.WebsocketBasicAuthTestCase.WrapperFilter.doFilter.doFilter.new HttpServletRequestWrapper.getUserPrincipal.new Principal with () -> "wrapped" in method public getUserPrincipal() : Principal from class io.undertow.websockets.jsr.test.security.WebsocketBasicAuthTestCase.WrapperFilter.doFilter.doFilter.new HttpServletRequestWrapper


        @Override
        public void run() {
            session.getAsyncRemote().sendText("t-" + thread + "-m-" + count.get(), result -> {
                if (!result.isOK()) {
                    try {
                        result.getException().printStackTrace();
                        session.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (count.incrementAndGet() != NUM_REQUESTS) {
                    executor.submit(SendRunnable.this);
                } else {
                    executor.submit(() -> {
                        session.getAsyncRemote().sendText("close");
                    });
                }
            });
        }

        @Override
        public void run() {
            session.getAsyncRemote().sendText("t-" + thread + "-m-" + count.get(), new SendHandler() {
                @Override
                public void onResult(SendResult result) {
                    if (!result.isOK()) {
                        try {
                            result.getException().printStackTrace();
                            session.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if (count.incrementAndGet() != NUM_REQUESTS) {
                        executor.submit(SendRunnable.this);
                    } else {
                        executor.submit(new Runnable() {
                            @Override
                            public void run() {
                                session.getAsyncRemote().sendText("close");
                            }
                        });
                    }
                }
            });
        }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.stress.WebsocketStressTestCase.SendRunnable.run.sendText.new SendHandler with result -> {if(!result.isOK()){tryresult.getException().printStackTrace(); in method public run() : void from class io.undertow.websockets.jsr.test.stress.WebsocketStressTestCase.SendRunnable


    @Test
    public void webSocketStringStressTestCase() throws Exception {
        List<CountDownLatch> latches = new ArrayList<>();
        for (int i = 0; i < NUM_THREADS; ++i) {
            final CountDownLatch latch = new CountDownLatch(1);
            latches.add(latch);
            final Session session = deployment.connectToServer(new Endpoint() {
                @Override
                public void onOpen(Session session, EndpointConfig config) {
                }

                @Override
                public void onClose(Session session, CloseReason closeReason) {
                    latch.countDown();
                }

                @Override
                public void onError(Session session, Throwable thr) {
                    latch.countDown();
                }
            }, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
            final int thread = i;
            executor.submit(() -> {
                try {
                    executor.submit(new SendRunnable(session, thread, executor));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });

        }
        for (CountDownLatch future : latches) {
            assertTrue(future.await(40, TimeUnit.SECONDS));
        }
        for (int t = 0; t < NUM_THREADS; ++t) {
            for (int i = 0; i < NUM_REQUESTS; ++i) {
                String msg = "t-" + t + "-m-" + i;
                assertTrue(msg, StressEndpoint.MESSAGES.remove(msg));
            }
        }
        assertEquals(0, StressEndpoint.MESSAGES.size());
    }

    @Test
    public void webSocketStringStressTestCase() throws Exception {
        List<CountDownLatch> latches = new ArrayList<>();
        for (int i = 0; i < NUM_THREADS; ++i) {
            final CountDownLatch latch = new CountDownLatch(1);
            latches.add(latch);
            final Session session = deployment.connectToServer(new Endpoint() {
                @Override
                public void onOpen(Session session, EndpointConfig config) {
                }

                @Override
                public void onClose(Session session, CloseReason closeReason) {
                    latch.countDown();
                }

                @Override
                public void onError(Session session, Throwable thr) {
                    latch.countDown();
                }
            }, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
            final int thread = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        executor.submit(new SendRunnable(session, thread, executor));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

        }
        for (CountDownLatch future : latches) {
            future.await(40, TimeUnit.SECONDS);
        }
        for (int t = 0; t < NUM_THREADS; ++t) {
            for (int i = 0; i < NUM_REQUESTS; ++i) {
                String msg = "t-" + t + "-m-" + i;
                Assert.assertTrue(msg, StressEndpoint.MESSAGES.remove(msg));
            }
        }
        Assert.assertEquals(0, StressEndpoint.MESSAGES.size());
    }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.stress.WebsocketStressTestCase.webSocketStringStressTestCase.submit.new Runnable with () -> {tryexecutor.submit(new SendRunnable(session,thread,executor)); in method public webSocketStringStressTestCase() : void from class io.undertow.websockets.jsr.test.stress.WebsocketStressTestCase


    @Test
    public void testConnectionClosedOnPause() throws Exception {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicReference<String> message = new AtomicReference<>();
        WebSocketChannel channel = WebSocketClient.connectionBuilder(DefaultServer.getWorker(), DefaultServer.getBufferPool(), new URI(DefaultServer.getDefaultServerURL() + "/"))
                .connect().get();
        channel.getReceiveSetter().set(receivingChannel -> {
            try {
                StreamSourceFrameChannel res = receivingChannel.receive();
                if(res == null) {
                    return;
                }
                if (res.getType() == WebSocketFrameType.CLOSE) {
                    message.set("closed");
                    done.countDown();
                }
                Channels.drain(res, Long.MAX_VALUE);
            } catch (IOException e) {
                if(message.get() == null) {
                    e.printStackTrace();
                    message.set("error");
                    done.countDown();
                }
            }
        });
        channel.resumeReceives();
        Assert.assertTrue(channel.isOpen());
        Thread.sleep(500);
        serverContainer.pause(null);
        try {
            Assert.assertTrue(done.await(10, TimeUnit.SECONDS));
            Assert.assertEquals("closed", message.get());
        } finally {
            serverContainer.resume();
        }
    }

    @Test
    public void testConnectionClosedOnPause() throws Exception {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicReference<String> message = new AtomicReference<>();
        WebSocketChannel channel = WebSocketClient.connectionBuilder(DefaultServer.getWorker(), DefaultServer.getBufferPool(), new URI(DefaultServer.getDefaultServerURL() + "/"))
                .connect().get();
        channel.getReceiveSetter().set(new ChannelListener<WebSocketChannel>() {
            @Override
            public void handleEvent(WebSocketChannel channel) {
                try {
                    StreamSourceFrameChannel res = channel.receive();
                    if(res == null) {
                        return;
                    }
                    if (res.getType() == WebSocketFrameType.CLOSE) {
                        message.set("closed");
                        done.countDown();
                    }
                    Channels.drain(res, Long.MAX_VALUE);
                } catch (IOException e) {
                    if(message.get() == null) {
                        e.printStackTrace();
                        message.set("error");
                        done.countDown();
                    }
                }
            }
        });
        channel.resumeReceives();
        Assert.assertTrue(channel.isOpen());
        Thread.sleep(500);
        serverContainer.pause(null);
        try {
            Assert.assertTrue(done.await(10, TimeUnit.SECONDS));
            Assert.assertEquals("closed", message.get());
        } finally {
            serverContainer.resume();
        }
    }

Replace Anonymous With Lambda io.undertow.websockets.jsr.test.suspendresume.SuspendResumeTestCase.testConnectionClosedOnPause.set.new ChannelListener<WebSocketChannel> with receivingChannel -> {tryStreamSourceFrameChannel res=receivingChannel.receive(); in method public testConnectionClosedOnPause() : void from class io.undertow.websockets.jsr.test.suspendresume.SuspendResumeTestCase


    @Override
    public String readAttribute(HttpServerExchange exchange) {
        SSLSessionInfo ssl = exchange.getConnection().getSslSessionInfo();
        if(ssl == null) {
            return null;
        }
        Certificate[] certificates;
        try {
            certificates = ssl.getPeerCertificates();
            if(certificates.length > 0) {
                return Certificates.toPem(certificates[0]);
            }
            return null;
        } catch (SSLPeerUnverifiedException
                | CertificateEncodingException
                | RenegotiationRequiredException e) {
            return null;
        }
    }

    @Override
    public String readAttribute(HttpServerExchange exchange) {
        SSLSessionInfo ssl = exchange.getConnection().getSslSessionInfo();
        if(ssl == null) {
            return null;
        }
        X509Certificate[] certificates;
        try {
            certificates = ssl.getPeerCertificateChain();
            if(certificates.length > 0) {
                return Certificates.toPem(certificates[0]);
            }
            return null;
        } catch (SSLPeerUnverifiedException e) {
            return null;
        } catch (CertificateEncodingException e) {
            return null;
        } catch (RenegotiationRequiredException e) {
            return null;
        }
    }

Merge Catch [catch(SSLPeerUnverifiedException e), catch(CertificateEncodingException e), catch(RenegotiationRequiredException e)] to catch(SSLPeerUnverifiedException|CertificateEncodingException|RenegotiationRequiredException e) in method public readAttribute(exchange HttpServerExchange) : String from class io.undertow.attribute.SslClientCertAttribute


    /**
     * This message should not be compressed as it is too small
     *
     * @throws IOException
     */
    @Test
    public void testSmallMessagePredicateDoesNotCompress() throws IOException {

        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "deflate");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(0, header.length);
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        }
    }

    /**
     * This message should not be compressed as it is too small
     *
     * @throws IOException
     */
    @Test
    public void testSmallMessagePredicateDoesNotCompress() throws IOException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        try {
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "deflate");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(0, header.length);
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public testSmallMessagePredicateDoesNotCompress() : void from class io.undertow.server.handlers.encoding.DeflateContentEncodingTestCase


    public void runTest(final String theMessage) throws IOException {

        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {//by default it has gzip enabled
            message = theMessage;
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "deflate");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            assert result.getEntity() instanceof DecompressingEntity; //no other nice way to be sure we get back gzipped content
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals(theMessage, body);
        }
    }

    public void runTest(final String theMessage) throws IOException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        try {
            message = theMessage;
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "deflate");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals("deflate", header[0].getValue());
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals(theMessage, body);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public runTest(theMessage String) : void from class io.undertow.server.handlers.encoding.DeflateContentEncodingTestCase


    /**
     * This message should not be compressed as it is too small
     *
     * @throws IOException
     */
    @Test
    public void testSmallMessagePredicateDoesNotCompress() throws IOException {

        try (CloseableHttpClient client = HttpClientBuilder.create().build()){
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "gzip");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(0, header.length);
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        }
    }

    /**
     * This message should not be compressed as it is too small
     *
     * @throws IOException
     */
    @Test
    public void testSmallMessagePredicateDoesNotCompress() throws IOException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        try {
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "gzip");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(0, header.length);
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public testSmallMessagePredicateDoesNotCompress() : void from class io.undertow.server.handlers.encoding.GzipContentEncodingSimpleObjectPoolTestCase


    @Test
    public void testAcceptIdentity() throws IOException {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()){
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "identity;q=1, *;q=0");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(1, header.length);
            Assert.assertEquals("identity", header[0].getValue());
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        }
    }

    @Test
    public void testAcceptIdentity() throws IOException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        try {
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "identity;q=1, *;q=0");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(1, header.length);
            Assert.assertEquals("identity", header[0].getValue());
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public testAcceptIdentity() : void from class io.undertow.server.handlers.encoding.GzipContentEncodingSimpleObjectPoolTestCase


    public void runTest(final String theMessage) throws IOException {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()){
            message = theMessage;
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "gzip");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            assert result.getEntity() instanceof DecompressingEntity; //no other nice way to be sure we get back gzipped content
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals(theMessage, body);
        }
    }

    public void runTest(final String theMessage) throws IOException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        try {
            message = theMessage;
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "gzip");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals("gzip", header[0].getValue());
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals(theMessage, body);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public runTest(theMessage String) : void from class io.undertow.server.handlers.encoding.GzipContentEncodingSimpleObjectPoolTestCase


    /**
     * This message should not be compressed as it is too small
     *
     * @throws java.io.IOException
     */
    @Test
    public void testSmallMessagePredicateDoesNotCompress() throws IOException {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()){
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "gzip");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(0, header.length);
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        }
    }

    /**
     * This message should not be compressed as it is too small
     *
     * @throws java.io.IOException
     */
    @Test
    public void testSmallMessagePredicateDoesNotCompress() throws IOException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        try {
            message = "Hi";
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, "gzip");
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(0, header.length);
            final String body = HttpClientUtils.readResponse(result);
            Assert.assertEquals("Hi", body);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public testSmallMessagePredicateDoesNotCompress() : void from class io.undertow.server.handlers.encoding.GzipContentEncodingTestCase


    public void runTest(final String theMessage, String encoding) throws IOException {
        try (CloseableHttpClient client = HttpClientBuilder.create().disableContentCompression().build()){
            message = theMessage;
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/encode");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, encoding);
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(encoding, header[0].getValue());
            byte[] body = HttpClientUtils.readRawResponse(result);

            HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/decode");
            post.setEntity(new ByteArrayEntity(body));
            post.addHeader(Headers.CONTENT_ENCODING_STRING, encoding);

            result = client.execute(post);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            String sb = HttpClientUtils.readResponse(result);
            Assert.assertEquals(theMessage.length(), sb.length());
            Assert.assertEquals(theMessage, sb);

        }
    }

    public void runTest(final String theMessage, String encoding) throws IOException {
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            message = theMessage;
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/encode");
            get.setHeader(Headers.ACCEPT_ENCODING_STRING, encoding);
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
            Assert.assertEquals(encoding, header[0].getValue());
            byte[] body = HttpClientUtils.readRawResponse(result);

            HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/decode");
            post.setEntity(new ByteArrayEntity(body));
            post.addHeader(Headers.CONTENT_ENCODING_STRING, encoding);

            result = client.execute(post);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            String sb = HttpClientUtils.readResponse(result);
            Assert.assertEquals(theMessage.length(), sb.length());
            Assert.assertEquals(theMessage, sb);

        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().disableContentCompression().build()) in method public runTest(theMessage String, encoding String) : void from class io.undertow.server.handlers.encoding.RequestContentEncodingTestCase


    @Test
    public void testFileIsCompressed() throws IOException, InterruptedException {
        String fileName = "hello.html";
        Path f = tmpDir.resolve(fileName);
        Files.write(f, "hello world".getBytes());
        try (CloseableHttpClient client = HttpClientBuilder.create().build()){
            for (int i = 0; i < 3; ++i) {
                HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/" + fileName);
                CloseableHttpResponse result = client.execute(get);
                Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                String response = HttpClientUtils.readResponse(result);
                Assert.assertEquals("hello world", response);
                assert result.getEntity() instanceof DecompressingEntity; //no other nice way to be sure we get back gzipped content
                result.close();
            }
            Files.write(f, "modified file".getBytes());

            //if it is serving a cached compressed version what is being served will not change
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/" + fileName);
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            String response = HttpClientUtils.readResponse(result);
            Assert.assertEquals("hello world", response);
            assert result.getEntity() instanceof DecompressingEntity; //no other nice way to be sure we get back gzipped content

        }
    }

    @Test
    public void testFileIsCompressed() throws IOException, InterruptedException {
        ContentEncodingHttpClient client = new ContentEncodingHttpClient();
        String fileName = "hello.html";
        Path f = tmpDir.resolve(fileName);
        Files.write(f, "hello world".getBytes());
        try {
            for (int i = 0; i < 3; ++i) {
                HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/" + fileName);
                HttpResponse result = client.execute(get);
                Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                String response = HttpClientUtils.readResponse(result);
                Assert.assertEquals("hello world", response);
                Assert.assertEquals("deflate", result.getHeaders(Headers.CONTENT_ENCODING_STRING)[0].getValue());
            }
            Files.write(f, "modified file".getBytes());

            //if it is serving a cached compressed version what is being served will not change
            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/" + fileName);
            HttpResponse result = client.execute(get);
            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            String response = HttpClientUtils.readResponse(result);
            Assert.assertEquals("hello world", response);
            Assert.assertEquals("deflate", result.getHeaders(Headers.CONTENT_ENCODING_STRING)[0].getValue());

        } finally {
            client.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient client=HttpClientBuilder.create().build()) in method public testFileIsCompressed() : void from class io.undertow.server.handlers.file.ContentEncodedResourceTestCase


    @Test
    public void testContentEncodedResource() throws IOException, URISyntaxException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        TestHttpClient client = new TestHttpClient();
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
            DefaultServer.setRootHandler(new CanonicalPathHandler()
                    .setNext(new PathHandler()
                            .addPrefixPath("/path", new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gz"))
                                    .setDirectoryListingEnabled(true))));

            //assert response without compression
            final String plainResponse = assertResponse(client.execute(get), false);

            //assert compressed response, that doesn't exists, so returns plain
            assertResponse(compClient.execute(get), false, plainResponse);

            //generate compressed resource with extension .gz
            generatePreCompressedResource("gz");

            //assert compressed response that was pre compressed
            assertResponse(compClient.execute(get), true, plainResponse, "gz");

        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    @Test
    public void testContentEncodedResource() throws IOException, URISyntaxException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        TestHttpClient client = new TestHttpClient();
        ContentEncodingHttpClient compClient = new ContentEncodingHttpClient();
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        try {
            DefaultServer.setRootHandler(new CanonicalPathHandler()
                    .setNext(new PathHandler()
                            .addPrefixPath("/path", new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gz"))
                                    .setDirectoryListingEnabled(true))));

            //assert response without compression
            final String plainResponse = assertResponse(client.execute(get), false);

            //assert compressed response, that doesn't exists, so returns plain
            assertResponse(compClient.execute(get), false, plainResponse);

            //generate compressed resource with extension .gz
            generatePreCompressedResource("gz");

            //assert compressed response that was pre compressed
            assertResponse(compClient.execute(get), true, plainResponse, "gz");

        } finally {
            client.getConnectionManager().shutdown();
            compClient.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient compClient=HttpClientBuilder.create().build()) in method public testContentEncodedResource() : void from class io.undertow.server.handlers.file.PreCompressedResourceTestCase


    @Test
    public void testCorrectResourceSelected() throws IOException, URISyntaxException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        TestHttpClient client = new TestHttpClient();
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
            DefaultServer.setRootHandler(new CanonicalPathHandler()
                    .setNext(new PathHandler()
                            .addPrefixPath("/path", new EncodingHandler(new ContentEncodingRepository()
                                            .addEncodingHandler("gzip", new GzipEncodingProvider(), 50, Predicates.truePredicate()))
                                    .setNext(new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gzip"))
                                            .setDirectoryListingEnabled(true)))
                    ));

            //assert response without compression
            final String plainResponse = assertResponse(client.execute(get), false);

            //assert compressed response generated by filter
            assertResponse(compClient.execute(get), true, plainResponse);

            //generate resources
            generatePreCompressedResource("gzip");
            generatePreCompressedResource("nonsense");
            generatePreCompressedResource("gzip.nonsense");

            //assert compressed response that was pre compressed
            assertResponse(compClient.execute(get), true, plainResponse, "gzip");

        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    @Test
    public void testCorrectResourceSelected() throws IOException, URISyntaxException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        TestHttpClient client = new TestHttpClient();
        ContentEncodingHttpClient compClient = new ContentEncodingHttpClient();
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        try {
            DefaultServer.setRootHandler(new CanonicalPathHandler()
                    .setNext(new PathHandler()
                            .addPrefixPath("/path", new EncodingHandler(new ContentEncodingRepository()
                                            .addEncodingHandler("gzip", new GzipEncodingProvider(), 50, Predicates.truePredicate()))
                                    .setNext(new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gzip"))
                                            .setDirectoryListingEnabled(true)))
                    ));

            //assert response without compression
            final String plainResponse = assertResponse(client.execute(get), false);

            //assert compressed response generated by filter
            assertResponse(compClient.execute(get), true, plainResponse);

            //generate resources
            generatePreCompressedResource("gzip");
            generatePreCompressedResource("nonsense");
            generatePreCompressedResource("gzip.nonsense");

            //assert compressed response that was pre compressed
            assertResponse(compClient.execute(get), true, plainResponse, "gzip");

        } finally {
            client.getConnectionManager().shutdown();
            compClient.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient compClient=HttpClientBuilder.create().build()) in method public testCorrectResourceSelected() : void from class io.undertow.server.handlers.file.PreCompressedResourceTestCase