/*
 * 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.karaf.shell.packages;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;

@Command(scope = "packages", name = "imports", description = "Display imported packages")
public class ImportsCommand extends PackageCommandSupport {

	@Argument(index = 0, name = "ids", description = "The IDs of bundles to check", required = false, multiValued = true)
    List<Long> ids;

    protected void doExecute(PackageAdmin admin) throws Exception {
        Map<Long, List<ExportedPackage>> packages = new HashMap<Long, List<ExportedPackage>>();
        ExportedPackage[] exported = admin.getExportedPackages((Bundle) null);
        for (ExportedPackage pkg : exported) {
            Bundle[] bundles = pkg.getImportingBundles();
            if (bundles != null) {
                for (Bundle b : bundles) {
                    List<ExportedPackage> p = packages.get(b.getBundleId());
                    if (p == null) {
                        p = new ArrayList<ExportedPackage>();
                        packages.put(b.getBundleId(), p);
                    }
                    p.add(pkg);
                }
            }
        }
        if (ids != null && !ids.isEmpty()) {
            for (long id : ids) {
                Bundle bundle = getBundleContext().getBundle(id);
                if (bundle != null) {
                    printImports(System.out, bundle, packages.get(bundle.getBundleId()));
                } else {
                    System.err.println("Bundle ID " + id + " is invalid.");
                }
            }
        }
        else {
            List<ExportedPackage> pkgs = new ArrayList<ExportedPackage>();
            for (List<ExportedPackage> l : packages.values()) {
                pkgs.addAll(l);
            }
            printImports(System.out, null, pkgs);
        }
    }

    protected void printImports(PrintStream out, Bundle target, List<ExportedPackage> imports) {
        if ((imports != null) && (imports.size() > 0)) {
            for (ExportedPackage p : imports) {
                Bundle bundle = p.getExportingBundle();
                out.print(getBundleName(bundle));
                out.println(": " + p);
            }
        } else {
            out.println(getBundleName(target) + ": No active imported packages.");
        }
    }

    public static String getBundleName(Bundle bundle) {
        if (bundle != null) {
            String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME);
            return (name == null)
                ? "Bundle " + Long.toString(bundle.getBundleId())
                : name + " (" + Long.toString(bundle.getBundleId()) + ")";
        }
        return "[STALE BUNDLE]";
    }

}

@@ -1236,16 +1236,62 @@
 Command;
+%0Aimport org.apache.felix.gogo.commands.Option;
 %0A%0A@Comma
@@ -1573,16 +1573,210 @@
 ng%3E ids;
+%0A%09%0A    @Option(name = %22-i%22, aliases = %7B %22--show-importer%22 %7D, description = %22show the bundle that is importing a package%22, required = false, multiValued = false)%0A    private boolean showImporter;
 %0A%0A    pr
@@ -2948,32 +2948,141 @@
 %0A        else %7B%0A
+            if (showImporter) %7B%0A                printImports(System.out, packages);%0A            %7D else %7B%0A    
             List
@@ -3148,24 +3148,28 @@
             
+    
 for (List%3CEx
@@ -3224,16 +3224,20 @@
         
+   
+ 
 pkgs.add
@@ -3248,34 +3248,42 @@
 l);%0A            
-%7D%0A
+    %7D%0A    
             prin
@@ -3312,24 +3312,827 @@
 ull, pkgs);%0A
+            %7D%0A        %7D%0A    %7D   %0A    %0A    protected void printImports(PrintStream out, Map%3CLong, List%3CExportedPackage%3E%3E imports) %7B%0A        for (Map.Entry%3CLong, List%3CExportedPackage%3E%3E entry : imports.entrySet()) %7B%0A            for (ExportedPackage p : entry.getValue()) %7B%0A                // print bundle that is importing this package%0A                Bundle importer = getBundleContext().getBundle(entry.getKey());%0A                out.print(getBundleName(importer));%0A                out.print(%22 imports: %22);%0A                %0A                // print bundle that is exporting this package%0A                Bundle exporter = p.getExportingBundle();%0A                out.print(getBundleName(exporter));%0A                %0A                // print the package%0A                out.println(%22: %22 + p);%0A            %7D%0A
         %7D%0A  
@@ -4131,24 +4131,28 @@
     %7D%0A    %7D%0A
+    
 %0A    protect

print importer bundle in packages:imports.