public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {
        HeaderMap headers = exchange.getRequestHeaders();
        String[] origins = headers.get(Headers.ORIGIN).toArray();
        if(logger.isTraceEnabled()) logger.trace("origins from the request header = " + Arrays.toString(origins) + " allowedOrigins = " + allowedOrigins);
        if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
            for (String allowedOrigin : allowedOrigins) {
                for (String origin : origins) {
                    if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {
                        return allowedOrigin;
                    }
                }
            }
        }
        String allowedOrigin = defaultOrigin(exchange);
        if(logger.isTraceEnabled()) logger.trace("allowedOrigin from the exchange = " + allowedOrigin);
        for (String origin : origins) {
            if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {
                return allowedOrigin;
            }
        }
        logger.debug("Request rejected due to HOST/ORIGIN mis-match.");
        ResponseCodeHandler.HANDLE_403.handleRequest(exchange);
        return null;
    }
@Test
    public void testMatchOrigin() throws Exception {
        HeaderMap headerMap = new HeaderMap();
        headerMap.add(HOST, "localhost:80");
        headerMap.add(ORIGIN, "http://localhost");
        HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10);
        exchange.setRequestScheme("http");
        exchange.setRequestMethod(HttpString.EMPTY);
        Collection<String> allowedOrigins = null;
        assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
        allowedOrigins = Collections.singletonList("http://www.example.com:9990");
        //Default origin
        assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
        headerMap.clear();
        headerMap.add(HOST, "localhost:80");
        headerMap.add(ORIGIN, "http://www.example.com:9990");
        assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://www.example.com:9990"));
        headerMap.clear();
        headerMap.add(HOST, "localhost:80");
        headerMap.add(ORIGIN, "http://www.example.com");
        assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is(nullValue()));
        headerMap.addAll(ORIGIN, Arrays.asList("http://localhost:7080", "http://www.example.com:9990", "http://localhost"));
        allowedOrigins = Arrays.asList("http://localhost", "http://www.example.com:9990");
        assertThat(CorsUtil.matchOrigin(exchange, allowedOrigins), is("http://localhost"));
    }