/*
 * Copyright 2014 - 2017 Cognizant Technology Solutions
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cognizant.cognizantits.engine.reporting.sync;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.simple.JSONObject;
import static org.testng.Assert.*;
import org.testng.annotations.*;

public class BasicHttpClientTest {

    private JSONObject getArgs;
    private static final int PORT = 3210;
    private static LocalServer server;

    public BasicHttpClientTest() throws Exception {

    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        new Thread(() -> {
            try {
                server = new LocalServer(PORT);
                server.start();
            } catch (Exception ex) {
                Logger.getLogger(BasicHttpClientTest.class.getName())
                        .log(Level.SEVERE, ex.getMessage(), ex);
            }
        }).start();
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        server.stop();
    }

    @BeforeMethod
    public void setUpMethod() throws Exception {
        getArgs = new JSONObject();
        getArgs.put("data", "vola");
        getArgs.put("empty", "");
        getArgs.put("special", "^\\d{5,}$");
    }

    /**
     * Test of Get method, of class BasicHttpClient.
     * @throws java.lang.Exception
     */
    @Test(enabled = false,description = "http-get of remote address")
    public void testGetHttp() throws Exception {
        System.out.println("Get-http");
        URL targetUrl = new URL("http://postman-echo.com/get");
        BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon");        
        JSONObject result = instance.Get(targetUrl, getArgs.toJSONString());
        assertEquals(result.get("args"), getArgs);
    }

    /**
     * Test of Get method, of class BasicHttpClient.
     * @throws java.lang.Exception
     */
    @Test(enabled = false,description = "https-get of remote address")
    public void testGetHttps() throws Exception {
        System.out.println("Get-https");
        URL targetUrl = new URL("https://postman-echo.com/get");
        BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon");
        JSONObject result = instance.Get(targetUrl, getArgs.toJSONString());
        assertEquals(result.get("args"), getArgs);
    }

    /**
     * Test of Get method, of class BasicHttpClient.
     * @throws java.lang.Exception
     */
    @Test(enabled = false,description = "http-get of local address")
    public void testGetHttpLocal() throws Exception {
        System.out.println("Get-http-local");
        URL targetUrl = new URL("http://127.0.0.1:" + PORT);
        BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon");        
        JSONObject result = instance.Get(targetUrl, "data", "vola");
        assertEquals(result.toString(), "{\"data\":\"vola\"}");
    }

    public static class LocalServer {

        private final ServerSocket server;
        private final AtomicBoolean stopped = new AtomicBoolean(false);

        public LocalServer(int port) throws Exception {
            server = new ServerSocket(port);
        }

        public void start() throws Exception {
            System.out.println("local server started");
            while (!stopped.get()) {
                try (Socket client = server.accept();
                        OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));) {
                    String req = in.readLine();
                    System.out.println(req);
                    JSONObject res = new JSONObject();
                    Matcher m = Pattern.compile("GET /\\?(.*?)=(.*?) HTTP/1.1").matcher(req);
                    if (m.find()) {
                        res.put(m.group(1), m.group(2));
                    }
                    writer.write("HTTP/1.1 200 OK\nContent-Type: text/html\n\n");
                    writer.write(res.toJSONString());
                    writer.flush();
                }
            }
        }

        public void stop() throws Exception {
            System.out.println("local server stopping");
            stopped.set(true);
        }
    }

}

@@ -1249,43 +1249,8 @@
     
-private static LocalServer server;%0A
 %0A   
@@ -1310,522 +1310,8 @@
  %7D%0A%0A
-    @BeforeClass%0A    public static void setUpClass() throws Exception %7B%0A        new Thread(() -%3E %7B%0A            try %7B%0A                server = new LocalServer(PORT);%0A                server.start();%0A            %7D catch (Exception ex) %7B%0A                Logger.getLogger(BasicHttpClientTest.class.getName())%0A                        .log(Level.SEVERE, ex.getMessage(), ex);%0A            %7D%0A        %7D).start();%0A    %7D%0A%0A    @AfterClass%0A    public static void tearDownClass() throws Exception %7B%0A        server.stop();%0A    %7D%0A%0A
     
@@ -3120,32 +3120,32 @@
 data%22, %22vola%22);%0A
+
         assertEq
@@ -3203,1407 +3203,6 @@
  %7D%0A%0A
-    public static class LocalServer %7B%0A%0A        private final ServerSocket server;%0A        private final AtomicBoolean stopped = new AtomicBoolean(false);%0A%0A        public LocalServer(int port) throws Exception %7B%0A            server = new ServerSocket(port);%0A        %7D%0A%0A        public void start() throws Exception %7B%0A            System.out.println(%22local server started%22);%0A            while (!stopped.get()) %7B%0A                try (Socket client = server.accept();%0A                        OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());%0A                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));) %7B%0A                    String req = in.readLine();%0A                    System.out.println(req);%0A                    JSONObject res = new JSONObject();%0A                    Matcher m = Pattern.compile(%22GET /%5C%5C?(.*?)=(.*?) HTTP/1.1%22).matcher(req);%0A                    if (m.find()) %7B%0A                        res.put(m.group(1), m.group(2));%0A                    %7D%0A                    writer.write(%22HTTP/1.1 200 OK%5CnContent-Type: text/html%5Cn%5Cn%22);%0A                    writer.write(res.toJSONString());%0A                    writer.flush();%0A                %7D%0A            %7D%0A        %7D%0A%0A        public void stop() throws Exception %7B%0A            System.out.println(%22local server stopping%22);%0A            stopped.set(true);%0A        %7D%0A    %7D%0A%0A
 %7D%0A

Update BasicHttpClientTest.java