/*
 * Copyright 2016 NAVER Corp.
 * 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.navercorp.pinpoint.profiler.instrument;

import com.navercorp.pinpoint.exception.PinpointException;
import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author Woonduk Kang(emeroad)
 * @author jaehong.kim
 */
public class URLClassLoaderHandler implements ClassInjector {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();

    private static final Method ADD_URL, LOAD_CLASS;;

    static {
        try {
            ADD_URL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            ADD_URL.setAccessible(true);
        } catch (Exception e) {
            throw new PinpointException("Cannot access URLClassLoader.addURL(URL)", e);
        }
    }
    
    static {
        try {
            LOAD_CLASS = ClassLoader.class.getDeclaredMethod("loadClass", String.class, boolean.class);
            LOAD_CLASS.setAccessible(true);
        } catch (Exception e) {
            throw new PinpointException("Cannot access URLClassLoader.loadClass(class, boolean)", e);
        }
    }    

    private final URL pluginURL;
    private final String pluginURLString;

    public URLClassLoaderHandler(PluginConfig pluginConfig) {
        if (pluginConfig == null) {
            throw new NullPointerException("pluginConfig must not be null");
        }
        this.pluginURL = pluginConfig.getPluginJar();
        this.pluginURLString = pluginURL.toExternalForm();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> Class<? extends T> injectClass(ClassLoader classLoader, String className) {
        try {
            if (classLoader instanceof URLClassLoader) {
                final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
                addPluginURLIfAbsent(urlClassLoader);
                return (Class<T>) urlClassLoader.loadClass(className);
            }
        } catch (Exception e) {
            logger.warn("Failed to load plugin class {} with classLoader {}", className, classLoader, e);
            throw new PinpointException("Failed to load plugin class " + className + " with classLoader " + classLoader, e);
        }
        throw new PinpointException("invalid ClassLoader");
    }

    @Override
    public InputStream getResourceAsStream(ClassLoader targetClassLoader, String classPath) {
        try {
            if (targetClassLoader instanceof URLClassLoader) {
                final URLClassLoader urlClassLoader = (URLClassLoader) targetClassLoader;
                addPluginURLIfAbsent(urlClassLoader);
                return targetClassLoader.getResourceAsStream(classPath);
            }
        } catch (Exception e) {
            logger.warn("Failed to load plugin resource as stream {} with classLoader {}", classPath, targetClassLoader, e);
            return null;
        }
        return null;
    }

    private void addPluginURLIfAbsent(URLClassLoader classLoader) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
        final URL[] urls = classLoader.getURLs();
        if (urls != null) {
            final boolean hasPluginJar = hasPluginJar(urls);
            if (!hasPluginJar) {
                if (isDebug) {
                    logger.debug("add Jar:{}", pluginURLString);
                }
                ADD_URL.invoke(classLoader, pluginURL);
            }
        }
    }

    private boolean hasPluginJar(URL[] urls) {
        for (URL url : urls) {
            // if (url.equals(pluginJarURL)) { fix very slow
            // http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html
            final String externalForm = url.toExternalForm();
            if (pluginURLString.equals(externalForm)) {
                return true;
            }
        }
        return false;
    }
}

@@ -650,342 +650,315 @@
 ort 
-com.navercorp.pinpoint.exception.PinpointException;%0Aimport com.navercorp.pinpoint.profiler.plugin.PluginConfig;%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport java.io.InputStream;%0Aimport java.lang.reflect.InvocationTargetException;%0Aimport java.lang.reflect.Method;%0Aimport java.net.URL;%0Aimport java.net.URLClassLoader
+java.lang.reflect.InvocationTargetException;%0Aimport java.lang.reflect.Method;%0Aimport java.net.URL;%0Aimport java.net.URLClassLoader;%0A%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport com.navercorp.pinpoint.exception.PinpointException;%0Aimport com.navercorp.pinpoint.profiler.plugin.PluginConfig
 ;%0A%0A/
@@ -997,31 +997,8 @@
 ad)%0A
- * @author jaehong.kim%0A
  */%0A
@@ -1139,69 +1139,8 @@
 ());
-%0A    private final boolean isDebug = logger.isDebugEnabled();
 %0A%0A  
@@ -1189,17 +1189,16 @@
 D_CLASS;
-;
 %0A%0A    st
@@ -1807,20 +1807,16 @@
  %7D%0A    %7D
-    
 %0A%0A    pr
@@ -2505,80 +2505,38 @@
     
-addPluginURLIfAbsent(urlClassLoader);%0A                return (Class%3CT%3E) 
+return (Class%3CT%3E)injectClass0(
 urlC
@@ -2541,35 +2541,26 @@
 lClassLoader
-.loadClass(
+, 
 className);%0A
@@ -2917,708 +2917,88 @@
  %7D%0A%0A
-    @Override%0A    public InputStream getResourceAsStream(ClassLoader targetClassLoader, String classPath) %7B%0A        try %7B%0A            if (targetClassLoader instanceof URLClassLoader) %7B%0A                final URLClassLoader urlClassLoader = (URLClassLoader) targetClassLoader;%0A                addPluginURLIfAbsent(urlClassLoader);%0A                return targetClassLoader.getResourceAsStream(classPath);%0A            %7D%0A        %7D catch (Exception e) %7B%0A            logger.warn(%22Failed to load plugin resource as stream %7B%7D with classLoader %7B%7D%22, classPath, targetClassLoader, e);%0A            return null;%0A        %7D%0A        return null;%0A    %7D%0A%0A    private void addPluginURLIfAbsent(URLClassLoader classLoader
+%0A%0A    private Class%3C?%3E injectClass0(URLClassLoader classLoader, String className
 ) th
@@ -3174,32 +3174,33 @@
 urls != null) %7B%0A
+%0A
             fina
@@ -3240,24 +3240,25 @@
 nJar(urls);%0A
+%0A
             
@@ -3282,43 +3282,8 @@
 ) %7B%0A
-                if (isDebug) %7B%0A    
     
@@ -3343,26 +3343,8 @@
 g);%0A
-                %7D%0A
     
@@ -3410,32 +3410,108 @@
      %7D%0A        %7D
+%0A%0A        return (Class%3C?%3E) LOAD_CLASS.invoke(classLoader, className, true);
 %0A    %7D%0A%0A    priv
@@ -3852,24 +3852,25 @@
 nalForm)) %7B%0A
+%0A
             
@@ -3938,10 +3938,12 @@
 ;%0A    %7D%0A
+%0A%0A
 %7D%0A

Fix class loading