/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.knox.gateway.websockets;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.net.URI;
import java.util.Locale;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * A basic test that attempts to test the backend url generated by gateway proxy.
 */
public class WebsocketBackendUrlTest extends WebsocketEchoTestBase {
  private static Server backendServer;
  public static URI backendServerUri;

  public WebsocketBackendUrlTest() {
    super();
  }

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    WebsocketEchoTestBase.setUpBeforeClass();

    backendServer = new Server();
    ServerConnector connector = new ServerConnector(backendServer);
    backendServer.addConnector(connector);

    String host = connector.getHost();
    if (host == null) {
      host = "localhost";
    }
    int port = connector.getLocalPort();
    serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
    backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/testpart/", host, port));
    WebsocketEchoTestBase.setupGatewayConfig(backendServerUri.toString());
  }

  @AfterClass
  public static void tearDownAfterClass() {
    WebsocketEchoTestBase.cleanupFiles();
  }

  /*
   * Test url generated for websocket backend connection
   */
  @Test
  public void testWebsocketBackendUrl() throws Exception {
    URI requestURI = new URI(serverUri.toString() + "gateway/websocket/123foo456bar/channels");
    GatewayWebsocketHandler gwh = new GatewayWebsocketHandler(gatewayConfig, services);
    String backendUrl = gwh.getMatchedBackendURL(requestURI);
    String expectedBackendUrl = backendServerUri.toString() + "channels";
    assertThat(backendUrl, is(expectedBackendUrl));
  }
}
