package com.sun.identity.common;

import com.sun.identity.protocol.AMURLStreamHandlerFactory;
import com.sun.identity.shared.configuration.SystemPropertiesManager;
import com.sun.identity.shared.debug.Debug;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

public class HttpURLConnectionManager {
   private static final String URL_READTIMEOUT = "com.sun.identity.url.readTimeout";
   private static final Debug DEBUG = Debug.getInstance("PLLClient");
   private static final AMURLStreamHandlerFactory ST_FACTORY = new AMURLStreamHandlerFactory();
   private static final String PROT_HANDLER_STRING = SystemPropertiesManager.get("java.protocol.handler.pkgs", null);
   private static int readtimeout = 30000;

   public static HttpURLConnection getConnection(URL url) throws IOException {
      String prot = url.getProtocol();
      if (PROT_HANDLER_STRING != null && prot.equalsIgnoreCase("https")) {
         url = URL.of(URI.create(url.toExternalForm()), ST_FACTORY.createURLStreamHandler("https"));
      }

      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      conn.setReadTimeout(readtimeout);
      if (DEBUG.messageEnabled()) {
         DEBUG.message("HttpURLConnectionManager.getConnection: set read timeout to " + readtimeout);
      }

      return conn;
   }

   static {
      String rto = SystemPropertiesManager.get("com.sun.identity.url.readTimeout");
      if (DEBUG.messageEnabled()) {
         DEBUG.message("Configured Protocol Handler : " + PROT_HANDLER_STRING);
      }

      if (rto != null && !rto.isEmpty()) {
         try {
            readtimeout = Integer.parseInt(rto);
            if (DEBUG.messageEnabled()) {
               DEBUG.message("HttpURLConnectionManager.<init>: Set READTIMEOUT to " + readtimeout);
            }
         } catch (Exception e) {
            DEBUG.error("HttpURLConnectionManager.<init>: Fail to read com.sun.identity.url.readTimeout set READTIMEOUT to the default " + readtimeout, e);
         }
      }
   }
}
