/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.logging.log4j.util;

import java.net.URL;
import java.security.Permission;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.status.StatusLogger;
import org.osgi.framework.AdaptPermission;
import org.osgi.framework.AdminPermission;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.framework.wiring.BundleWiring;

/**
 * OSGi bundle activator. Used for locating an implementation of
 * {@link org.apache.logging.log4j.spi.LoggerContextFactory} et al. that have corresponding
 * {@code META-INF/log4j-provider.properties} files. As with all OSGi BundleActivator classes, this class is not for
 * public use and is only useful in an OSGi framework environment.
 */
public class Activator implements BundleActivator, SynchronousBundleListener {

    private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();

    private static final Logger LOGGER = StatusLogger.getLogger();

    private static void checkPermission(final Permission permission) {
        if (SECURITY_MANAGER != null) {
            SECURITY_MANAGER.checkPermission(permission);
        }
    }

    private void loadProvider(final Bundle bundle) {
        if (bundle.getState() == Bundle.UNINSTALLED) {
            return;
        }
        try {
            checkPermission(new AdminPermission(bundle, AdminPermission.RESOURCE));
            final URL url = bundle.getEntry(ProviderUtil.PROVIDER_RESOURCE);
            if (url != null) {
                checkPermission(new AdminPermission(bundle, AdminPermission.CLASS));
                checkPermission(new AdaptPermission(BundleWiring.class.getName(), bundle, AdaptPermission.ADAPT));
                ProviderUtil.loadProvider(url, getBundleClassLoader(bundle));
            }
        } catch (final Exception e) {
            LOGGER.warn("Problem checking bundle {} for Log4j 2 provider.", bundle.getSymbolicName(), e);
        }
    }

    private static ClassLoader getBundleClassLoader(Bundle bundle) {
        final BundleWiring wiring = bundle.adapt(BundleWiring.class);
        return wiring.getClassLoader();
    }

    @Override
    public void start(final BundleContext context) throws Exception {
        context.addBundleListener(this);
        final Bundle[] bundles = context.getBundles();
        for (final Bundle bundle : bundles) {
            loadProvider(bundle);
        }
    }

    @Override
    public void stop(final BundleContext context) throws Exception {
        context.removeBundleListener(this);
    }

    @Override
    public void bundleChanged(final BundleEvent event) {
        switch (event.getType()) {
            case BundleEvent.STARTED:
                // FIXME: LogManager won't see this update if it happens after LogManager is loaded
                loadProvider(event.getBundle());
                break;

            default:
                break;
        }
    }

}

@@ -887,16 +887,39 @@
 mission;
+%0Aimport java.util.List;
 %0A%0Aimport
@@ -944,32 +944,90 @@
 g.log4j.Logger;%0A
+import org.apache.logging.log4j.spi.LoggerContextFactory;%0A
 import org.apach
@@ -1355,24 +1355,69 @@
 leListener;%0A
+import org.osgi.framework.wiring.BundleWire;%0A
 import org.o
@@ -2477,717 +2477,718 @@
     
-final URL url = bundle.getEntry(ProviderUtil.PROVIDER_RESOURCE);%0A            if (url != null) %7B%0A                checkPermission(new AdminPermission(bundle, AdminPermission.CLASS));%0A                checkPermission(new AdaptPermission(BundleWiring.class.getName(), bundle, AdaptPermission.ADAPT));%0A                ProviderUtil.loadProvider(url, getBundleClassLoader(bundle));%0A            %7D%0A        %7D catch (final Exception e) %7B%0A            LOGGER.warn(%22Problem checking bundle %7B%7D for Log4j 2 provider.%22, bundle.getSymbolicName(), e);%0A        %7D%0A    %7D%0A%0A    private static ClassLoader getBundleClassLoader(Bundle bundle) %7B%0A        final BundleWiring wiring = bundle.adapt(BundleWiring.class);%0A        return wiring
+checkPermission(new AdaptPermission(BundleWiring.class.getName(), bundle, AdaptPermission.ADAPT));%0A            loadProvider(bundle.adapt(BundleWiring.class));%0A        %7D catch (final SecurityException e) %7B%0A            LOGGER.debug(%22Cannot access bundle %5B%7B%7D%5D contents. Ignoring.%22, bundle.getSymbolicName(), e);%0A        %7D catch (final Exception e) %7B%0A            LOGGER.warn(%22Problem checking bundle %7B%7D for Log4j 2 provider.%22, bundle.getSymbolicName(), e);%0A        %7D%0A    %7D%0A%0A    private void loadProvider(BundleWiring provider) %7B%0A        final List%3CURL%3E urls = provider.findEntries(%22META-INF%22, %22log4j-provider.properties%22, 0);%0A        for (final URL url : urls) %7B%0A            ProviderUtil.loadProvider(url, provider
 .get
@@ -3200,17 +3200,28 @@
 Loader()
-;
+);%0A        %7D
 %0A    %7D%0A%0A
@@ -3296,32 +3296,321 @@
 ows Exception %7B%0A
+        final BundleWiring self = context.getBundle().adapt(BundleWiring.class);%0A        final List%3CBundleWire%3E required = self.getRequiredWires(LoggerContextFactory.class.getName());%0A        for (BundleWire wire : required) %7B%0A            loadProvider(wire.getProviderWiring());%0A        %7D%0A
         context.

Use list of required bundle wires first in Activator to find log4j providers specifying the capability first.