Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * 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.felix.webconsole.internal.core;
  
  
  import java.io.*;
  import java.util.*;
  
  
  import org.json.*;
  import  org.osgi.framework.*;
  import  org.osgi.service.cm.ConfigurationAdmin;
  import  org.osgi.service.component.ComponentConstants;
  import  org.osgi.service.log.LogService;
  import  org.osgi.service.packageadmin.ExportedPackage;
  import  org.osgi.service.packageadmin.PackageAdmin;
  import  org.osgi.service.startlevel.StartLevel;


The BundlesServlet TODO
  
  public class BundlesServlet extends BaseWebConsolePlugin implements ConfigurationPrinter
  {
  
      public static final String NAME = "bundles";
  
      public static final String LABEL = "Bundles";
  
      public static final String BUNDLE_ID = "bundleId";
  
      // bootdelegation property entries. wildcards are converted to package
      // name prefixes. whether an entry is a wildcard or not is set as a flag
      // in the bootPkgWildcards array.
      // see #activate and #isBootDelegated
      private String[] bootPkgs;
  
      // a flag for each entry in bootPkgs indicating whether the respective
      // entry was declared as a wildcard or not
      // see #activate and #isBootDelegated
      private boolean[] bootPkgWildcards;
  
      private ServiceRegistration configurationPrinter;
  
      public void activate( BundleContext bundleContext )
      {
          super.activatebundleContext );
  
          // bootdelegation property parsing from Apache Felix R4SearchPolicyCore
          String bootDelegation = bundleContext.getProperty( Constants.FRAMEWORK_BOOTDELEGATION );
          bootDelegation = ( bootDelegation == null ) ? "java.*" : bootDelegation + ",java.*";
          StringTokenizer st = new StringTokenizerbootDelegation" ," );
           = new String[st.countTokens()];
           = new boolean[.];
          for ( int i = 0; i < .i++ )
          {
              bootDelegation = st.nextToken();
              if ( bootDelegation.endsWith"*" ) )
              {
                  [i] = true;
                  bootDelegation = bootDelegation.substring( 0, bootDelegation.length() - 1 );
              }
              [i] = bootDelegation;
          }
  
           = bundleContext.registerService( .thisnull );
      }
  
  
      public void deactivate()
      {
          if (  != null )
          {
              .unregister();
               = null;
         }
 
         super.deactivate();
     }
 
 
     public String getLabel()
     {
         return ;
     }
 
 
     public String getTitle()
     {
         return ;
     }
 
 
     //---------- ConfigurationPrinter
 
     public void printConfigurationPrintWriter pw )
     {
         try
         {
             StringWriter w = new StringWriter();
             writeJSONwnullnullnulltrue );
             String jsonString = w.toString();
             JSONObject json = new JSONObjectjsonString );
 
             pw.println"Status: " + json.get"status" ) );
             pw.println();
 
             JSONArray data = json.getJSONArray"data" );
             for ( int i = 0; i < data.length(); i++ )
             {
                 if ( !data.isNulli ) )
                 {
                     JSONObject bundle = data.getJSONObjecti );
 
                     pw.println( MessageFormat.format"Bundle {0} - {1} {2} (state: {3})"new Object[]
                         { bundle.get"id" ), bundle.get"name" ), bundle.get"version" ), bundle.get"state" ) } ) );
 
                     JSONArray props = bundle.getJSONArray"props" );
                     for ( int pi = 0; pi < props.length(); pi++ )
                     {
                         if ( !props.isNullpi ) )
                         {
                             JSONObject entry = props.getJSONObjectpi );
 
                             pw.print"    " + entry.get"key" ) + ": " );
 
                             Object entryValue = entry.get"value" );
                             if ( entryValue instanceof JSONArray )
                             {
                                 pw.println();
                                 JSONArray entryArray = ( JSONArray ) entryValue;
                                 for ( int ei = 0; ei < entryArray.length(); ei++ )
                                 {
                                     if ( !entryArray.isNullei ) )
                                     {
                                         pw.println"        " + entryArray.getei ) );
                                     }
                                 }
                             }
                             else
                             {
                                 pw.printlnentryValue );
                             }
                         }
                     }
 
                     pw.println();
                 }
             }
         }
         catch ( Exception e )
         {
             getLog().log( LogService.LOG_ERROR, "Problem rendering Bundle details for configuration status"e );
         }
     }
 
 
     //---------- BaseWebConsolePlugin
 
     protected void doGetHttpServletRequest requestHttpServletResponse response ) throws ServletException,
         IOException
     {
         final RequestInfo reqInfo = new RequestInfo(request);
         if ( "upload".equals(reqInfo.pathInfo) )
         {
             super.doGet(requestresponse);
             return;
         }
         if ( reqInfo.bundle == null && reqInfo.bundleRequested )
         {
             response.sendError(404);
             return;
         }
         if ( reqInfo.extension.equals("json")  )
         {
             final String pluginRoot = ( String ) request.getAttribute. );
             final String servicesRoot = getServicesRootrequest );
             this.renderJSON(responsereqInfo.bundlepluginRootservicesRoot);
 
             // nothing more to do
             return;
         }
 
         super.doGetrequestresponse );
     }
 
     protected void doPostHttpServletRequest reqHttpServletResponse resp ) throws ServletExceptionIOException
     {
         final RequestInfo reqInfo = new RequestInfo(req);
         if ( reqInfo.bundle == null && reqInfo.bundleRequested ) {
             resp.sendError(404);
             return;
         }
 
         boolean success = false;
 
         final String action = req.getParameter"action" );
 
         Bundle bundle = getBundlereq.getPathInfo() );
 
         if ( bundle != null )
         {
             if ( action == null )
             {
                 success = true;
             }
             else if ( "start".equalsaction ) )
             {
                 // start bundle
                 success = true;
                 try
                 {
                     bundle.start();
                 }
                 catch ( BundleException be )
                 {
                     getLog().log( LogService.LOG_ERROR, "Cannot start"be );
                 }
             }
             else if ( "stop".equalsaction ) )
             {
                 // stop bundle
                 success = true;
                 try
                 {
                     bundle.stop();
                 }
                 catch ( BundleException be )
                 {
                     getLog().log( LogService.LOG_ERROR, "Cannot stop"be );
                 }
             }
             else if ( "refresh".equalsaction ) )
             {
                 // refresh bundle wiring
                 refreshbundle );
                 success = true;
             }
             else if ( "update".equalsaction ) )
             {
                 // update the bundle
                 updatebundle );
                 success = true;
             }
             else if ( "uninstall".equalsaction ) )
             {
                 // uninstall bundle
                 success = true;
                 try
                 {
                     bundle.uninstall();
                     bundle = null// bundle has gone !
                 }
                 catch ( BundleException be )
                 {
                     getLog().log( LogService.LOG_ERROR, "Cannot uninstall"be );
                 }
             }
         }
 
         if ( "refreshPackages".equalsaction ) )
         {
             getPackageAdmin().refreshPackages( null );
             success = true;
         }
 
         if ( success )
         {
             // let's wait a little bit to give the framework time
             // to process our request
             try {
                 Thread.sleep(800);
             } catch (InterruptedException e) {
                 // we ignore this
             }
             final String pluginRoot = ( String ) req.getAttribute. );
             final String servicesRoot = getServicesRootreq );
             this.renderJSON(respnullpluginRootservicesRoot);
         }
         else
         {
             super.doPostreqresp );
         }
     }
 
     private String getServicesRoot(HttpServletRequest request)
     {
         return ( ( String ) request.getAttribute. ) ) +
             "/" + . + "/";
     }
 
     private Bundle getBundleString pathInfo )
     {
         // only use last part of the pathInfo
         pathInfo = pathInfo.substringpathInfo.lastIndexOf'/' ) + 1 );
 
         // assume bundle Id
         try
         {
             final long bundleId = Long.parseLongpathInfo );
             if ( bundleId >= 0 )
             {
                 return getBundleContext().getBundle( bundleId );
             }
         }
         catch ( NumberFormatException nfe )
         {
             // check if this follows the pattern {symbolic-name}[:{version}]
             final int pos = pathInfo.indexOf(':');
             final String symbolicName;
             final String version;
             if ( pos == -1 ) {
                 symbolicName = pathInfo;
                 version = null;
             } else {
                 symbolicName = pathInfo.substring(0, pos);
                 version = pathInfo.substring(pos+1);
             }
 
             // search
             final Bundle[] bundles = getBundleContext().getBundles();
             for(int i=0; i<bundles.length; i++)
             {
                 final Bundle bundle = bundles[i];
                 // check symbolic name first
                 if ( symbolicName.equals(bundle.getSymbolicName()) )
                 {
                     if ( version == null || version.equals(bundle.getHeaders().get(Constants.BUNDLE_VERSION)) )
                     {
                         return bundle;
                     }
                 }
             }
         }
 
 
         return null;
     }
 
 
     private void appendBundleInfoCountfinal StringBuffer bufString msgint count )
     {
         buf.append(count);
         buf.append(" bundle");
         if ( count != 1 )
             buf.append's' );
         buf.append(' ');
         buf.append(msg);
     }
 
     protected void renderContentHttpServletRequest requestHttpServletResponse response ) throws IOException
     {
         // get request info from request attribute
         final RequestInfo reqInfo = getRequestInfo(request);
         final PrintWriter pw = response.getWriter();
 
         final String appRoot = ( String ) request.getAttribute. );
 
         Util.startScriptpw );
         pw.println"var imgRoot = '" + appRoot + "/res/imgs';");
         pw.println"var startLevel = " + getStartLevel().getInitialBundleStartLevel() + ";");
         pw.println"var drawDetails = " + reqInfo.bundleRequested + ";");
         pw.println"var currentBundle = " + (reqInfo.bundleRequested ? String.valueOf(reqInfo.bundle.getBundleId()) : "null") + ";");
         Util.endScriptpw );
 
         Util.script(pwappRoot"bundles.js");
 
         if ( "upload".equals(reqInfo.pathInfo) )
         {
             renderUploadForm(pwappRoot);
         }
         else
         {
             pw.println"<div id='plugin_content'/>");
             Util.startScriptpw );
             pw.print"renderBundles(");
             final String pluginRoot = ( String ) request.getAttribute. );
             final String servicesRoot = getServicesRoot ( request );
             writeJSON(pwreqInfo.bundlepluginRootservicesRoot );
             pw.println(");" );
             Util.endScriptpw );
         }
     }
 
     private void renderUploadFormfinal PrintWriter pwfinal String appRoot ) throws IOException
     {
         Util.script(pwappRoot"jquery.multifile-1.4.6.min.js");
         pw.println(" <div id='plugin_content'><div class='contentheader'>Upload / Install Bundles</div>");
         pw.println"<form method='post' enctype='multipart/form-data' action='../'>");
         pw.println"<input type='hidden' name='action' value='install'/>");
         pw.println"<div class='contentline'><div class='contentleft'>Start Bundle</div><div class='contentright'><input class='checkradio' type='checkbox' name='bundlestart' value='start'/></div></div>");
         pw.println"<div class='contentline'><div class='contentleft'>Start Level</div><div class='contentright'><input class='input' type='input' name='bundlestartlevel' value='" + getStartLevel().getInitialBundleStartLevel() + "' size='4'/></div></div>");
         pw.println"<div class='contentline'><input class='fileinput multi' accept='jar' type='file' name='bundlefile'/></div>");
         pw.println"<div class='contentline'><input type='submit' value='Install or Update'/></div>");
         pw.println"</form></div");
     }
 
     private void renderJSONfinal HttpServletResponse responsefinal Bundle bundlefinal String pluginRootfinal String servicesRoot )
         throws IOException
     {
         response.setContentType"application/json" );
         response.setCharacterEncoding"UTF-8" );
 
         final PrintWriter pw = response.getWriter();
         writeJSON(pwbundlepluginRootservicesRoot);
     }
 
 
     private void writeJSONfinal PrintWriter pwfinal Bundle bundlefinal String pluginRootfinal String servicesRoot )
         throws IOException
     {
         writeJSONpwbundlepluginRootservicesRootfalse );
     }
 
 
     private void writeJSONfinal Writer pwfinal Bundle bundlefinal String pluginRoot,
         final String servicesRootfinal boolean fullDetails ) throws IOException
     {
         final Bundle[] allBundles = this.getBundles();
         final String statusLine = this.getStatusLine(allBundles);
         final Bundle[] bundles = ( bundle != null ) ? new Bundle[]
             { bundle } : allBundles;
         Util.sortbundles );
 
         final JSONWriter jw = new JSONWriterpw );
 
         try
         {
             jw.object();
 
             jw.key"status" );
             jw.valuestatusLine );
 
             jw.key"data" );
 
             jw.array();
 
             for ( int i = 0; i < bundles.length; i++ )
             {
                 bundleInfojwbundles[i], fullDetails || bundle != nullpluginRootservicesRoot );
             }
 
             jw.endArray();
 
             jw.endObject();
 
         }
         catch ( JSONException je )
         {
             throw new IOExceptionje.toString() );
         }
 
     }
 
     private String getStatusLine(final Bundle[] bundles)
     {
         int active = 0, installed = 0, resolved = 0, fragments = 0;
         for ( int i = 0; i < bundles.length; i++ )
         {
             switch ( bundles[i].getState() )
             {
                 case Bundle.ACTIVE:
                     active++;
                     break;
                 case Bundle.INSTALLED:
                     installed++;
                     break;
                 case Bundle.RESOLVED:
                     if ( isFragmentBundlebundles[i] ) )
                     {
                         fragments++;
                     }
                     else
                     {
                         resolved++;
                     }
                     break;
             }
         }
         final StringBuffer buffer = new StringBuffer();
         buffer.append("Bundle information: ");
         appendBundleInfoCount(buffer"in total"bundles.length);
         if ( active == bundles.length || active + fragments == bundles.length )
         {
             buffer.append(" - all ");
             appendBundleInfoCount(buffer"active."bundles.length);
         }
         else
         {
             if ( active != 0 )
             {
                 buffer.append(", ");
                 appendBundleInfoCount(buffer"active"active);
             }
             if ( fragments != 0 )
             {
                 buffer.append(", ");
                 appendBundleInfoCount(buffer"active fragments"fragments);
             }
             if ( resolved != 0 )
             {
                 buffer.append(", ");
                 appendBundleInfoCount(buffer"resolved"resolved);
             }
             if ( installed != 0 )
             {
                 buffer.append(", ");
                 appendBundleInfoCount(buffer"installed"installed);
             }
             buffer.append('.');
         }
         return buffer.toString();
     }
 
     private void bundleInfoJSONWriter jw, Bundle bundleboolean detailsfinal String pluginRootfinal String servicesRoot )
         throws JSONException
     {
         jw.object();
         jw.key"id" );
         jw.valuebundle.getBundleId() );
         jw.key"name" );
         jw.value( Util.getNamebundle ) );
         jw.key"state" );
         jw.valuetoStateStringbundle ) );
         jw.key"version" );
         jw.value( Util.getHeaderValue(bundle, Constants.BUNDLE_VERSION) );
         jw.key"symbolicName" );
         jw.value( Util.getHeaderValue(bundle, Constants.BUNDLE_SYMBOLICNAME) );
 
         jw.key"actions" );
         jw.array();
 
         if ( bundle.getBundleId() != 0 )
         {
             if ( hasStart(bundle) )
             {
                 actionjwhasStartbundle ), "start""Start""start" );
             }
             else
             {
                 actionjwhasStopbundle ), "stop""Stop""stop" );
             }
             actionjwtrue"refresh""Refresh Package Imports""refresh" );
             actionjwtrue"update""Update""update" );
             actionjwhasUninstallbundle ), "uninstall""Uninstall""delete" );
         }
         jw.endArray();
 
         if ( details )
         {
             bundleDetailsjwbundlepluginRootservicesRoot );
         }
 
         jw.endObject();
     }
 
 
     protected Bundle[] getBundles()
     {
         return getBundleContext().getBundles();
     }
 
 
     private String toStateStringfinal Bundle bundle )
     {
         switch ( bundle.getState() )
         {
             case Bundle.INSTALLED:
                 return "Installed";
             case Bundle.RESOLVED:
                 if ( isFragmentBundle(bundle) )
                 {
                     return "Fragment";
                 }
                 return "Resolved";
             case Bundle.STARTING:
                 return "Starting";
             case Bundle.ACTIVE:
                 return "Active";
             case Bundle.STOPPING:
                 return "Stopping";
             case Bundle.UNINSTALLED:
                 return "Uninstalled";
             default:
                 return "Unknown: " + bundle.getState();
         }
     }
 
 
     private void actionJSONWriter jwboolean enabledString opString opLabelString image ) throws JSONException
     {
         jw.object();
         jw.key"enabled" ).valueenabled );
         jw.key"name" ).valueopLabel );
         jw.key"link" ).valueop );
         jw.key"image" ).valueimage );
         jw.endObject();
     }
 
     private boolean isFragmentBundle( Bundle bundle)
     {
         return getPackageAdmin().getBundleType( bundle ) == PackageAdmin.BUNDLE_TYPE_FRAGMENT;
     }
 
     private boolean hasStart( Bundle bundle )
     {
         if ( isFragmentBundle(bundle) )
         {
             return false;
         }
         return bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.RESOLVED;
     }
 
 
     private boolean hasStop( Bundle bundle )
     {
         if ( isFragmentBundle(bundle) )
         {
             return false;
         }
         return bundle.getState() == Bundle.ACTIVE;
     }
 
 
     private boolean hasUninstall( Bundle bundle )
     {
         return bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.RESOLVED
             || bundle.getState() == Bundle.ACTIVE;
 
     }
 
 
     private void bundleDetailsJSONWriter jw, Bundle bundlefinal String pluginRootfinal String servicesRoot)
         throws JSONException
     {
         Dictionary headers = bundle.getHeaders();
 
         jw.key"props" );
         jw.array();
         keyValjw"Symbolic Name"bundle.getSymbolicName() );
         keyValjw"Version"headers.get( Constants.BUNDLE_VERSION ) );
         keyValjw"Bundle Location"bundle.getLocation() );
         keyValjw"Last Modification"new Datebundle.getLastModified() ) );
 
         String docUrl = ( String ) headers.get( Constants.BUNDLE_DOCURL );
         if ( docUrl != null )
         {
             keyValjw"Bundle Documentation"docUrl );
         }
 
         keyValjw"Vendor"headers.get( Constants.BUNDLE_VENDOR ) );
         keyValjw"Copyright"headers.get( Constants.BUNDLE_COPYRIGHT ) );
         keyValjw"Description"headers.get( Constants.BUNDLE_DESCRIPTION ) );
 
         keyValjw"Start Level"getStartLevelbundle ) );
 
         keyValjw"Bundle Classpath"headers.get( Constants.BUNDLE_CLASSPATH ) );
 
         listFragmentInfojwbundlepluginRoot );
 
         if ( bundle.getState() == Bundle.INSTALLED )
         {
             listImportExportsUnresolvedjwbundlepluginRoot );
         }
         else
         {
             listImportExportjwbundlepluginRoot );
         }
 
         listServicesjwbundleservicesRoot );
 
         listHeadersjwbundle );
 
         jw.endArray();
     }
 
 
     private Integer getStartLevel( Bundle bundle )
     {
         StartLevel sl = getStartLevel();
         return ( sl != null ) ? new Integersl.getBundleStartLevel( bundle ) ) : null;
     }
 
 
     private void listImportExportJSONWriter jw, Bundle bundlefinal String pluginRoot ) throws JSONException
     {
         PackageAdmin packageAdmin = getPackageAdmin();
         if ( packageAdmin == null )
         {
             return;
         }
 
         Map usingBundles = new TreeMap();
 
         ExportedPackage[] exports = packageAdmin.getExportedPackages( bundle );
         if ( exports != null && exports.length > 0 )
         {
             // do alphabetical sort
             Arrays.sortexportsnew Comparator()
             {
                 public int compare( ExportedPackage p1, ExportedPackage p2 )
                 {
                     return p1.getName().compareTo( p2.getName() );
                 }
 
 
                 public int compareObject o1Object o2 )
                 {
                     return compare( ( ExportedPackage ) o1, ( ExportedPackage ) o2 );
                 }
             } );
 
             JSONArray val = new JSONArray();
             for ( int j = 0; j < exports.length; j++ )
             {
                 ExportedPackage export = exports[j];
                 collectExportvalexport.getName(), export.getVersion() );
                 Bundle[] ubList = export.getImportingBundles();
                 if ( ubList != null )
                 {
                     for ( int i = 0; i < ubList.length; i++ )
                     {
                         Bundle ub = ubList[i];
                         usingBundles.putub.getSymbolicName(), ub );
                     }
                 }
             }
             keyValjw"Exported Packages"val );
         }
         else
         {
             keyValjw"Exported Packages""None" );
         }
 
         exports = packageAdmin.getExportedPackages( ( Bundle ) null );
         if ( exports != null && exports.length > 0 )
         {
             // collect import packages first
             final List imports = new ArrayList();
             for ( int i = 0; i < exports.length; i++ )
             {
                 final ExportedPackage ep = exports[i];
                 final Bundle[] importers = ep.getImportingBundles();
                 for ( int j = 0; importers != null && j < importers.length; j++ )
                 {
                     if ( importers[j].getBundleId() == bundle.getBundleId() )
                     {
                         imports.addep );
 
                         break;
                     }
                 }
             }
             // now sort
             JSONArray val = new JSONArray();
             if ( imports.size() > 0 )
             {
                 final ExportedPackage[] packages = ( ExportedPackage[] ) imports.toArraynew ExportedPackage[imports
                     .size()] );
                 Arrays.sortpackagesnew Comparator()
                 {
                     public int compare( ExportedPackage p1, ExportedPackage p2 )
                     {
                         return p1.getName().compareTo( p2.getName() );
                     }
 
 
                     public int compareObject o1Object o2 )
                     {
                         return compare( ( ExportedPackage ) o1, ( ExportedPackage ) o2 );
                     }
                 } );
                 // and finally print out
                 for ( int i = 0; i < packages.length; i++ )
                 {
                     ExportedPackage ep = packages[i];
                     collectImportvalep.getName(), ep.getVersion(), falseeppluginRoot );
                 }
             }
             else
             {
                 // add description if there are no imports
                 val.put"None" );
             }
 
             keyValjw"Imported Packages"val );
         }
 
         if ( !usingBundles.isEmpty() )
         {
             JSONArray val = new JSONArray();
             for ( Iterator ui = usingBundles.values().iterator(); ui.hasNext(); )
             {
                 Bundle usingBundle = ( Bundle ) ui.next();
                 val.putgetBundleDescriptorusingBundlepluginRoot ) );
             }
             keyValjw"Importing Bundles"val );
         }
     }
 
 
     private void listImportExportsUnresolvedJSONWriter jw, Bundle bundlefinal String pluginRoot ) throws JSONException
     {
         Dictionary dict = bundle.getHeaders();
 
         String target = ( String ) dict.get( Constants.EXPORT_PACKAGE );
         if ( target != null )
         {
             R4Package[] pkgs = R4Package.parseImportOrExportHeadertarget );
             if ( pkgs != null && pkgs.length > 0 )
             {
                 // do alphabetical sort
                 Arrays.sortpkgsnew Comparator()
                 {
                     public int compareR4Package p1R4Package p2 )
                     {
                         return p1.getName().compareTop2.getName() );
                     }
 
 
                     public int compareObject o1Object o2 )
                     {
                         return compare( ( R4Package ) o1, ( R4Package ) o2 );
                     }
                 } );
 
                 JSONArray val = new JSONArray();
                 for ( int i = 0; i < pkgs.lengthi++ )
                 {
                     R4Export export = new R4Exportpkgs[i] );
                     collectExportvalexport.getName(), export.getVersion() );
                 }
                 keyValjw"Exported Packages"val );
             }
             else
             {
                 keyValjw"Exported Packages""None" );
             }
         }
 
         target = ( String ) dict.get( Constants.IMPORT_PACKAGE );
         if ( target != null )
         {
             R4Package[] pkgs = R4Package.parseImportOrExportHeadertarget );
             if ( pkgs != null && pkgs.length > 0 )
             {
                 Map imports = new TreeMap();
                 for ( int i = 0; i < pkgs.lengthi++ )
                 {
                     R4Package pkg = pkgs[i];
                     imports.putpkg.getName(), new R4Importpkg ) );
                 }
 
                 // collect import packages first
                 final Map candidates = new HashMap();
                 PackageAdmin packageAdmin = getPackageAdmin();
                 if ( packageAdmin != null )
                 {
                     ExportedPackage[] exports = packageAdmin.getExportedPackages( ( Bundle ) null );
                     if ( exports != null && exports.length > 0 )
                     {
 
                         for ( int i = 0; i < exports.length; i++ )
                         {
                             final ExportedPackage ep = exports[i];
 
                             R4Import imp = ( R4Import ) imports.getep.getName() );
                             if ( imp != null && imp.isSatisfiedtoR4Exportep ) ) )
                             {
                                 candidates.putep.getName(), ep );
                             }
                         }
                     }
                 }
 
                 // now sort
                 JSONArray val = new JSONArray();
                 if ( imports.size() > 0 )
                 {
                     for ( Iterator ii = imports.values().iterator(); ii.hasNext(); )
                     {
                         R4Import r4Import = ( R4Import ) ii.next();
                         ExportedPackage ep = ( ExportedPackage ) candidates.getr4Import.getName() );
 
                         // if there is no matching export, check whether this
                         // bundle has the package, ignore the entry in this case
                         if ( ep == null )
                         {
                             String path = r4Import.getName().replace'.''/' );
                             if ( bundle.getEntry( path ) != null )
                             {
                                 continue;
                             }
                         }
 
                         collectImportvalr4Import.getName(), r4Import.getVersion(), r4Import.isOptional(), eppluginRoot );
                     }
                 }
                 else
                 {
                     // add description if there are no imports
                     val.put"None" );
                 }
 
                 keyValjw"Imported Packages"val );
             }
         }
     }
 
     private String getServiceID(ServiceReference reffinal String servicesRoot) {
         String id = ref.getProperty( Constants.SERVICE_ID ).toString();
         StringBuffer val = new StringBuffer();
 
         if ( servicesRoot != null ) {
             val.append"<a href='" ).appendservicesRoot ).appendid ).append"'>" );
             val.appendid );
             val.append"</a>" );
             return val.toString();
         } else {
             return id;
         }
     }
 
 
     private void listServicesJSONWriter jw, Bundle bundlefinal String servicesRoot ) throws JSONException
     {
         ServiceReference[] refs = bundle.getRegisteredServices();
         if ( refs == null || refs.length == 0 )
         {
             return;
         }
 
         for ( int i = 0; i < refs.length; i++ )
         {
 
 
             String key = "Service ID " + getServiceIDrefs[i], servicesRoot );
 
             JSONArray val = new JSONArray();
 
             appendPropertyvalrefs[i], Constants.OBJECTCLASS, "Types" );
             appendPropertyvalrefs[i], Constants.SERVICE_PID, "Service PID" );
             appendPropertyvalrefs[i], "org.apache.felix.karaf.features.configKey""Feature PID" );
             appendPropertyvalrefs[i], ConfigurationAdmin.SERVICE_FACTORYPID, "Factory PID" );
             appendPropertyvalrefs[i], ComponentConstants.COMPONENT_NAME, "Component Name" );
             appendPropertyvalrefs[i], ComponentConstants.COMPONENT_ID, "Component ID" );
             appendPropertyvalrefs[i], ComponentConstants.COMPONENT_FACTORY, "Component Factory" );
             appendPropertyvalrefs[i], Constants.SERVICE_DESCRIPTION, "Description" );
             appendPropertyvalrefs[i], Constants.SERVICE_VENDOR, "Vendor" );
 
             keyValjwkeyval);
         }
     }
 
 
     private void listHeadersJSONWriter jw, Bundle bundle ) throws JSONException
     {
         JSONArray val = new JSONArray();
 
         Dictionary headers = bundle.getHeaders();
         Enumeration he = headers.keys();
         while ( he.hasMoreElements() )
         {
             Object header = he.nextElement();
             String value = String.valueOf(headers.getheader ));
             // Package headers may be long, support line breaking by
             // ensuring blanks after comma and semicolon.
             value = value.replaceAll"([;,])""$1 " );
             val.putheader + ": " + value );
         }
 
         keyValjw"Manifest Headers"val );
     }
 
 
    private void listFragmentInfofinal JSONWriter jwfinal Bundle bundlefinal String pluginRoot )
        throws JSONException
    {
        if ( isFragmentBundlebundle ) )
        {
            Bundle[] hostBundles = getPackageAdmin().getHosts( bundle );
            if ( hostBundles != null )
            {
                JSONArray val = new JSONArray();
                for ( int i = 0; i < hostBundles.length; i++ )
                {
                    val.putgetBundleDescriptorhostBundles[i], pluginRoot ) );
                }
                keyValjw"Host Bundles"val );
            }
        }
        else
        {
            Bundle[] fragmentBundles = getPackageAdmin().getFragments( bundle );
            if ( fragmentBundles != null )
            {
                JSONArray val = new JSONArray();
                for ( int i = 0; i < fragmentBundles.length; i++ )
                {
                    val.putgetBundleDescriptorfragmentBundles[i], pluginRoot ) );
                }
                keyValjw"Fragments Attached"val );
            }
        }
    }
    private void appendPropertyJSONArray array, ServiceReference refString nameString label )
    {
        StringBuffer dest = new StringBuffer();
        Object value = ref.getProperty( name );
        if ( value instanceof Object[] )
        {
            Object[] values = ( Object[] ) value;
            dest.appendlabel ).append": " );
            for ( int j = 0; j < values.lengthj++ )
            {
                if ( j > 0 )
                    dest.append", " );
                dest.appendvalues[j] );
            }
            array.put(dest.toString());
        }
        else if ( value != null )
        {
            dest.appendlabel ).append": " ).appendvalue );
            array.put(dest.toString());
        }
    }
    private void keyValJSONWriter jwString keyObject value ) throws JSONException
    {
        if ( key != null && value != null )
        {
            jw.object();
            jw.key"key" );
            jw.valuekey );
            jw.key"value" );
            jw.valuevalue );
            jw.endObject();
        }
    }
    private void collectExportJSONArray arrayString name, Version version )
    {
        StringBuffer val = new StringBuffer();
        boolean bootDel = isBootDelegatedname );
        if ( bootDel )
        {
            val.append"!! " );
        }
        val.appendname );
        val.append",version=" );
        val.appendversion );