/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.extension.jar.internal.handler;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.ComponentAnnotationLoader;
import org.xwiki.component.annotation.ComponentDeclaration;
import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.internal.StackingComponentEventManager;
import org.xwiki.component.internal.multi.ComponentManagerManager;
import org.xwiki.component.manager.ComponentEventManager;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.extension.ExtensionException;
import org.xwiki.extension.InstallException;
import org.xwiki.extension.LocalExtension;
import org.xwiki.extension.LocalExtensionFile;
import org.xwiki.extension.UninstallException;
import org.xwiki.extension.handler.internal.AbstractExtensionHandler;

@Component("jar")
@Singleton
public class JarExtensionHandler extends AbstractExtensionHandler implements Initializable
{
    @Inject
    private ComponentManagerManager componentManagerManager;

    @Inject
    private JarExtensionClassLoader jarExtensionClassLoader;

    @Inject
    private Logger logger;

    private ComponentAnnotationLoader jarLoader;

    @Override
    public void initialize() throws InitializationException
    {
        this.jarLoader = new ComponentAnnotationLoader();
    }

    @Override
    public void initialize(LocalExtension localExtension, String namespace) throws ExtensionException
    {
        install(localExtension, namespace, null);
    }

    private static URL getExtensionURL(LocalExtension localExtension) throws MalformedURLException
    {
        return new File(localExtension.getFile().getAbsolutePath()).toURI().toURL();
    }

    @Override
    public void install(LocalExtension localExtension, String namespace, Map<String, ? > extra) throws InstallException
    {
        ExtensionURLClassLoader classLoader = this.jarExtensionClassLoader.getURLClassLoader(namespace, true);

        // 1) load jar into classloader
        try {
            classLoader.addURL(getExtensionURL(localExtension));
        } catch (MalformedURLException e) {
            throw new InstallException("Failed to load jar file", e);
        }

        // 2) load and register components
        loadComponents(localExtension.getFile(), classLoader, namespace);
    }

    @Override
    public void uninstall(LocalExtension localExtension, String namespace, Map<String, ? > extra)
        throws UninstallException
    {
        ExtensionURLClassLoader classLoader = this.jarExtensionClassLoader.getURLClassLoader(namespace, false);

        if (namespace == null || classLoader.getWiki().equals(namespace)) {
            // unregister components
            unloadComponents(localExtension.getFile(), classLoader, namespace);

            // The ClassLoader(s) will be replaced and reloaded at the end of the job
            // @see org.xwiki.extension.jar.internal.handler.JarExtensionJobFinishedListener
        }
    }

    private void loadComponents(LocalExtensionFile jarFile, ExtensionURLClassLoader classLoader, String namespace)
        throws InstallException
    {
        try {
            List<ComponentDeclaration> componentDeclarations = getDeclaredComponents(jarFile);

            if (componentDeclarations == null) {
                this.logger.debug("[{}] does not contain any component", jarFile.getName());
                return;
            }

            ComponentManager componentManager = this.componentManagerManager.getComponentManager(namespace, true);

            ComponentEventManager componentEventManager = componentManager.getComponentEventManager();

            // Make sure to send events only when the extension is fully ready
            StackingComponentEventManager stackingComponentEventManager = null;
            try {
                if (componentEventManager instanceof StackingComponentEventManager) {
                    stackingComponentEventManager = (StackingComponentEventManager) componentEventManager;
                } else {
                    stackingComponentEventManager = new StackingComponentEventManager();
                    componentManager.setComponentEventManager(stackingComponentEventManager);
                }
                stackingComponentEventManager.shouldStack(true);

                this.jarLoader.initialize(componentManager, classLoader, componentDeclarations);
            } finally {
                if (stackingComponentEventManager != null) {
                    if (componentEventManager != stackingComponentEventManager) {
                        componentManager.setComponentEventManager(componentEventManager);
                    }
                    stackingComponentEventManager.shouldStack(false);
                    stackingComponentEventManager.flushEvents();
                }
            }
        } catch (Exception e) {
            throw new InstallException("Failed to load jar file components", e);
        }
    }

    private List<ComponentDeclaration> getDeclaredComponents(LocalExtensionFile jarFile) throws IOException
    {
        ZipInputStream zis = new ZipInputStream(jarFile.openStream());

        List<ComponentDeclaration> componentDeclarations = null;
        List<ComponentDeclaration> componentOverrideDeclarations = null;

        try {
            for (ZipEntry entry = zis.getNextEntry(); entry != null
                && (componentDeclarations == null || componentOverrideDeclarations == null); entry = zis.getNextEntry()) {
                if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_LIST)) {
                    componentDeclarations = this.jarLoader.getDeclaredComponents(zis);
                } else if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_OVERRIDE_LIST)) {
                    componentOverrideDeclarations = this.jarLoader.getDeclaredComponents(zis);
                }
            }
        } finally {
            zis.close();
        }

        // Merge all overrides found with a priority of 0. This is purely for backward compatibility since the
        // override files is now deprecated.
        if (componentOverrideDeclarations != null) {
            if (componentDeclarations == null) {
                componentDeclarations = new ArrayList<ComponentDeclaration>();
            }
            for (ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations) {
                componentDeclarations.add(new ComponentDeclaration(componentOverrideDeclaration
                    .getImplementationClassName(), 0));
            }
        }

        return componentDeclarations;
    }

    private void unloadComponents(LocalExtensionFile jarFile, ExtensionURLClassLoader classLoader, String namespace)
        throws UninstallException
    {
        try {
            List<ComponentDeclaration> componentDeclarations = getDeclaredComponents(jarFile);

            if (componentDeclarations == null) {
                this.logger.debug("[{}] does not contain any component", jarFile.getName());
                return;
            }

            for (ComponentDeclaration componentDeclaration : componentDeclarations) {
                try {
                    for (ComponentDescriptor componentDescriptor : this.jarLoader.getComponentsDescriptors(classLoader
                        .loadClass(componentDeclaration.getImplementationClassName()))) {
                        this.componentManagerManager.getComponentManager(namespace, false).unregisterComponent(
                            componentDescriptor);
                    }
                } catch (ClassNotFoundException e) {
                    this.logger.warn("Can't find any existing component with class [{}]. Ignoring it.",
                        componentDeclaration.getImplementationClassName());
                }
            }
        } catch (Exception e) {
            throw new UninstallException("Failed to unload jar file components", e);
        }
    }
}

@@ -1452,67 +1452,8 @@
 on;%0A
-import org.xwiki.component.descriptor.ComponentDescriptor;%0A
 impo
@@ -8385,761 +8385,154 @@
     
-for (ComponentDeclaration componentDeclaration : componentDeclarations) %7B%0A                try %7B%0A                    for (ComponentDescriptor componentDescriptor : this.jarLoader.getComponentsDescriptors(classLoader%0A                        .loadClass(componentDeclaration.getImplementationClassName()))) %7B%0A                        this.componentManagerManager.getComponentManager(namespace, false).unregisterComponent(%0A                            componentDescriptor);%0A                    %7D%0A                %7D catch (ClassNotFoundException e) %7B%0A                    this.logger.warn(%22Can't find any existing component with class %5B%7B%7D%5D. Ignoring it.%22,%0A                        componentDeclaration.getImplementationClassName());%0A                %7D%0A            %7D
+this.jarLoader.unregister(this.componentManagerManager.getComponentManager(namespace, false), classLoader,%0A                componentDeclarations);
 %0A   

Move from Class to Type as Component role Use new APIs