package cd.casic.ci.process.engine.worker.base;


import cd.casic.ci.process.engine.worker.base.BaseWorker;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName httpWorker
 * @Date: 2025/5/21 20:13
 * @Description:
 */
public abstract class HttpWorker extends BaseWorker {
    public static RestTemplate getRestTemplateWithoutSANCheck() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, KeyStoreException {
        // 创建信任所有证书的SSL上下文
        SSLContext sslContext = SSLContextBuilder.create()
                .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true)
                .build();

        // 配置连接工厂
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(
                        PoolingHttpClientConnectionManagerBuilder.create()
                                .setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
                                        .setSslContext(sslContext)
                                        .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                        .build())
                                .build())
                .build();

        // 创建RestTemplate
        HttpComponentsClientHttpRequestFactory factory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }

    public static void main(String[] args) {
        try {
            RestTemplate restTemplate = getRestTemplateWithoutSANCheck();
            // 示例 POST 请求
            String url = "https://175.6.27.252:30002/openapi/v1/sbom/detect-file";
            String requestBody = "{\"key\": \"value\"}";
            String response = restTemplate.postForObject(url, requestBody, String.class);
            System.out.println("Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
