package com.sun.identity.protocol;

import com.sun.identity.shared.configuration.SystemPropertiesManager;
import com.sun.identity.shared.debug.Debug;
import java.lang.reflect.InvocationTargetException;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;

public class AMURLStreamHandlerFactory implements URLStreamHandlerFactory {
   private static final Debug DEBUG = Debug.getInstance("amComm");
   private static String prot_handler_string = SystemPropertiesManager.get("java.protocol.handler.pkgs", null);

   @Override
   public URLStreamHandler createURLStreamHandler(String protocol) {
      String method = "AMURLStreamHandlerFactory.createURLStreamHandler ";
      if (protocol.equalsIgnoreCase("https") && prot_handler_string != null) {
         try {
            return (URLStreamHandler)Class.forName(prot_handler_string).getDeclaredConstructor().newInstance();
         } catch (ClassNotFoundException e) {
            DEBUG.error(method + "Failed to find protocol handler class ", e);
         } catch (InstantiationException | InvocationTargetException | NoSuchMethodException e) {
            DEBUG.error(method + "Failed to instantiate protocol handler class ", e);
         } catch (IllegalAccessException e) {
            DEBUG.error(method + "Invalid access for protocol handler class ", e);
         }
      }

      return null;
   }

   static {
      if (prot_handler_string != null) {
         prot_handler_string = prot_handler_string + ".https.Handler";
      }

      if (DEBUG.messageEnabled()) {
         DEBUG.message("Configured Protocol Handler : " + prot_handler_string);
      }
   }
}
