From edfad55cdc1844c3ba2402c950582dede999ba6e Mon Sep 17 00:00:00 2001 From: Felix Meschberger Date: Mon, 19 May 2008 07:36:38 +0000 Subject: [PATCH] Organize imports and format according to Apache Felix code conventions git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@657742 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/felix/webconsole/Action.java | 16 +- .../webconsole/ConfigurationPrinter.java | 9 +- .../org/apache/felix/webconsole/Render.java | 10 +- .../internal/BaseManagementPlugin.java | 56 +- .../internal/OsgiManagerActivator.java | 20 +- .../felix/webconsole/internal/Util.java | 114 ++-- .../compendium/AbstractScrPlugin.java | 24 +- .../compendium/AjaxConfigManagerAction.java | 434 ++++++++------ .../ComponentConfigurationPrinter.java | 202 ++++--- .../compendium/ComponentRenderAction.java | 489 +++++++++------- .../internal/compendium/ConfigManager.java | 184 +++--- .../compendium/ConfigManagerBase.java | 192 ++++--- .../core/AjaxBundleDetailsAction.java | 542 +++++++++++------- .../internal/core/BundleAction.java | 22 +- .../internal/core/BundleListRender.java | 406 +++++++------ .../internal/core/InstallAction.java | 288 ++++++---- .../internal/core/RefreshPackagesAction.java | 20 +- .../internal/core/SetStartLevelAction.java | 48 +- .../webconsole/internal/core/StartAction.java | 37 +- .../webconsole/internal/core/StopAction.java | 37 +- .../internal/core/UninstallAction.java | 37 +- .../internal/core/UpdateAction.java | 132 +++-- .../internal/misc/AssemblyListRender.java | 27 +- .../internal/misc/ConfigurationRender.java | 499 +++++++++------- .../internal/obr/AbstractObrPlugin.java | 45 +- .../internal/obr/BundleRepositoryRender.java | 371 ++++++------ .../internal/obr/InstallFromRepoAction.java | 13 +- .../internal/obr/RefreshRepoAction.java | 99 ++-- .../servlet/ConfigurationListener.java | 31 +- .../webconsole/internal/servlet/Logger.java | 51 +- .../internal/servlet/OsgiManager.java | 496 +++++++++------- .../servlet/OsgiManagerHttpContext.java | 129 +++-- .../webconsole/internal/system/GCAction.java | 17 +- .../internal/system/ShutdownAction.java | 47 +- .../internal/system/ShutdownRender.java | 36 +- .../internal/system/VMStatRender.java | 234 ++++---- 36 files changed, 3181 insertions(+), 2233 deletions(-) diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/Action.java b/webconsole/src/main/java/org/apache/felix/webconsole/Action.java index 93ead818388..8389af15c77 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/Action.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/Action.java @@ -16,26 +16,32 @@ */ package org.apache.felix.webconsole; + import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -public interface Action { + +public interface Action +{ static final String SERVICE = Action.class.getName(); - + /** * The name of a request attribute, which may be set by performAction if * redirecting. */ - static final String ATTR_REDIRECT_PARAMETERS= "redirectParameters"; + static final String ATTR_REDIRECT_PARAMETERS = "redirectParameters"; + String getName(); + String getLabel(); + /** * Performs the action the request data optionally sending a response to * the HTTP Servlet Response. @@ -53,7 +59,7 @@ public interface Action { * processing the action. The rootCause of the exception * should contain the cause of the error. */ - boolean performAction(HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException; + boolean performAction( HttpServletRequest request, HttpServletResponse response ) throws IOException, + ServletException; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/ConfigurationPrinter.java b/webconsole/src/main/java/org/apache/felix/webconsole/ConfigurationPrinter.java index e16faadaa3d..8e9c22e1a5f 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/ConfigurationPrinter.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/ConfigurationPrinter.java @@ -18,14 +18,19 @@ */ package org.apache.felix.webconsole; + import java.io.PrintWriter; -public interface ConfigurationPrinter { + +public interface ConfigurationPrinter +{ static final String SERVICE = ConfigurationPrinter.class.getName(); + String getTitle(); - void printConfiguration(PrintWriter printWriter); + + void printConfiguration( PrintWriter printWriter ); } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/Render.java b/webconsole/src/main/java/org/apache/felix/webconsole/Render.java index 4c8255a3569..33fa0eefeef 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/Render.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/Render.java @@ -16,23 +16,29 @@ */ package org.apache.felix.webconsole; + import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + /** * The Render TODO */ -public interface Render { +public interface Render +{ static final String SERVICE = Render.class.getName(); + String getName(); + String getLabel(); - void render(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; + + void render( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/BaseManagementPlugin.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/BaseManagementPlugin.java index c0602e4293f..83ac401e628 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/BaseManagementPlugin.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/BaseManagementPlugin.java @@ -18,13 +18,16 @@ */ package org.apache.felix.webconsole.internal; + import org.apache.felix.webconsole.internal.servlet.Logger; import org.osgi.framework.BundleContext; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; import org.osgi.util.tracker.ServiceTracker; -public class BaseManagementPlugin { + +public class BaseManagementPlugin +{ private BundleContext bundleContext; private Logger log; @@ -33,42 +36,55 @@ public class BaseManagementPlugin { private ServiceTracker packageAdmin; - protected BaseManagementPlugin() { + + protected BaseManagementPlugin() + { } - public void setBundleContext(BundleContext bundleContext) { + + public void setBundleContext( BundleContext bundleContext ) + { this.bundleContext = bundleContext; } - - public void setLogger(Logger log) { + + + public void setLogger( Logger log ) + { this.log = log; } - protected BundleContext getBundleContext() { + + protected BundleContext getBundleContext() + { return bundleContext; } - - protected Logger getLog() { + + + protected Logger getLog() + { return log; } - - protected StartLevel getStartLevel() { - if (startLevelService == null) { - startLevelService = new ServiceTracker(getBundleContext(), - StartLevel.class.getName(), null); + + + protected StartLevel getStartLevel() + { + if ( startLevelService == null ) + { + startLevelService = new ServiceTracker( getBundleContext(), StartLevel.class.getName(), null ); startLevelService.open(); } - return (StartLevel) startLevelService.getService(); + return ( StartLevel ) startLevelService.getService(); } - protected PackageAdmin getPackageAdmin() { - if (packageAdmin == null) { - packageAdmin = new ServiceTracker(getBundleContext(), - PackageAdmin.class.getName(), null); + + protected PackageAdmin getPackageAdmin() + { + if ( packageAdmin == null ) + { + packageAdmin = new ServiceTracker( getBundleContext(), PackageAdmin.class.getName(), null ); packageAdmin.open(); } - return (PackageAdmin) packageAdmin.getService(); + return ( PackageAdmin ) packageAdmin.getService(); } - } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/OsgiManagerActivator.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/OsgiManagerActivator.java index 6b83f1b6c8d..32749a7bbcf 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/OsgiManagerActivator.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/OsgiManagerActivator.java @@ -18,20 +18,28 @@ */ package org.apache.felix.webconsole.internal; + import org.apache.felix.webconsole.internal.servlet.OsgiManager; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; -public class OsgiManagerActivator implements BundleActivator { + +public class OsgiManagerActivator implements BundleActivator +{ private OsgiManager osgiManager; - - public void start(BundleContext bundleContext) { - osgiManager = new OsgiManager(bundleContext); + + + public void start( BundleContext bundleContext ) + { + osgiManager = new OsgiManager( bundleContext ); } - public void stop(BundleContext arg0) { - if (osgiManager != null) { + + public void stop( BundleContext arg0 ) + { + if ( osgiManager != null ) + { osgiManager.dispose(); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/Util.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/Util.java index b8368c6322b..9d4212e1bbd 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/Util.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/Util.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal; + import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; @@ -30,10 +31,12 @@ import org.apache.commons.io.IOUtils; import org.apache.felix.webconsole.Render; + /** * The Util TODO */ -public class Util { +public class Util +{ /** web apps subpage */ public static final String PAGE_WEBAPPS = "/webapps"; @@ -87,8 +90,10 @@ public class Util { /** The name of the request attribute containig the map of FileItems from the POST request */ public static final String ATTR_FILEUPLOAD = "org.apache.felix.webconsole.fileupload"; - public static PrintWriter startHtml(HttpServletResponse resp, String pageTitle) throws IOException { - resp.setContentType("text/html; utf-8"); + + public static PrintWriter startHtml( HttpServletResponse resp, String pageTitle ) throws IOException + { + resp.setContentType( "text/html; utf-8" ); PrintWriter pw = resp.getWriter(); @@ -102,69 +107,90 @@ public static PrintWriter startHtml(HttpServletResponse resp, String pageTitle) long totalMem = Runtime.getRuntime().totalMemory() / 1024; long usedMem = totalMem - freeMem; - String header = MessageFormat.format(HEADER, new Object[] { - adminTitle, - "1.0.0-SNAPSHOT", // ServletEngine.VERSION.getFullVersion(), - System.getProperty("java.runtime.version"), - System.getProperty("java.runtime.name"), - System.getProperty("java.vm.name"), - System.getProperty("java.vm.version"), - System.getProperty("java.vm.info"), new Long(totalMem), - new Long(usedMem), new Long(freeMem), vendorWeb, productName, - pageTitle, productWeb, vendorName}); - pw.println(header); + String header = MessageFormat.format( HEADER, new Object[] + { + adminTitle, + "1.0.0-SNAPSHOT", // ServletEngine.VERSION.getFullVersion(), + System.getProperty( "java.runtime.version" ), System.getProperty( "java.runtime.name" ), + System.getProperty( "java.vm.name" ), System.getProperty( "java.vm.version" ), + System.getProperty( "java.vm.info" ), new Long( totalMem ), new Long( usedMem ), new Long( freeMem ), + vendorWeb, productName, pageTitle, productWeb, vendorName } ); + pw.println( header ); return pw; } - public static void navigation(PrintWriter pw, Collection renders, String current, boolean disabled) { - pw.println("

"); + + public static void navigation( PrintWriter pw, Collection renders, String current, boolean disabled ) + { + pw.println( "

" ); SortedMap map = new TreeMap(); - for (Iterator ri=renders.iterator(); ri.hasNext(); ) { - Render render = (Render) ri.next(); - if (render.getLabel() == null) { + for ( Iterator ri = renders.iterator(); ri.hasNext(); ) + { + Render render = ( Render ) ri.next(); + if ( render.getLabel() == null ) + { // ignore renders without a label - } else if (disabled || current.equals(render.getName())) { - map.put(render.getLabel(), "" + render.getLabel() + ""); - } else { - map.put(render.getLabel(), "" + render.getLabel() + ""); + } + else if ( disabled || current.equals( render.getName() ) ) + { + map.put( render.getLabel(), "" + render.getLabel() + "" ); + } + else + { + map.put( render.getLabel(), "" + render.getLabel() + "" ); } } - for (Iterator li=map.values().iterator(); li.hasNext(); ) { - pw.println(li.next()); + for ( Iterator li = map.values().iterator(); li.hasNext(); ) + { + pw.println( li.next() ); } - pw.println("

"); + pw.println( "

" ); } - public static void endHhtml(PrintWriter pw) { - pw.println(""); - pw.println(""); + + public static void endHhtml( PrintWriter pw ) + { + pw.println( "" ); + pw.println( "" ); } - public static void startScript(PrintWriter pw) { - pw.println(""); + + public static void endScript( PrintWriter pw ) + { + pw.println( "// ]]>" ); + pw.println( "" ); } - public static void spool(String res, HttpServletResponse resp) throws IOException { - InputStream ins = getResource(res); - if (ins != null) { - try { - IOUtils.copy(ins, resp.getOutputStream()); - } finally { - IOUtils.closeQuietly(ins); + + public static void spool( String res, HttpServletResponse resp ) throws IOException + { + InputStream ins = getResource( res ); + if ( ins != null ) + { + try + { + IOUtils.copy( ins, resp.getOutputStream() ); + } + finally + { + IOUtils.closeQuietly( ins ); } } } - private static InputStream getResource(String resource) { - return Util.class.getResourceAsStream(resource); + + private static InputStream getResource( String resource ) + { + return Util.class.getResourceAsStream( resource ); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AbstractScrPlugin.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AbstractScrPlugin.java index bcc031270d0..763e910e54c 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AbstractScrPlugin.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AbstractScrPlugin.java @@ -18,27 +18,35 @@ */ package org.apache.felix.webconsole.internal.compendium; + import org.apache.felix.scr.ScrService; import org.apache.felix.webconsole.internal.BaseManagementPlugin; import org.osgi.util.tracker.ServiceTracker; -public class AbstractScrPlugin extends BaseManagementPlugin { + +public class AbstractScrPlugin extends BaseManagementPlugin +{ private ServiceTracker scrServiceTracker; - protected ScrService getScrService() { - if (scrServiceTracker == null) { - try { - scrServiceTracker = new ServiceTracker(getBundleContext(), - ScrService.class.getName(), null); + + protected ScrService getScrService() + { + if ( scrServiceTracker == null ) + { + try + { + scrServiceTracker = new ServiceTracker( getBundleContext(), ScrService.class.getName(), null ); scrServiceTracker.open(); - } catch (Throwable t) { + } + catch ( Throwable t ) + { // missing ScrService class ?? return null; } } - return (ScrService) scrServiceTracker.getService(); + return ( ScrService ) scrServiceTracker.getService(); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AjaxConfigManagerAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AjaxConfigManagerAction.java index d80cf6fda86..9dc7aad6e66 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AjaxConfigManagerAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/AjaxConfigManagerAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.compendium; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.Array; @@ -45,202 +46,249 @@ import org.osgi.service.metatype.AttributeDefinition; import org.osgi.service.metatype.ObjectClassDefinition; + /** * The AjaxConfigManagerAction TODO */ -public class AjaxConfigManagerAction extends ConfigManagerBase implements - Action { +public class AjaxConfigManagerAction extends ConfigManagerBase implements Action +{ public static final String NAME = "ajaxConfigManager"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return NAME; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) throws IOException { + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) throws IOException + { // should actually apply the configuration before redirecting - if (request.getParameter("apply") != null) { - return applyConfiguration(request); + if ( request.getParameter( "apply" ) != null ) + { + return applyConfiguration( request ); } JSONObject result = new JSONObject(); - String pid = request.getParameter(ConfigManager.PID); + String pid = request.getParameter( ConfigManager.PID ); boolean isFactory = pid == null; - if (isFactory) { - pid = request.getParameter("factoryPid"); + if ( isFactory ) + { + pid = request.getParameter( "factoryPid" ); } - if (pid != null) { - try { - this.configForm(result, pid, isFactory, getLocale(request)); - } catch (Exception e) { + if ( pid != null ) + { + try + { + this.configForm( result, pid, isFactory, getLocale( request ) ); + } + catch ( Exception e ) + { // add message } } // send the result - response.setContentType("text/javascript"); - response.getWriter().print(result.toString()); + response.setContentType( "text/javascript" ); + response.getWriter().print( result.toString() ); return false; } - private void configForm(JSONObject json, String pid, boolean isFactory, - Locale loc) throws IOException, JSONException { - String locale = (loc == null) ? null : loc.toString(); + + private void configForm( JSONObject json, String pid, boolean isFactory, Locale loc ) throws IOException, + JSONException + { + String locale = ( loc == null ) ? null : loc.toString(); ConfigurationAdmin ca = this.getConfigurationAdmin(); - if (ca == null) { + if ( ca == null ) + { // should print message return; } Configuration config = null; - try { - Configuration[] configs = ca.listConfigurations("(" - + Constants.SERVICE_PID + "=" + pid + ")"); - if (configs != null && configs.length > 0) { + try + { + Configuration[] configs = ca.listConfigurations( "(" + Constants.SERVICE_PID + "=" + pid + ")" ); + if ( configs != null && configs.length > 0 ) + { config = configs[0]; } - } catch (InvalidSyntaxException ise) { + } + catch ( InvalidSyntaxException ise ) + { // should print message return; } - json.put(ConfigManager.PID, pid); - json.put("isFactory", isFactory); + json.put( ConfigManager.PID, pid ); + json.put( "isFactory", isFactory ); Dictionary props = null; ObjectClassDefinition ocd; - if (config != null) { + if ( config != null ) + { props = config.getProperties(); - ocd = this.getObjectClassDefinition(config, locale); - } else { - ocd = this.getObjectClassDefinition(pid, locale); + ocd = this.getObjectClassDefinition( config, locale ); + } + else + { + ocd = this.getObjectClassDefinition( pid, locale ); } - props = this.mergeWithMetaType(props, ocd, json); + props = this.mergeWithMetaType( props, ocd, json ); - if (props != null) { + if ( props != null ) + { JSONObject properties = new JSONObject(); - for (Enumeration pe = props.keys(); pe.hasMoreElements();) { + for ( Enumeration pe = props.keys(); pe.hasMoreElements(); ) + { Object key = pe.nextElement(); // ignore well known special properties - if (!key.equals(Constants.SERVICE_PID) - && !key.equals(Constants.SERVICE_DESCRIPTION) - && !key.equals(Constants.SERVICE_ID) - && !key.equals(Constants.SERVICE_RANKING) - && !key.equals(Constants.SERVICE_VENDOR) - && !key.equals(ConfigurationAdmin.SERVICE_BUNDLELOCATION) - && !key.equals(ConfigurationAdmin.SERVICE_FACTORYPID)) { - properties.put(String.valueOf(key), props.get(key)); + if ( !key.equals( Constants.SERVICE_PID ) && !key.equals( Constants.SERVICE_DESCRIPTION ) + && !key.equals( Constants.SERVICE_ID ) && !key.equals( Constants.SERVICE_RANKING ) + && !key.equals( Constants.SERVICE_VENDOR ) + && !key.equals( ConfigurationAdmin.SERVICE_BUNDLELOCATION ) + && !key.equals( ConfigurationAdmin.SERVICE_FACTORYPID ) ) + { + properties.put( String.valueOf( key ), props.get( key ) ); } } - json.put("title", pid); - json.put( - "description", - "Please enter configuration properties for this configuration in the field below. This configuration has no associated description"); + json.put( "title", pid ); + json + .put( + "description", + "Please enter configuration properties for this configuration in the field below. This configuration has no associated description" ); - json.put("propertylist", "properties"); - json.put("properties", properties); + json.put( "propertylist", "properties" ); + json.put( "properties", properties ); } - if (config != null) { - this.addConfigurationInfo(config, json, locale); + if ( config != null ) + { + this.addConfigurationInfo( config, json, locale ); } } - private Dictionary mergeWithMetaType(Dictionary props, - ObjectClassDefinition ocd, JSONObject json) throws JSONException { - if (props == null) { + private Dictionary mergeWithMetaType( Dictionary props, ObjectClassDefinition ocd, JSONObject json ) + throws JSONException + { + + if ( props == null ) + { props = new Hashtable(); } - if (ocd != null) { + if ( ocd != null ) + { - json.put("title", ocd.getName()); + json.put( "title", ocd.getName() ); - if (ocd.getDescription() != null) { - json.put("description", ocd.getDescription()); + if ( ocd.getDescription() != null ) + { + json.put( "description", ocd.getDescription() ); } - AttributeDefinition[] ad = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL); - if (ad != null) { + AttributeDefinition[] ad = ocd.getAttributeDefinitions( ObjectClassDefinition.ALL ); + if ( ad != null ) + { JSONArray propertyList = new JSONArray(); - for (int i = 0; i < ad.length; i++) { + for ( int i = 0; i < ad.length; i++ ) + { JSONObject entry = new JSONObject(); - Object value = props.get(ad[i].getID()); - if (value == null) { + Object value = props.get( ad[i].getID() ); + if ( value == null ) + { value = ad[i].getDefaultValue(); - if (value == null) { - if (ad[i].getCardinality() == 0) { + if ( value == null ) + { + if ( ad[i].getCardinality() == 0 ) + { value = ""; - } else { + } + else + { value = new String[0]; } } } - entry.put("name", ad[i].getName()); + entry.put( "name", ad[i].getName() ); - if (ad[i].getOptionLabels() != null - && ad[i].getOptionLabels().length > 0) { + if ( ad[i].getOptionLabels() != null && ad[i].getOptionLabels().length > 0 ) + { JSONObject type = new JSONObject(); - type.put("labels", - Arrays.asList(ad[i].getOptionLabels())); - type.put("values", - Arrays.asList(ad[i].getOptionValues())); - entry.put("type", type); - } else { - entry.put("type", ad[i].getType()); + type.put( "labels", Arrays.asList( ad[i].getOptionLabels() ) ); + type.put( "values", Arrays.asList( ad[i].getOptionValues() ) ); + entry.put( "type", type ); + } + else + { + entry.put( "type", ad[i].getType() ); } - if (ad[i].getCardinality() == 0) { + if ( ad[i].getCardinality() == 0 ) + { // scalar - if (value instanceof Vector) { - value = ((Vector) value).get(0); - } else if (value.getClass().isArray()) { - value = Array.get(value, 0); + if ( value instanceof Vector ) + { + value = ( ( Vector ) value ).get( 0 ); + } + else if ( value.getClass().isArray() ) + { + value = Array.get( value, 0 ); + } + entry.put( "value", value ); + } + else + { + if ( value instanceof Vector ) + { + value = new JSONArray( ( Vector ) value ); + } + else if ( value.getClass().isArray() ) + { + value = new JSONArray( Arrays.asList( ( Object[] ) value ) ); } - entry.put("value", value); - } else { - if (value instanceof Vector) { - value = new JSONArray((Vector) value); - } else if (value.getClass().isArray()) { - value = new JSONArray( - Arrays.asList((Object[]) value)); - } else { + else + { JSONArray tmp = new JSONArray(); - tmp.put(value); + tmp.put( value ); value = tmp; } - entry.put("values", value); + entry.put( "values", value ); } - if (ad[i].getDescription() != null) { - entry.put("description", ad[i].getDescription()); + if ( ad[i].getDescription() != null ) + { + entry.put( "description", ad[i].getDescription() ); } - json.put(ad[i].getID(), entry); - propertyList.put(ad[i].getID()); + json.put( ad[i].getID(), entry ); + propertyList.put( ad[i].getID() ); } - json.put("propertylist", propertyList); + json.put( "propertylist", propertyList ); } // nothing more to display @@ -250,149 +298,182 @@ private Dictionary mergeWithMetaType(Dictionary props, return props; } - private void addConfigurationInfo(Configuration config, JSONObject json, - String locale) throws JSONException { - if (config.getFactoryPid() != null) { - json.put("factoryPID", config.getFactoryPid()); + private void addConfigurationInfo( Configuration config, JSONObject json, String locale ) throws JSONException + { + + if ( config.getFactoryPid() != null ) + { + json.put( "factoryPID", config.getFactoryPid() ); } String location; - if (config.getBundleLocation() == null) { + if ( config.getBundleLocation() == null ) + { location = "None"; - } else { - Bundle bundle = this.getBundle(config.getBundleLocation()); - - Dictionary headers = bundle.getHeaders(locale); - String name = (String) headers.get(Constants.BUNDLE_NAME); - if (name == null) { + } + else + { + Bundle bundle = this.getBundle( config.getBundleLocation() ); + + Dictionary headers = bundle.getHeaders( locale ); + String name = ( String ) headers.get( Constants.BUNDLE_NAME ); + if ( name == null ) + { location = bundle.getSymbolicName(); - } else { + } + else + { location = name + " (" + bundle.getSymbolicName() + ")"; } - Version v = Version.parseVersion((String) headers.get(Constants.BUNDLE_VERSION)); + Version v = Version.parseVersion( ( String ) headers.get( Constants.BUNDLE_VERSION ) ); location += ", Version " + v.toString(); } - json.put("bundleLocation", location); + json.put( "bundleLocation", location ); } - private boolean applyConfiguration(HttpServletRequest request) - throws IOException { + + private boolean applyConfiguration( HttpServletRequest request ) throws IOException + { ConfigurationAdmin ca = this.getConfigurationAdmin(); - if (ca == null) { + if ( ca == null ) + { return false; } - String pid = request.getParameter("pid"); + String pid = request.getParameter( "pid" ); - if (request.getParameter("delete") != null) { + if ( request.getParameter( "delete" ) != null ) + { // TODO: should log this here !! - Configuration config = ca.getConfiguration(pid, null); + Configuration config = ca.getConfiguration( pid, null ); config.delete(); return true; - } else if (request.getParameter("create") != null) { + } + else if ( request.getParameter( "create" ) != null ) + { // pid is a factory PID and we have to create a new configuration // we should actually also display that one ! - Configuration config = ca.createFactoryConfiguration(pid, null); + Configuration config = ca.createFactoryConfiguration( pid, null ); // request.setAttribute(ATTR_REDIRECT_PARAMETERS, "pid=" + // config.getPid()); return true; } - String propertyList = request.getParameter("propertylist"); - if (propertyList == null) { - String propertiesString = request.getParameter("properties"); + String propertyList = request.getParameter( "propertylist" ); + if ( propertyList == null ) + { + String propertiesString = request.getParameter( "properties" ); - if (propertiesString != null) { - byte[] propBytes = propertiesString.getBytes("ISO-8859-1"); - ByteArrayInputStream bin = new ByteArrayInputStream(propBytes); + if ( propertiesString != null ) + { + byte[] propBytes = propertiesString.getBytes( "ISO-8859-1" ); + ByteArrayInputStream bin = new ByteArrayInputStream( propBytes ); Properties props = new Properties(); - props.load(bin); + props.load( bin ); - Configuration config = ca.getConfiguration(pid, null); - config.update(props); + Configuration config = ca.getConfiguration( pid, null ); + config.update( props ); } - } else { - Configuration config = ca.getConfiguration(pid, null); + } + else + { + Configuration config = ca.getConfiguration( pid, null ); Dictionary props = config.getProperties(); - if (props == null) { + if ( props == null ) + { props = new Hashtable(); } - Map adMap = (Map) this.getAttributeDefinitionMap(config, null); - if (adMap != null) { - StringTokenizer propTokens = new StringTokenizer(propertyList, - ","); - while (propTokens.hasMoreTokens()) { + Map adMap = ( Map ) this.getAttributeDefinitionMap( config, null ); + if ( adMap != null ) + { + StringTokenizer propTokens = new StringTokenizer( propertyList, "," ); + while ( propTokens.hasMoreTokens() ) + { String propName = propTokens.nextToken(); - AttributeDefinition ad = (AttributeDefinition) adMap.get(propName); - if (ad == null - || (ad.getCardinality() == 0 && ad.getType() == AttributeDefinition.STRING)) { - String prop = request.getParameter(propName); - if (prop != null) { - props.put(propName, prop); + AttributeDefinition ad = ( AttributeDefinition ) adMap.get( propName ); + if ( ad == null || ( ad.getCardinality() == 0 && ad.getType() == AttributeDefinition.STRING ) ) + { + String prop = request.getParameter( propName ); + if ( prop != null ) + { + props.put( propName, prop ); } - } else if (ad.getCardinality() == 0) { + } + else if ( ad.getCardinality() == 0 ) + { // scalar of non-string - String prop = request.getParameter(propName); - props.put(propName, this.toType(ad.getType(), prop)); - } else { + String prop = request.getParameter( propName ); + props.put( propName, this.toType( ad.getType(), prop ) ); + } + else + { // array or vector of any type Vector vec = new Vector(); - String[] properties = request.getParameterValues(propName); - if (properties != null) { - for (int i = 0; i < properties.length; i++) { - vec.add(this.toType(ad.getType(), properties[i])); + String[] properties = request.getParameterValues( propName ); + if ( properties != null ) + { + for ( int i = 0; i < properties.length; i++ ) + { + vec.add( this.toType( ad.getType(), properties[i] ) ); } } // but ensure size - int maxSize = Math.abs(ad.getCardinality()); - if (vec.size() > maxSize) { - vec.setSize(maxSize); + int maxSize = Math.abs( ad.getCardinality() ); + if ( vec.size() > maxSize ) + { + vec.setSize( maxSize ); } - if (ad.getCardinality() < 0) { + if ( ad.getCardinality() < 0 ) + { // keep the vector - props.put(propName, vec); - } else { + props.put( propName, vec ); + } + else + { // convert to an array - props.put(propName, this.toArray(ad.getType(), vec)); + props.put( propName, this.toArray( ad.getType(), vec ) ); } } } } - config.update(props); + config.update( props ); } // request.setAttribute(ATTR_REDIRECT_PARAMETERS, "pid=" + pid); return true; } - private Object toType(int type, String value) { - switch (type) { + + private Object toType( int type, String value ) + { + switch ( type ) + { case AttributeDefinition.BOOLEAN: - return Boolean.valueOf(value); + return Boolean.valueOf( value ); case AttributeDefinition.BYTE: - return Byte.valueOf(value); + return Byte.valueOf( value ); case AttributeDefinition.CHARACTER: - char c = (value.length() > 0) ? value.charAt(0) : 0; - return new Character(c); + char c = ( value.length() > 0 ) ? value.charAt( 0 ) : 0; + return new Character( c ); case AttributeDefinition.DOUBLE: - return Double.valueOf(value); + return Double.valueOf( value ); case AttributeDefinition.FLOAT: - return Float.valueOf(value); + return Float.valueOf( value ); case AttributeDefinition.LONG: - return Long.valueOf(value); + return Long.valueOf( value ); case AttributeDefinition.INTEGER: - return Integer.valueOf(value); + return Integer.valueOf( value ); case AttributeDefinition.SHORT: - return Short.valueOf(value); + return Short.valueOf( value ); default: // includes AttributeDefinition.STRING @@ -400,16 +481,20 @@ private Object toType(int type, String value) { } } - private Object toArray(int type, Vector values) { + + private Object toArray( int type, Vector values ) + { int size = values.size(); // short cut for string array - if (type == AttributeDefinition.STRING) { - return values.toArray(new String[size]); + if ( type == AttributeDefinition.STRING ) + { + return values.toArray( new String[size] ); } Object array; - switch (type) { + switch ( type ) + { case AttributeDefinition.BOOLEAN: array = new boolean[size]; case AttributeDefinition.BYTE: @@ -431,8 +516,9 @@ private Object toArray(int type, Vector values) { array = new String[size]; } - for (int i = 0; i < size; i++) { - Array.set(array, i, values.get(i)); + for ( int i = 0; i < size; i++ ) + { + Array.set( array, i, values.get( i ) ); } return array; diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentConfigurationPrinter.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentConfigurationPrinter.java index 1d0af86bbc0..76a6980d5c1 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentConfigurationPrinter.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentConfigurationPrinter.java @@ -18,6 +18,7 @@ */ package org.apache.felix.webconsole.internal.compendium; + import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; @@ -36,156 +37,187 @@ import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentConstants; -public class ComponentConfigurationPrinter extends AbstractScrPlugin implements - ConfigurationPrinter { + +public class ComponentConfigurationPrinter extends AbstractScrPlugin implements ConfigurationPrinter +{ private ServiceRegistration registration; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); - registration = bundleContext.registerService( - ConfigurationPrinter.SERVICE, this, null); + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); + + registration = bundleContext.registerService( ConfigurationPrinter.SERVICE, this, null ); } - public String getTitle() { + + public String getTitle() + { return "Declarative Services Components"; } - public void printConfiguration(PrintWriter pw) { + + public void printConfiguration( PrintWriter pw ) + { ScrService scrService = getScrService(); - if (scrService != null) { + if ( scrService != null ) + { Component[] components = scrService.getComponents(); - if (components == null || components.length == 0) { + if ( components == null || components.length == 0 ) + { - pw.println(" No Components Registered"); + pw.println( " No Components Registered" ); - } else { + } + else + { // order components by id TreeMap componentMap = new TreeMap(); - for (int i=0; i < components.length; i++) { + for ( int i = 0; i < components.length; i++ ) + { Component component = components[1]; - componentMap.put(new Long(component.getId()), component); + componentMap.put( new Long( component.getId() ), component ); } // render components - for (Iterator ci = componentMap.values().iterator(); ci.hasNext();) { - Component component = (Component) ci.next(); - component(pw, component); + for ( Iterator ci = componentMap.values().iterator(); ci.hasNext(); ) + { + Component component = ( Component ) ci.next(); + component( pw, component ); } } - } else { - pw.println(" Apache Felix Declarative Service not installed"); + } + else + { + pw.println( " Apache Felix Declarative Service not installed" ); } } - private void component(PrintWriter pw, Component component) { - pw.print(component.getId()); - pw.print("=["); - pw.print(component.getName()); - pw.println("]"); + private void component( PrintWriter pw, Component component ) + { + + pw.print( component.getId() ); + pw.print( "=[" ); + pw.print( component.getName() ); + pw.println( "]" ); - pw.println(" Bundle" + component.getBundle().getSymbolicName() + " (" - + component.getBundle().getBundleId() + ")"); - pw.println(" State=" - + ComponentRenderAction.toStateString(component.getState())); - pw.println(" DefaultState=" - + (component.isDefaultEnabled() ? "enabled" : "disabled")); - pw.println(" Activation=" - + (component.isImmediate() ? "immediate" : "delayed")); + pw.println( " Bundle" + component.getBundle().getSymbolicName() + " (" + component.getBundle().getBundleId() + + ")" ); + pw.println( " State=" + ComponentRenderAction.toStateString( component.getState() ) ); + pw.println( " DefaultState=" + ( component.isDefaultEnabled() ? "enabled" : "disabled" ) ); + pw.println( " Activation=" + ( component.isImmediate() ? "immediate" : "delayed" ) ); - listServices(pw, component); - listReferences(pw, component); - listProperties(pw, component); + listServices( pw, component ); + listReferences( pw, component ); + listProperties( pw, component ); pw.println(); } - private void listServices(PrintWriter pw, Component component) { + + private void listServices( PrintWriter pw, Component component ) + { String[] services = component.getServices(); - if (services == null) { + if ( services == null ) + { return; } - pw.println(" ServiceType=" - + (component.isServiceFactory() ? "service factory" : "service")); + pw.println( " ServiceType=" + ( component.isServiceFactory() ? "service factory" : "service" ) ); StringBuffer buf = new StringBuffer(); - for (int i = 0; i < services.length; i++) { - if (i > 0) { - buf.append(", "); + for ( int i = 0; i < services.length; i++ ) + { + if ( i > 0 ) + { + buf.append( ", " ); } - buf.append(services[i]); + buf.append( services[i] ); } - pw.println(" Services=" + buf); + pw.println( " Services=" + buf ); } - private void listReferences(PrintWriter pw, Component component) { + + private void listReferences( PrintWriter pw, Component component ) + { Reference[] refs = component.getReferences(); - if (refs != null) { - for (int i = 0; i < refs.length; i++) { + if ( refs != null ) + { + for ( int i = 0; i < refs.length; i++ ) + { - pw.println(" Reference=" + refs[i].getName() + ", " - + (refs[i].isSatisfied() ? "Satisfied" : "Unsatisfied")); + pw.println( " Reference=" + refs[i].getName() + ", " + + ( refs[i].isSatisfied() ? "Satisfied" : "Unsatisfied" ) ); - pw.println(" Service Name: " + refs[i].getServiceName()); + pw.println( " Service Name: " + refs[i].getServiceName() ); - if (refs[i].getTarget() != null) { - pw.println(" Target Filter: " + refs[i].getTarget()); + if ( refs[i].getTarget() != null ) + { + pw.println( " Target Filter: " + refs[i].getTarget() ); } - pw.println(" Multiple: " - + (refs[i].isMultiple() ? "multiple" : "single")); - pw.println(" Optional: " - + (refs[i].isOptional() ? "optional" : "mandatory")); - pw.println(" Policy: " - + (refs[i].isStatic() ? "static" : "dynamic")); + pw.println( " Multiple: " + ( refs[i].isMultiple() ? "multiple" : "single" ) ); + pw.println( " Optional: " + ( refs[i].isOptional() ? "optional" : "mandatory" ) ); + pw.println( " Policy: " + ( refs[i].isStatic() ? "static" : "dynamic" ) ); // list bound services ServiceReference[] boundRefs = refs[i].getServiceReferences(); - if (boundRefs != null && boundRefs.length > 0) { - for (int j = 0; j < boundRefs.length; j++) { - pw.print(" Bound Service: ID "); - pw.print(boundRefs[j].getProperty(Constants.SERVICE_ID)); - - String name = (String) boundRefs[j].getProperty(ComponentConstants.COMPONENT_NAME); - if (name == null) { - name = (String) boundRefs[j].getProperty(Constants.SERVICE_PID); - if (name == null) { - name = (String) boundRefs[j].getProperty(Constants.SERVICE_DESCRIPTION); + if ( boundRefs != null && boundRefs.length > 0 ) + { + for ( int j = 0; j < boundRefs.length; j++ ) + { + pw.print( " Bound Service: ID " ); + pw.print( boundRefs[j].getProperty( Constants.SERVICE_ID ) ); + + String name = ( String ) boundRefs[j].getProperty( ComponentConstants.COMPONENT_NAME ); + if ( name == null ) + { + name = ( String ) boundRefs[j].getProperty( Constants.SERVICE_PID ); + if ( name == null ) + { + name = ( String ) boundRefs[j].getProperty( Constants.SERVICE_DESCRIPTION ); } } - if (name != null) { - pw.print(" ("); - pw.print(name); - pw.print(")"); + if ( name != null ) + { + pw.print( " (" ); + pw.print( name ); + pw.print( ")" ); } } - } else { - pw.print(" No Services bound"); + } + else + { + pw.print( " No Services bound" ); } pw.println(); } } } - private void listProperties(PrintWriter pw, Component component) { + + private void listProperties( PrintWriter pw, Component component ) + { Dictionary props = component.getProperties(); - if (props != null) { - - pw.println(" Properties="); - TreeSet keys = new TreeSet(Collections.list(props.keys())); - for (Iterator ki = keys.iterator(); ki.hasNext();) { - String key = (String) ki.next(); - Object value = props.get(key); - if (value.getClass().isArray()) { - value = Arrays.asList((Object[]) value); + if ( props != null ) + { + + pw.println( " Properties=" ); + TreeSet keys = new TreeSet( Collections.list( props.keys() ) ); + for ( Iterator ki = keys.iterator(); ki.hasNext(); ) + { + String key = ( String ) ki.next(); + Object value = props.get( key ); + if ( value.getClass().isArray() ) + { + value = Arrays.asList( ( Object[] ) value ); } - pw.println(" " + key + "=" + value); + pw.println( " " + key + "=" + value ); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentRenderAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentRenderAction.java index ebb46e0eef1..9153ab5da6b 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentRenderAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ComponentRenderAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.compendium; + import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; @@ -41,8 +42,9 @@ import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentConstants; -public class ComponentRenderAction extends AbstractScrPlugin implements Render, - Action { + +public class ComponentRenderAction extends AbstractScrPlugin implements Render, Action +{ public static final String NAME = "components"; @@ -58,30 +60,42 @@ public class ComponentRenderAction extends AbstractScrPlugin implements Render, public static final String OPERATION_DISABLE = "disable"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) throws IOException { - ScrService scrService = getScrService(); - if (scrService != null) { - - long componentId = getComponentId(request); - Component component = scrService.getComponent(componentId); + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) throws IOException + { - if (component != null) { - String op = request.getParameter(OPERATION); - if (OPERATION_DETAILS.equals(op)) { - return sendAjaxDetails(component, response); - } else if (OPERATION_ENABLE.equals(op)) { + ScrService scrService = getScrService(); + if ( scrService != null ) + { + + long componentId = getComponentId( request ); + Component component = scrService.getComponent( componentId ); + + if ( component != null ) + { + String op = request.getParameter( OPERATION ); + if ( OPERATION_DETAILS.equals( op ) ) + { + return sendAjaxDetails( component, response ); + } + else if ( OPERATION_ENABLE.equals( op ) ) + { component.enable(); - } else if (OPERATION_DISABLE.equals(op)) { + } + else if ( OPERATION_DISABLE.equals( op ) ) + { component.disable(); } } @@ -91,306 +105,339 @@ public boolean performAction(HttpServletRequest request, return true; } - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { + + public void render( HttpServletRequest request, HttpServletResponse response ) throws IOException + { PrintWriter pw = response.getWriter(); - this.header(pw); + this.header( pw ); - pw.println(""); - pw.println(" "); - pw.println(""); + pw.println( "" ); + pw.println( " " ); + pw.println( "" ); - this.tableHeader(pw); + this.tableHeader( pw ); ScrService scrService = getScrService(); - if (scrService == null) { - pw.println(""); - pw.println("Apache Felix Declarative Service required for this function"); - pw.println(""); - } else { + if ( scrService == null ) + { + pw.println( "" ); + pw + .println( "Apache Felix Declarative Service required for this function" ); + pw.println( "" ); + } + else + { Component[] components = scrService.getComponents(); - if (components == null || components.length == 0) { - pw.println(""); - pw.println("No " - + this.getLabel() + " installed currently"); - pw.println(""); + if ( components == null || components.length == 0 ) + { + pw.println( "" ); + pw.println( "No " + this.getLabel() + " installed currently" ); + pw.println( "" ); - } else { + } + else + { // order components by id TreeMap componentMap = new TreeMap(); - for (int i=0; i < components.length; i++) { + for ( int i = 0; i < components.length; i++ ) + { Component component = components[i]; - componentMap.put(component.getName(), component); + componentMap.put( component.getName(), component ); } // render components long previousComponent = -1; - for (Iterator ci = componentMap.values().iterator(); ci.hasNext();) { - Component component = (Component) ci.next(); - if (previousComponent >= 0) { + for ( Iterator ci = componentMap.values().iterator(); ci.hasNext(); ) + { + Component component = ( Component ) ci.next(); + if ( previousComponent >= 0 ) + { // prepare for injected table information row - pw.println(""); + pw.println( "" ); } - component(pw, component); + component( pw, component ); previousComponent = component.getId(); } - if (previousComponent >= 0) { + if ( previousComponent >= 0 ) + { // prepare for injected table information row - pw.println(""); + pw.println( "" ); } } } - pw.println(""); - pw.println(" "); - pw.println(""); + pw.println( "" ); + pw.println( " " ); + pw.println( "" ); - this.footer(pw); + this.footer( pw ); } - private void header(PrintWriter pw) { - Util.startScript(pw); - pw.println("function showDetails(componentId) {"); - pw.println(" var span = document.getElementById('component' + componentId);"); - pw.println(" if (!span) {"); - pw.println(" return;"); - pw.println(" }"); - pw.println(" if (span.innerHTML) {"); - pw.println(" span.innerHTML = '';"); - pw.println(" return;"); - pw.println(" }"); - pw.println(" var parm = '?" + Util.PARAM_ACTION + "=" + NAME + "&" - + OPERATION + "=" + OPERATION_DETAILS + "&" + COMPONENT_ID - + "=' + componentId;"); - pw.println(" sendRequest('GET', parm, displayComponentDetails);"); - pw.println("}"); - pw.println("function displayComponentDetails(obj) {"); - pw.println(" var span = document.getElementById('component' + obj." - + COMPONENT_ID + ");"); - pw.println(" if (!span) {"); - pw.println(" return;"); - pw.println(" }"); - pw.println(" var innerHtml = ' ';"); - pw.println(" var props = obj.props;"); - pw.println(" for (var i=0; i < props.length; i++) {"); - pw.println(" innerHtml += '';"); - pw.println(" }"); - pw.println(" innerHtml += '
' + props[i].key + '' + props[i].value + '
';"); - pw.println(" span.innerHTML = innerHtml;"); - pw.println("}"); - Util.endScript(pw); - - pw.println(""); + + private void header( PrintWriter pw ) + { + Util.startScript( pw ); + pw.println( "function showDetails(componentId) {" ); + pw.println( " var span = document.getElementById('component' + componentId);" ); + pw.println( " if (!span) {" ); + pw.println( " return;" ); + pw.println( " }" ); + pw.println( " if (span.innerHTML) {" ); + pw.println( " span.innerHTML = '';" ); + pw.println( " return;" ); + pw.println( " }" ); + pw.println( " var parm = '?" + Util.PARAM_ACTION + "=" + NAME + "&" + OPERATION + "=" + OPERATION_DETAILS + + "&" + COMPONENT_ID + "=' + componentId;" ); + pw.println( " sendRequest('GET', parm, displayComponentDetails);" ); + pw.println( "}" ); + pw.println( "function displayComponentDetails(obj) {" ); + pw.println( " var span = document.getElementById('component' + obj." + COMPONENT_ID + ");" ); + pw.println( " if (!span) {" ); + pw.println( " return;" ); + pw.println( " }" ); + pw + .println( " var innerHtml = '';" ); + pw.println( " span.innerHTML = innerHtml;" ); + pw.println( "}" ); + Util.endScript( pw ); + + pw.println( "
 ';" ); + pw.println( " var props = obj.props;" ); + pw.println( " for (var i=0; i < props.length; i++) {" ); + pw + .println( " innerHtml += '';" ); + pw.println( " }" ); + pw.println( " innerHtml += '
' + props[i].key + '' + props[i].value + '
" ); } - private void tableHeader(PrintWriter pw) { - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); + private void tableHeader( PrintWriter pw ) + { + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } - private void footer(PrintWriter pw) { - pw.println("
IDNameStatusActions
IDNameStatusActions
"); + + private void footer( PrintWriter pw ) + { + pw.println( "" ); } - private void component(PrintWriter pw, Component component) { + + private void component( PrintWriter pw, Component component ) + { String name = component.getName(); - pw.println(""); - pw.println("" + component.getId() + ""); - pw.println("" + name + ""); - pw.println("" - + toStateString(component.getState()) + ""); + pw.println( "" ); + pw.println( "" + component.getId() + "" ); + pw.println( "" + name + + "" ); + pw.println( "" + toStateString( component.getState() ) + "" ); boolean enabled = component.getState() == Component.STATE_DISABLED; - this.actionForm(pw, enabled, component.getId(), OPERATION_ENABLE, - "Enable"); + this.actionForm( pw, enabled, component.getId(), OPERATION_ENABLE, "Enable" ); - enabled = component.getState() != Component.STATE_DISABLED - && component.getState() != Component.STATE_DESTROYED; - this.actionForm(pw, enabled, component.getId(), OPERATION_DISABLE, - "Disable"); + enabled = component.getState() != Component.STATE_DISABLED && component.getState() != Component.STATE_DESTROYED; + this.actionForm( pw, enabled, component.getId(), OPERATION_DISABLE, "Disable" ); - pw.println(""); + pw.println( "" ); } - private void actionForm(PrintWriter pw, boolean enabled, long componentId, - String op, String opLabel) { - pw.println("
"); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("
"); + + private void actionForm( PrintWriter pw, boolean enabled, long componentId, String op, String opLabel ) + { + pw.println( "
" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "
" ); } - private boolean sendAjaxDetails(Component component, - HttpServletResponse response) throws IOException { + + private boolean sendAjaxDetails( Component component, HttpServletResponse response ) throws IOException + { JSONObject result = null; - try { - if (component != null) { + try + { + if ( component != null ) + { JSONArray props = new JSONArray(); - keyVal(props, "Bundle", component.getBundle().getSymbolicName() - + " (" + component.getBundle().getBundleId() + ")"); - keyVal(props, "Default State", component.isDefaultEnabled() - ? "enabled" - : "disabled"); - keyVal(props, "Activation", component.isImmediate() - ? "immediate" - : "delayed"); - - listServices(props, component); - listReferences(props, component); - listProperties(props, component); + keyVal( props, "Bundle", component.getBundle().getSymbolicName() + " (" + + component.getBundle().getBundleId() + ")" ); + keyVal( props, "Default State", component.isDefaultEnabled() ? "enabled" : "disabled" ); + keyVal( props, "Activation", component.isImmediate() ? "immediate" : "delayed" ); + + listServices( props, component ); + listReferences( props, component ); + listProperties( props, component ); result = new JSONObject(); - result.put(ComponentRenderAction.COMPONENT_ID, - component.getId()); - result.put("props", props); + result.put( ComponentRenderAction.COMPONENT_ID, component.getId() ); + result.put( "props", props ); } - } catch (Exception exception) { + } + catch ( Exception exception ) + { // create an empty result on problems result = new JSONObject(); } // send the result - response.setContentType("text/javascript"); - response.getWriter().print(result.toString()); + response.setContentType( "text/javascript" ); + response.getWriter().print( result.toString() ); return false; } - private void listServices(JSONArray props, Component component) { + + private void listServices( JSONArray props, Component component ) + { String[] services = component.getServices(); - if (services == null) { + if ( services == null ) + { return; } - keyVal(props, "Service Type", component.isServiceFactory() - ? "service factory" - : "service"); + keyVal( props, "Service Type", component.isServiceFactory() ? "service factory" : "service" ); StringBuffer buf = new StringBuffer(); - for (int i = 0; i < services.length; i++) { - if (i > 0) { - buf.append("
"); + for ( int i = 0; i < services.length; i++ ) + { + if ( i > 0 ) + { + buf.append( "
" ); } - buf.append(services[i]); + buf.append( services[i] ); } - keyVal(props, "Services", buf.toString()); + keyVal( props, "Services", buf.toString() ); } - private void listReferences(JSONArray props, Component component) { + + private void listReferences( JSONArray props, Component component ) + { Reference[] refs = component.getReferences(); - if (refs != null) { - for (int i = 0; i < refs.length; i++) { + if ( refs != null ) + { + for ( int i = 0; i < refs.length; i++ ) + { StringBuffer buf = new StringBuffer(); - buf.append(refs[i].isSatisfied() ? "Satisfied" : "Unsatisfied").append( - "
"); - buf.append("Service Name: ").append(refs[i].getServiceName()).append( - "
"); - if (refs[i].getTarget() != null) { - buf.append("Target Filter: ").append(refs[i].getTarget()).append( - "
"); + buf.append( refs[i].isSatisfied() ? "Satisfied" : "Unsatisfied" ).append( "
" ); + buf.append( "Service Name: " ).append( refs[i].getServiceName() ).append( "
" ); + if ( refs[i].getTarget() != null ) + { + buf.append( "Target Filter: " ).append( refs[i].getTarget() ).append( "
" ); } - buf.append("Multiple: ").append( - refs[i].isMultiple() ? "multiple" : "single").append( - "
"); - buf.append("Optional: ").append( - refs[i].isOptional() ? "optional" : "mandatory").append( - "
"); - buf.append("Policy: ").append( - refs[i].isStatic() ? "static" : "dynamic").append("
"); + buf.append( "Multiple: " ).append( refs[i].isMultiple() ? "multiple" : "single" ).append( "
" ); + buf.append( "Optional: " ).append( refs[i].isOptional() ? "optional" : "mandatory" ).append( "
" ); + buf.append( "Policy: " ).append( refs[i].isStatic() ? "static" : "dynamic" ).append( "
" ); // list bound services ServiceReference[] boundRefs = refs[i].getServiceReferences(); - if (boundRefs != null && boundRefs.length > 0) { - for (int j = 0; j < boundRefs.length; j++) { - buf.append("Bound Service ID "); - buf.append(boundRefs[j].getProperty(Constants.SERVICE_ID)); - - String name = (String) boundRefs[j].getProperty(ComponentConstants.COMPONENT_NAME); - if (name == null) { - name = (String) boundRefs[j].getProperty(Constants.SERVICE_PID); - if (name == null) { - name = (String) boundRefs[j].getProperty(Constants.SERVICE_DESCRIPTION); + if ( boundRefs != null && boundRefs.length > 0 ) + { + for ( int j = 0; j < boundRefs.length; j++ ) + { + buf.append( "Bound Service ID " ); + buf.append( boundRefs[j].getProperty( Constants.SERVICE_ID ) ); + + String name = ( String ) boundRefs[j].getProperty( ComponentConstants.COMPONENT_NAME ); + if ( name == null ) + { + name = ( String ) boundRefs[j].getProperty( Constants.SERVICE_PID ); + if ( name == null ) + { + name = ( String ) boundRefs[j].getProperty( Constants.SERVICE_DESCRIPTION ); } } - if (name != null) { - buf.append(" ("); - buf.append(name); - buf.append(")"); + if ( name != null ) + { + buf.append( " (" ); + buf.append( name ); + buf.append( ")" ); } } - } else { - buf.append("No Services bound"); } - buf.append("
"); + else + { + buf.append( "No Services bound" ); + } + buf.append( "
" ); - keyVal(props, "Reference " + refs[i].getName(), buf.toString()); + keyVal( props, "Reference " + refs[i].getName(), buf.toString() ); } } } - private void listProperties(JSONArray jsonProps, Component component) { + + private void listProperties( JSONArray jsonProps, Component component ) + { Dictionary props = component.getProperties(); - if (props != null) { + if ( props != null ) + { StringBuffer buf = new StringBuffer(); - TreeSet keys = new TreeSet(Collections.list(props.keys())); - for (Iterator ki = keys.iterator(); ki.hasNext();) { - String key = (String) ki.next(); - buf.append(key).append(" = "); - - Object prop = props.get(key); - if (prop.getClass().isArray()) { - prop = Arrays.asList((Object[]) prop); + TreeSet keys = new TreeSet( Collections.list( props.keys() ) ); + for ( Iterator ki = keys.iterator(); ki.hasNext(); ) + { + String key = ( String ) ki.next(); + buf.append( key ).append( " = " ); + + Object prop = props.get( key ); + if ( prop.getClass().isArray() ) + { + prop = Arrays.asList( ( Object[] ) prop ); } - buf.append(prop); - if (ki.hasNext()) { - buf.append("
"); + buf.append( prop ); + if ( ki.hasNext() ) + { + buf.append( "
" ); } } - keyVal(jsonProps, "Properties", buf.toString()); + keyVal( jsonProps, "Properties", buf.toString() ); } } - private void keyVal(JSONArray props, String key, Object value) { - if (key != null && value != null) { - try { + + private void keyVal( JSONArray props, String key, Object value ) + { + if ( key != null && value != null ) + { + try + { JSONObject obj = new JSONObject(); - obj.put("key", key); - obj.put("value", value); - props.put(obj); - } catch (JSONException je) { + obj.put( "key", key ); + obj.put( "value", value ); + props.put( obj ); + } + catch ( JSONException je ) + { // don't care } } } - static String toStateString(int state) { - switch (state) { + + static String toStateString( int state ) + { + switch ( state ) + { case Component.STATE_DISABLED: return "disabled"; case Component.STATE_ENABLED: @@ -410,16 +457,22 @@ static String toStateString(int state) { case Component.STATE_DESTROYED: return "destroyed"; default: - return String.valueOf(state); + return String.valueOf( state ); } } - protected long getComponentId(HttpServletRequest request) { - String componentIdPar = request.getParameter(ComponentRenderAction.COMPONENT_ID); - if (componentIdPar != null) { - try { - return Long.parseLong(componentIdPar); - } catch (NumberFormatException nfe) { + + protected long getComponentId( HttpServletRequest request ) + { + String componentIdPar = request.getParameter( ComponentRenderAction.COMPONENT_ID ); + if ( componentIdPar != null ) + { + try + { + return Long.parseLong( componentIdPar ); + } + catch ( NumberFormatException nfe ) + { // TODO: log } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManager.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManager.java index 006558c914b..0a43e07309c 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManager.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManager.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.compendium; + import java.io.IOException; import java.io.PrintWriter; import java.util.Dictionary; @@ -40,10 +41,12 @@ import org.osgi.service.cm.ManagedServiceFactory; import org.osgi.service.metatype.ObjectClassDefinition; + /** * The ConfigManager TODO */ -public class ConfigManager extends ConfigManagerBase implements Render { +public class ConfigManager extends ConfigManagerBase implements Render +{ public static final String NAME = "configMgr"; @@ -51,128 +54,153 @@ public class ConfigManager extends ConfigManagerBase implements Render { public static final String PID = "pid"; - public String getLabel() { + + public String getLabel() + { return LABEL; } - public String getName() { + + public String getName() + { return NAME; } - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { + + public void render( HttpServletRequest request, HttpServletResponse response ) throws IOException + { // true if MetaType service information is not required boolean optionalMetaType = false; PrintWriter pw = response.getWriter(); - pw.println(""); + pw.println( "" ); - pw.println(""); + pw.println( "
" ); - pw.println(""); - pw.println(""); - pw.println(""); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); - pw.println("
Configurations"); - pw.println(""); - this.listConfigurations(pw, optionalMetaType, getLocale(request)); - pw.println("
Configurations" ); + pw.println( "" ); + this.listConfigurations( pw, optionalMetaType, getLocale( request ) ); + pw.println( "
"); + pw.println( "" ); } - private void listConfigurations(PrintWriter pw, boolean optionalMetaType, - Locale loc) { + + private void listConfigurations( PrintWriter pw, boolean optionalMetaType, Locale loc ) + { ConfigurationAdmin ca = this.getConfigurationAdmin(); - if (ca == null) { - pw.print("Configuration Admin Service not available"); + if ( ca == null ) + { + pw.print( "Configuration Admin Service not available" ); return; } - String locale = (loc != null) ? loc.toString() : null; + String locale = ( loc != null ) ? loc.toString() : null; - try { + try + { // get a list of all pids for which MetaData exists Map metaDataPids = this.getMetadataPids(); // sorted map of options - SortedMap options = new TreeMap(String.CASE_INSENSITIVE_ORDER); + SortedMap options = new TreeMap( String.CASE_INSENSITIVE_ORDER ); // find all ManagedServiceFactories to get the factoryPIDs ServiceReference[] refs = this.getBundleContext().getServiceReferences( - ManagedServiceFactory.class.getName(), null); - for (int i = 0; refs != null && i < refs.length; i++) { - Object factoryPid = refs[i].getProperty(Constants.SERVICE_PID); - if (factoryPid instanceof String) { - String pid = (String) factoryPid; + ManagedServiceFactory.class.getName(), null ); + for ( int i = 0; refs != null && i < refs.length; i++ ) + { + Object factoryPid = refs[i].getProperty( Constants.SERVICE_PID ); + if ( factoryPid instanceof String ) + { + String pid = ( String ) factoryPid; String name; - ObjectClassDefinition ocd = this.getObjectClassDefinition( - refs[i].getBundle(), pid, locale); - if (ocd != null) { + ObjectClassDefinition ocd = this.getObjectClassDefinition( refs[i].getBundle(), pid, locale ); + if ( ocd != null ) + { name = ocd.getName() + " ("; name += pid + ")"; - } else { + } + else + { name = pid; } - if (ocd != null || optionalMetaType) { - options.put("factoryPid=" + pid, name); + if ( ocd != null || optionalMetaType ) + { + options.put( "factoryPid=" + pid, name ); } } } // get a sorted list of configuration PIDs - Configuration[] cfgs = ca.listConfigurations(null); - for (int i = 0; cfgs != null && i < cfgs.length; i++) { + Configuration[] cfgs = ca.listConfigurations( null ); + for ( int i = 0; cfgs != null && i < cfgs.length; i++ ) + { // ignore configuration object if an entry already exists in the // map String pid = cfgs[i].getPid(); - if (options.containsKey("pid=" + pid) - || options.containsKey("factoryPid=" + pid)) { + if ( options.containsKey( "pid=" + pid ) || options.containsKey( "factoryPid=" + pid ) ) + { continue; } Dictionary props = cfgs[i].getProperties(); // insert and entry for the pid - ObjectClassDefinition ocd = this.getObjectClassDefinition( - cfgs[i], locale); + ObjectClassDefinition ocd = this.getObjectClassDefinition( cfgs[i], locale ); String name; - if (ocd != null) { + if ( ocd != null ) + { name = ocd.getName() + " ("; name += pid + ")"; // remove from the list of known pids - metaDataPids.remove(pid); + metaDataPids.remove( pid ); - } else { + } + else + { name = pid; } - if (ocd != null || optionalMetaType) { - options.put("pid=" + pid, name); + if ( ocd != null || optionalMetaType ) + { + options.put( "pid=" + pid, name ); } // if the configuration is part of a factory, ensure an entry // for the factory - if (cfgs[i].getFactoryPid() != null) { + if ( cfgs[i].getFactoryPid() != null ) + { pid = cfgs[i].getFactoryPid(); - if (options.containsValue("factoryPid=" + pid)) { + if ( options.containsValue( "factoryPid=" + pid ) ) + { continue; } - String existing = (String) options.remove("pid=" + pid); - if (existing != null) { - options.put("factoryPid=" + pid, existing); - } else { - Bundle bundle = this.getBundle(cfgs[i].getBundleLocation()); - ocd = this.getObjectClassDefinition(bundle, pid, locale); - if (ocd != null) { - options.put("factoryPid=" + pid, ocd.getName()); - } else if (optionalMetaType) { - options.put("factoryPid=" + pid, pid); + String existing = ( String ) options.remove( "pid=" + pid ); + if ( existing != null ) + { + options.put( "factoryPid=" + pid, existing ); + } + else + { + Bundle bundle = this.getBundle( cfgs[i].getBundleLocation() ); + ocd = this.getObjectClassDefinition( bundle, pid, locale ); + if ( ocd != null ) + { + options.put( "factoryPid=" + pid, ocd.getName() ); + } + else if ( optionalMetaType ) + { + options.put( "factoryPid=" + pid, pid ); } } } @@ -180,32 +208,36 @@ private void listConfigurations(PrintWriter pw, boolean optionalMetaType, // If there are any meta data PIDs for which there is no existing // configuration, we add them to the list to create configuration - if (!metaDataPids.isEmpty()) { - for(Iterator mdpi=metaDataPids.entrySet().iterator(); mdpi.hasNext(); ) { - Entry mdp = (Entry) mdpi.next(); - ObjectClassDefinition ocd = this.getObjectClassDefinition( - (Bundle) mdp.getValue(), (String) mdp.getKey(), locale); - options.put("pid=" + mdp.getKey(), ocd.getName() + " (" - + mdp.getKey() + ")"); + if ( !metaDataPids.isEmpty() ) + { + for ( Iterator mdpi = metaDataPids.entrySet().iterator(); mdpi.hasNext(); ) + { + Entry mdp = ( Entry ) mdpi.next(); + ObjectClassDefinition ocd = this.getObjectClassDefinition( ( Bundle ) mdp.getValue(), + ( String ) mdp.getKey(), locale ); + options.put( "pid=" + mdp.getKey(), ocd.getName() + " (" + mdp.getKey() + ")" ); } } - pw.println("
"); - pw.println("" ); + for ( Iterator ei = options.entrySet().iterator(); ei.hasNext(); ) + { + Entry entry = ( Entry ) ei.next(); + pw.print( "" ); } - pw.println(""); - pw.println("  "); - pw.println(""); - pw.println("
"); + pw.println( "" ); + pw.println( "  " ); + pw.println( "" ); + pw.println( "" ); - } catch (Exception e) { + } + catch ( Exception e ) + { // write a message or ignore } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManagerBase.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManagerBase.java index 90fc49e7f72..5a5de807659 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManagerBase.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/compendium/ConfigManagerBase.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.compendium; + import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -33,53 +34,71 @@ import org.osgi.service.metatype.ObjectClassDefinition; import org.osgi.util.tracker.ServiceTracker; + /** * The ConfigManagerBase TODO * */ -abstract class ConfigManagerBase extends BaseManagementPlugin { +abstract class ConfigManagerBase extends BaseManagementPlugin +{ private ServiceTracker configurationAdmin; private ServiceTracker metaTypeService; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); - - configurationAdmin = new ServiceTracker(bundleContext, ConfigurationAdmin.class.getName(), null); + + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); + + configurationAdmin = new ServiceTracker( bundleContext, ConfigurationAdmin.class.getName(), null ); configurationAdmin.open(); - metaTypeService = new ServiceTracker(bundleContext, MetaTypeService.class.getName(), null); + metaTypeService = new ServiceTracker( bundleContext, MetaTypeService.class.getName(), null ); metaTypeService.open(); } - - public void destroy() { - if (configurationAdmin != null) { + + + public void destroy() + { + if ( configurationAdmin != null ) + { configurationAdmin.close(); } - if (metaTypeService != null) { + if ( metaTypeService != null ) + { metaTypeService.close(); } } - - protected ConfigurationAdmin getConfigurationAdmin() { - return (ConfigurationAdmin) configurationAdmin.getService(); + + + protected ConfigurationAdmin getConfigurationAdmin() + { + return ( ConfigurationAdmin ) configurationAdmin.getService(); } - protected MetaTypeService getMetaTypeService() { - return (MetaTypeService) metaTypeService.getService(); + + protected MetaTypeService getMetaTypeService() + { + return ( MetaTypeService ) metaTypeService.getService(); } - protected Map getMetadataPids() { + + protected Map getMetadataPids() + { Map pids = new HashMap(); MetaTypeService mts = this.getMetaTypeService(); - if (mts != null) { + if ( mts != null ) + { Bundle[] bundles = this.getBundleContext().getBundles(); - for (int i = 0; i < bundles.length; i++) { - MetaTypeInformation mti = mts.getMetaTypeInformation(bundles[i]); - if (mti != null) { + for ( int i = 0; i < bundles.length; i++ ) + { + MetaTypeInformation mti = mts.getMetaTypeInformation( bundles[i] ); + if ( mti != null ) + { String[] pidList = mti.getPids(); - for (int j = 0; pidList != null && j < pidList.length; j++) { - pids.put(pidList[j], bundles[i]); + for ( int j = 0; pidList != null && j < pidList.length; j++ ) + { + pids.put( pidList[j], bundles[i] ); } } } @@ -87,42 +106,47 @@ protected Map getMetadataPids() { return pids; } - protected ObjectClassDefinition getObjectClassDefinition( - Configuration config, String locale) { + + protected ObjectClassDefinition getObjectClassDefinition( Configuration config, String locale ) + { // if the configuration is not bound, search in the bundles - if (config.getBundleLocation() == null) { - ObjectClassDefinition ocd = this.getObjectClassDefinition( - config.getPid(), locale); - if (ocd != null) { + if ( config.getBundleLocation() == null ) + { + ObjectClassDefinition ocd = this.getObjectClassDefinition( config.getPid(), locale ); + if ( ocd != null ) + { return ocd; } // if none, check whether there might be one for the factory PID - if (config.getFactoryPid() != null) { - return this.getObjectClassDefinition(config.getFactoryPid(), - locale); + if ( config.getFactoryPid() != null ) + { + return this.getObjectClassDefinition( config.getFactoryPid(), locale ); } } MetaTypeService mts = this.getMetaTypeService(); - if (mts != null) { - Bundle bundle = this.getBundle(config.getBundleLocation()); - if (bundle != null) { - MetaTypeInformation mti = mts.getMetaTypeInformation(bundle); - if (mti != null) { + if ( mts != null ) + { + Bundle bundle = this.getBundle( config.getBundleLocation() ); + if ( bundle != null ) + { + MetaTypeInformation mti = mts.getMetaTypeInformation( bundle ); + if ( mti != null ) + { // try OCD by PID first - ObjectClassDefinition ocd = mti.getObjectClassDefinition( - config.getPid(), locale); - if (ocd != null) { + ObjectClassDefinition ocd = mti.getObjectClassDefinition( config.getPid(), locale ); + if ( ocd != null ) + { return ocd; } // if none, check whether there might be one for the factory // PID - if (config.getFactoryPid() != null) { - return mti.getObjectClassDefinition( - config.getFactoryPid(), locale); + if ( config.getFactoryPid() != null ) + { + return mti.getObjectClassDefinition( config.getFactoryPid(), locale ); } } } @@ -132,14 +156,18 @@ protected ObjectClassDefinition getObjectClassDefinition( return null; } - protected ObjectClassDefinition getObjectClassDefinition(Bundle bundle, - String pid, String locale) { - if (bundle != null) { + + protected ObjectClassDefinition getObjectClassDefinition( Bundle bundle, String pid, String locale ) + { + if ( bundle != null ) + { MetaTypeService mts = this.getMetaTypeService(); - if (mts != null) { - MetaTypeInformation mti = mts.getMetaTypeInformation(bundle); - if (mti != null) { - return mti.getObjectClassDefinition(pid, locale); + if ( mts != null ) + { + MetaTypeInformation mti = mts.getMetaTypeInformation( bundle ); + if ( mti != null ) + { + return mti.getObjectClassDefinition( pid, locale ); } } } @@ -148,33 +176,41 @@ protected ObjectClassDefinition getObjectClassDefinition(Bundle bundle, return null; } - protected ObjectClassDefinition getObjectClassDefinition(String pid, - String locale) { + + protected ObjectClassDefinition getObjectClassDefinition( String pid, String locale ) + { Bundle[] bundles = this.getBundleContext().getBundles(); - for (int i = 0; i < bundles.length; i++) { - try { - ObjectClassDefinition ocd = this.getObjectClassDefinition( - bundles[i], pid, locale); - if (ocd != null) { + for ( int i = 0; i < bundles.length; i++ ) + { + try + { + ObjectClassDefinition ocd = this.getObjectClassDefinition( bundles[i], pid, locale ); + if ( ocd != null ) + { return ocd; } - } catch (IllegalArgumentException iae) { + } + catch ( IllegalArgumentException iae ) + { // don't care } } return null; } - protected Map getAttributeDefinitionMap( - Configuration config, String locale) { - ObjectClassDefinition ocd = this.getObjectClassDefinition(config, - locale); - if (ocd != null) { - AttributeDefinition[] ad = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL); - if (ad != null) { + + protected Map getAttributeDefinitionMap( Configuration config, String locale ) + { + ObjectClassDefinition ocd = this.getObjectClassDefinition( config, locale ); + if ( ocd != null ) + { + AttributeDefinition[] ad = ocd.getAttributeDefinitions( ObjectClassDefinition.ALL ); + if ( ad != null ) + { Map adMap = new HashMap(); - for (int i = 0; i < ad.length; i++) { - adMap.put(ad[i].getID(), ad[i]); + for ( int i = 0; i < ad.length; i++ ) + { + adMap.put( ad[i].getID(), ad[i] ); } return adMap; } @@ -184,14 +220,19 @@ protected Map getAttributeDefinitionMap( return null; } - protected Bundle getBundle(String bundleLocation) { - if (bundleLocation == null) { + + protected Bundle getBundle( String bundleLocation ) + { + if ( bundleLocation == null ) + { return null; } Bundle[] bundles = this.getBundleContext().getBundles(); - for (int i = 0; i < bundles.length; i++) { - if (bundleLocation.equals(bundles[i].getLocation())) { + for ( int i = 0; i < bundles.length; i++ ) + { + if ( bundleLocation.equals( bundles[i].getLocation() ) ) + { return bundles[i]; } } @@ -199,10 +240,15 @@ protected Bundle getBundle(String bundleLocation) { return null; } - protected Locale getLocale(HttpServletRequest request) { - try { + + protected Locale getLocale( HttpServletRequest request ) + { + try + { return request.getLocale(); - } catch (Throwable t) { + } + catch ( Throwable t ) + { // expected in standard OSGi Servlet 2.1 environments // fallback to using the default locale return Locale.getDefault(); diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/AjaxBundleDetailsAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/AjaxBundleDetailsAction.java index 663c65935fd..6fdba1af1f4 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/AjaxBundleDetailsAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/AjaxBundleDetailsAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -50,7 +51,9 @@ import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; -public class AjaxBundleDetailsAction extends BundleAction { + +public class AjaxBundleDetailsAction extends BundleAction +{ public static final String NAME = "ajaxBundleDetails"; @@ -65,136 +68,166 @@ public class AjaxBundleDetailsAction extends BundleAction { // see #activate and #isBootDelegated private boolean[] bootPkgWildcards; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); + + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); // bootdelegation property parsing from Apache Felix R4SearchPolicyCore - String bootDelegation = bundleContext.getProperty(Constants.FRAMEWORK_BOOTDELEGATION); - bootDelegation = (bootDelegation == null) ? "java.*" : bootDelegation - + ",java.*"; - StringTokenizer st = new StringTokenizer(bootDelegation, " ,"); + String bootDelegation = bundleContext.getProperty( Constants.FRAMEWORK_BOOTDELEGATION ); + bootDelegation = ( bootDelegation == null ) ? "java.*" : bootDelegation + ",java.*"; + StringTokenizer st = new StringTokenizer( bootDelegation, " ," ); bootPkgs = new String[st.countTokens()]; bootPkgWildcards = new boolean[bootPkgs.length]; - for (int i = 0; i < bootPkgs.length; i++) { + for ( int i = 0; i < bootPkgs.length; i++ ) + { bootDelegation = st.nextToken(); - if (bootDelegation.endsWith("*")) { + if ( bootDelegation.endsWith( "*" ) ) + { bootPkgWildcards[i] = true; - bootDelegation = bootDelegation.substring(0, - bootDelegation.length() - 1); + bootDelegation = bootDelegation.substring( 0, bootDelegation.length() - 1 ); } bootPkgs[i] = bootDelegation; } } - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return NAME; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) throws IOException { + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) throws IOException + { JSONObject result = null; - try { - long bundleId = getBundleId(request); - Bundle bundle = getBundleContext().getBundle(bundleId); - if (bundle != null) { + try + { + long bundleId = getBundleId( request ); + Bundle bundle = getBundleContext().getBundle( bundleId ); + if ( bundle != null ) + { Dictionary headers = bundle.getHeaders(); JSONArray props = new JSONArray(); - keyVal(props, "Symbolic Name", bundle.getSymbolicName()); - keyVal(props, "Version", headers.get(Constants.BUNDLE_VERSION)); - keyVal(props, "Location", bundle.getLocation()); - keyVal(props, "Last Modification", new Date( - bundle.getLastModified())); - - keyVal(props, "Vendor", headers.get(Constants.BUNDLE_VENDOR)); - keyVal(props, "Copyright", - headers.get(Constants.BUNDLE_COPYRIGHT)); - keyVal(props, "Description", - headers.get(Constants.BUNDLE_DESCRIPTION)); - - keyVal(props, "Start Level", getStartLevel(bundle)); - - if (bundle.getState() == Bundle.INSTALLED) { - listImportExportsUnresolved(props, bundle); - } else { - listImportExport(props, bundle); + keyVal( props, "Symbolic Name", bundle.getSymbolicName() ); + keyVal( props, "Version", headers.get( Constants.BUNDLE_VERSION ) ); + keyVal( props, "Location", bundle.getLocation() ); + keyVal( props, "Last Modification", new Date( bundle.getLastModified() ) ); + + keyVal( props, "Vendor", headers.get( Constants.BUNDLE_VENDOR ) ); + keyVal( props, "Copyright", headers.get( Constants.BUNDLE_COPYRIGHT ) ); + keyVal( props, "Description", headers.get( Constants.BUNDLE_DESCRIPTION ) ); + + keyVal( props, "Start Level", getStartLevel( bundle ) ); + + if ( bundle.getState() == Bundle.INSTALLED ) + { + listImportExportsUnresolved( props, bundle ); + } + else + { + listImportExport( props, bundle ); } - listServices(props, bundle); + listServices( props, bundle ); result = new JSONObject(); - result.put(BundleListRender.BUNDLE_ID, bundleId); - result.put("props", props); + result.put( BundleListRender.BUNDLE_ID, bundleId ); + result.put( "props", props ); } - } catch (Exception exception) { + } + catch ( Exception exception ) + { // create an empty result on problems result = new JSONObject(); } // send the result - response.setContentType("text/javascript"); - response.getWriter().print(result.toString()); + response.setContentType( "text/javascript" ); + response.getWriter().print( result.toString() ); return false; } - private Integer getStartLevel(Bundle bundle) { + + private Integer getStartLevel( Bundle bundle ) + { StartLevel sl = getStartLevel(); - return (sl != null) ? new Integer(sl.getBundleStartLevel(bundle)) : null; + return ( sl != null ) ? new Integer( sl.getBundleStartLevel( bundle ) ) : null; } - private void listImportExport(JSONArray props, Bundle bundle) { + + private void listImportExport( JSONArray props, Bundle bundle ) + { PackageAdmin packageAdmin = getPackageAdmin(); - if (packageAdmin == null) { + if ( packageAdmin == null ) + { return; } Map usingBundles = new TreeMap(); - ExportedPackage[] exports = packageAdmin.getExportedPackages(bundle); - if (exports != null && exports.length > 0) { + ExportedPackage[] exports = packageAdmin.getExportedPackages( bundle ); + if ( exports != null && exports.length > 0 ) + { // do alphabetical sort - Arrays.sort(exports, new Comparator() { - public int compare(ExportedPackage p1, ExportedPackage p2) { - return p1.getName().compareTo(p2.getName()); + Arrays.sort( exports, new Comparator() + { + public int compare( ExportedPackage p1, ExportedPackage p2 ) + { + return p1.getName().compareTo( p2.getName() ); } - public int compare(Object o1, Object o2) { - return compare((ExportedPackage) o1, (ExportedPackage) o2); + + public int compare( Object o1, Object o2 ) + { + return compare( ( ExportedPackage ) o1, ( ExportedPackage ) o2 ); } - }); + } ); StringBuffer val = new StringBuffer(); - for (int j=0; j < exports.length; j++) { + for ( int j = 0; j < exports.length; j++ ) + { ExportedPackage export = exports[j]; - printExport(val, export.getName(), export.getVersion()); + printExport( val, export.getName(), export.getVersion() ); Bundle[] ubList = export.getImportingBundles(); - if (ubList != null) { - for (int i=0; i < ubList.length; i++) { + if ( ubList != null ) + { + for ( int i = 0; i < ubList.length; i++ ) + { Bundle ub = ubList[i]; - usingBundles.put(ub.getSymbolicName(), ub); + usingBundles.put( ub.getSymbolicName(), ub ); } } } - keyVal(props, "Exported Packages", val.toString()); - } else { - keyVal(props, "Exported Packages", "None"); + keyVal( props, "Exported Packages", val.toString() ); + } + else + { + keyVal( props, "Exported Packages", "None" ); } - exports = packageAdmin.getExportedPackages((Bundle) null); - if (exports != null && exports.length > 0) { + 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++) { + 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.add(ep); + for ( int j = 0; importers != null && j < importers.length; j++ ) + { + if ( importers[j].getBundleId() == bundle.getBundleId() ) + { + imports.add( ep ); break; } @@ -202,94 +235,122 @@ public int compare(Object o1, Object o2) { } // now sort StringBuffer val = new StringBuffer(); - if (imports.size() > 0) { - final ExportedPackage[] packages = (ExportedPackage[]) imports.toArray(new ExportedPackage[imports.size()]); - Arrays.sort(packages, new Comparator() { - public int compare(ExportedPackage p1, ExportedPackage p2) { - return p1.getName().compareTo(p2.getName()); + if ( imports.size() > 0 ) + { + final ExportedPackage[] packages = ( ExportedPackage[] ) imports.toArray( new ExportedPackage[imports + .size()] ); + Arrays.sort( packages, new Comparator() + { + public int compare( ExportedPackage p1, ExportedPackage p2 ) + { + return p1.getName().compareTo( p2.getName() ); } - public int compare(Object o1, Object o2) { - return compare((ExportedPackage) o1, - (ExportedPackage) o2); + + public int compare( Object o1, Object o2 ) + { + return compare( ( ExportedPackage ) o1, ( ExportedPackage ) o2 ); } - }); + } ); // and finally print out - for (int i=0; i < packages.length; i++) { + for ( int i = 0; i < packages.length; i++ ) + { ExportedPackage ep = packages[i]; - printImport(val, ep.getName(), ep.getVersion(), ep); + printImport( val, ep.getName(), ep.getVersion(), ep ); } - } else { + } + else + { // add description if there are no imports - val.append("None"); + val.append( "None" ); } - keyVal(props, "Imported Packages", val.toString()); + keyVal( props, "Imported Packages", val.toString() ); } - if (!usingBundles.isEmpty()) { + if ( !usingBundles.isEmpty() ) + { StringBuffer val = new StringBuffer(); - for (Iterator ui = usingBundles.values().iterator(); ui.hasNext();) { - Bundle usingBundle = (Bundle) ui.next(); - val.append(getBundleDescriptor(usingBundle)); - val.append("
"); + for ( Iterator ui = usingBundles.values().iterator(); ui.hasNext(); ) + { + Bundle usingBundle = ( Bundle ) ui.next(); + val.append( getBundleDescriptor( usingBundle ) ); + val.append( "
" ); } - keyVal(props, "Importing Bundles", val.toString()); + keyVal( props, "Importing Bundles", val.toString() ); } } - private void listImportExportsUnresolved(JSONArray props, Bundle bundle) { + + private void listImportExportsUnresolved( JSONArray props, Bundle bundle ) + { Dictionary dict = bundle.getHeaders(); - String target = (String) dict.get(Constants.EXPORT_PACKAGE); - if (target != null) { - R4Package[] pkgs = R4Package.parseImportOrExportHeader(target); - if (pkgs != null && pkgs.length > 0) { + String target = ( String ) dict.get( Constants.EXPORT_PACKAGE ); + if ( target != null ) + { + R4Package[] pkgs = R4Package.parseImportOrExportHeader( target ); + if ( pkgs != null && pkgs.length > 0 ) + { // do alphabetical sort - Arrays.sort(pkgs, new Comparator() { - public int compare(R4Package p1, R4Package p2) { - return p1.getName().compareTo(p2.getName()); + Arrays.sort( pkgs, new Comparator() + { + public int compare( R4Package p1, R4Package p2 ) + { + return p1.getName().compareTo( p2.getName() ); } - public int compare(Object o1, Object o2) { - return compare((R4Package) o1, (R4Package) o2); + + public int compare( Object o1, Object o2 ) + { + return compare( ( R4Package ) o1, ( R4Package ) o2 ); } - }); + } ); StringBuffer val = new StringBuffer(); - for (int i=0; i < pkgs.length; i++) { - R4Export export = new R4Export(pkgs[i]); - printExport(val, export.getName(), export.getVersion()); + for ( int i = 0; i < pkgs.length; i++ ) + { + R4Export export = new R4Export( pkgs[i] ); + printExport( val, export.getName(), export.getVersion() ); } - keyVal(props, "Exported Packages", val.toString()); - } else { - keyVal(props, "Exported Packages", "None"); + keyVal( props, "Exported Packages", val.toString() ); + } + else + { + keyVal( props, "Exported Packages", "None" ); } } - target = (String) dict.get(Constants.IMPORT_PACKAGE); - if (target != null) { - R4Package[] pkgs = R4Package.parseImportOrExportHeader(target); - if (pkgs != null && pkgs.length > 0) { + target = ( String ) dict.get( Constants.IMPORT_PACKAGE ); + if ( target != null ) + { + R4Package[] pkgs = R4Package.parseImportOrExportHeader( target ); + if ( pkgs != null && pkgs.length > 0 ) + { Map imports = new TreeMap(); - for (int i=0; i < pkgs.length; i++) { + for ( int i = 0; i < pkgs.length; i++ ) + { R4Package pkg = pkgs[i]; - imports.put(pkg.getName(), new R4Import(pkg)); + imports.put( pkg.getName(), new R4Import( pkg ) ); } // 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++) { + 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.get(ep.getName()); - if (imp != null && imp.isSatisfied(toR4Export(ep))) { - candidates.put(ep.getName(), ep); + R4Import imp = ( R4Import ) imports.get( ep.getName() ); + if ( imp != null && imp.isSatisfied( toR4Export( ep ) ) ) + { + candidates.put( ep.getName(), ep ); } } } @@ -297,150 +358,180 @@ public int compare(Object o1, Object o2) { // now sort StringBuffer val = new StringBuffer(); - if (imports.size() > 0) { - for (Iterator ii = imports.values().iterator(); ii.hasNext();) { - R4Import r4Import = (R4Import) ii.next(); - ExportedPackage ep = (ExportedPackage) candidates.get(r4Import.getName()); + if ( imports.size() > 0 ) + { + for ( Iterator ii = imports.values().iterator(); ii.hasNext(); ) + { + R4Import r4Import = ( R4Import ) ii.next(); + ExportedPackage ep = ( ExportedPackage ) candidates.get( r4Import.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.getResource(path) != null) { + if ( ep == null ) + { + String path = r4Import.getName().replace( '.', '/' ); + if ( bundle.getResource( path ) != null ) + { continue; } } - printImport(val, r4Import.getName(), - r4Import.getVersion(), ep); + printImport( val, r4Import.getName(), r4Import.getVersion(), ep ); } - } else { + } + else + { // add description if there are no imports - val.append("None"); + val.append( "None" ); } - keyVal(props, "Imported Packages", val.toString()); + keyVal( props, "Imported Packages", val.toString() ); } } } - private void listServices(JSONArray props, Bundle bundle) { + + private void listServices( JSONArray props, Bundle bundle ) + { ServiceReference[] refs = bundle.getRegisteredServices(); - if (refs == null || refs.length == 0) { + if ( refs == null || refs.length == 0 ) + { return; } - for (int i = 0; i < refs.length; i++) { - String key = "Service ID " - + refs[i].getProperty(Constants.SERVICE_ID); + for ( int i = 0; i < refs.length; i++ ) + { + String key = "Service ID " + refs[i].getProperty( Constants.SERVICE_ID ); StringBuffer val = new StringBuffer(); - appendProperty(val, refs[i], Constants.OBJECTCLASS, "Types"); - appendProperty(val, refs[i], Constants.SERVICE_PID, "PID"); - appendProperty(val, refs[i], ConfigurationAdmin.SERVICE_FACTORYPID, - "Factory PID"); - appendProperty(val, refs[i], ComponentConstants.COMPONENT_NAME, - "Component Name"); - appendProperty(val, refs[i], ComponentConstants.COMPONENT_ID, - "Component ID"); - appendProperty(val, refs[i], ComponentConstants.COMPONENT_FACTORY, - "Component Factory"); - appendProperty(val, refs[i], Constants.SERVICE_DESCRIPTION, - "Description"); - appendProperty(val, refs[i], Constants.SERVICE_VENDOR, "Vendor"); - - keyVal(props, key, val.toString()); + appendProperty( val, refs[i], Constants.OBJECTCLASS, "Types" ); + appendProperty( val, refs[i], Constants.SERVICE_PID, "PID" ); + appendProperty( val, refs[i], ConfigurationAdmin.SERVICE_FACTORYPID, "Factory PID" ); + appendProperty( val, refs[i], ComponentConstants.COMPONENT_NAME, "Component Name" ); + appendProperty( val, refs[i], ComponentConstants.COMPONENT_ID, "Component ID" ); + appendProperty( val, refs[i], ComponentConstants.COMPONENT_FACTORY, "Component Factory" ); + appendProperty( val, refs[i], Constants.SERVICE_DESCRIPTION, "Description" ); + appendProperty( val, refs[i], Constants.SERVICE_VENDOR, "Vendor" ); + + keyVal( props, key, val.toString() ); } } - private void appendProperty(StringBuffer dest, ServiceReference ref, - String name, String label) { - Object value = ref.getProperty(name); - if (value instanceof Object[]) { - Object[] values = (Object[]) value; - dest.append(label).append(": "); - for (int j = 0; j < values.length; j++) { - if (j > 0) dest.append(", "); - dest.append(values[j]); + + private void appendProperty( StringBuffer dest, ServiceReference ref, String name, String label ) + { + Object value = ref.getProperty( name ); + if ( value instanceof Object[] ) + { + Object[] values = ( Object[] ) value; + dest.append( label ).append( ": " ); + for ( int j = 0; j < values.length; j++ ) + { + if ( j > 0 ) + dest.append( ", " ); + dest.append( values[j] ); } - dest.append("
"); // assume HTML use of result - } else if (value != null) { - dest.append(label).append(": ").append(value).append("
"); + dest.append( "
" ); // assume HTML use of result + } + else if ( value != null ) + { + dest.append( label ).append( ": " ).append( value ).append( "
" ); } } - private void keyVal(JSONArray props, String key, Object value) { - if (key != null && value != null) { - try { + + private void keyVal( JSONArray props, String key, Object value ) + { + if ( key != null && value != null ) + { + try + { JSONObject obj = new JSONObject(); - obj.put("key", key); - obj.put("value", value); - props.put(obj); - } catch (JSONException je) { + obj.put( "key", key ); + obj.put( "value", value ); + props.put( obj ); + } + catch ( JSONException je ) + { // don't care } } } - private void printExport(StringBuffer val, String name, Version version) { - boolean bootDel = isBootDelegated(name); - if (bootDel) { - val.append("!! "); + + private void printExport( StringBuffer val, String name, Version version ) + { + boolean bootDel = isBootDelegated( name ); + if ( bootDel ) + { + val.append( "!! " ); } - val.append(name); - val.append(",version="); - val.append(version); + val.append( name ); + val.append( ",version=" ); + val.append( version ); - if (bootDel) { - val.append(" -- Overwritten by Boot Delegation"); + if ( bootDel ) + { + val.append( " -- Overwritten by Boot Delegation" ); } - val.append("
"); + val.append( "
" ); } - private void printImport(StringBuffer val, String name, Version version, - ExportedPackage export) { - boolean bootDel = isBootDelegated(name); - if (bootDel || export == null) { - val.append("!! "); + + private void printImport( StringBuffer val, String name, Version version, ExportedPackage export ) + { + boolean bootDel = isBootDelegated( name ); + if ( bootDel || export == null ) + { + val.append( "!! " ); } - val.append(name); - val.append(",version=").append(version); - val.append(" from "); + val.append( name ); + val.append( ",version=" ).append( version ); + val.append( " from " ); - if (export != null) { - val.append(getBundleDescriptor(export.getExportingBundle())); + if ( export != null ) + { + val.append( getBundleDescriptor( export.getExportingBundle() ) ); - if (bootDel) { - val.append(" -- Overwritten by Boot Delegation"); + if ( bootDel ) + { + val.append( " -- Overwritten by Boot Delegation" ); } - } else { - val.append(" -- Cannot be resolved"); - if (bootDel) { - val.append(" and overwritten by Boot Delegation"); + } + else + { + val.append( " -- Cannot be resolved" ); + if ( bootDel ) + { + val.append( " and overwritten by Boot Delegation" ); } - val.append(""); + val.append( "" ); } - val.append("
"); + val.append( "
" ); } + // returns true if the package is listed in the bootdelegation property - private boolean isBootDelegated(String pkgName) { + private boolean isBootDelegated( String pkgName ) + { // bootdelegation analysis from Apache Felix R4SearchPolicyCore // Only consider delegation if we have a package name, since // we don't want to promote the default package. The spec does // not take a stand on this issue. - if (pkgName.length() > 0) { + if ( pkgName.length() > 0 ) + { // Delegate any packages listed in the boot delegation // property to the parent class loader. - for (int i = 0; i < bootPkgs.length; i++) { + for ( int i = 0; i < bootPkgs.length; i++ ) + { // A wildcarded boot delegation package will be in the form of // "foo.", so if the package is wildcarded do a startsWith() or @@ -449,9 +540,10 @@ private boolean isBootDelegated(String pkgName) { // If the package is not wildcarded, then simply do an equals() // test to see if the request should be delegated to the parent // class loader. - if ((bootPkgWildcards[i] && (pkgName.startsWith(bootPkgs[i]) || bootPkgs[i].regionMatches( - 0, pkgName, 0, pkgName.length()))) - || (!bootPkgWildcards[i] && bootPkgs[i].equals(pkgName))) { + if ( ( bootPkgWildcards[i] && ( pkgName.startsWith( bootPkgs[i] ) || bootPkgs[i].regionMatches( 0, + pkgName, 0, pkgName.length() ) ) ) + || ( !bootPkgWildcards[i] && bootPkgs[i].equals( pkgName ) ) ) + { return true; } } @@ -460,29 +552,37 @@ private boolean isBootDelegated(String pkgName) { return false; } - private R4Export toR4Export(ExportedPackage export) { - R4Attribute version = new R4Attribute(Constants.VERSION_ATTRIBUTE, - export.getVersion().toString(), false); - return new R4Export(export.getName(), null, - new R4Attribute[] { version }); + + private R4Export toR4Export( ExportedPackage export ) + { + R4Attribute version = new R4Attribute( Constants.VERSION_ATTRIBUTE, export.getVersion().toString(), false ); + return new R4Export( export.getName(), null, new R4Attribute[] + { version } ); } - private String getBundleDescriptor(Bundle bundle) { + + private String getBundleDescriptor( Bundle bundle ) + { StringBuffer val = new StringBuffer(); - if (bundle.getSymbolicName() != null) { + if ( bundle.getSymbolicName() != null ) + { // list the bundle name if not null - val.append(bundle.getSymbolicName()); - val.append(" (").append(bundle.getBundleId()); - val.append(")"); - } else if (bundle.getLocation() != null) { + val.append( bundle.getSymbolicName() ); + val.append( " (" ).append( bundle.getBundleId() ); + val.append( ")" ); + } + else if ( bundle.getLocation() != null ) + { // otherwise try the location - val.append(bundle.getLocation()); - val.append(" (").append(bundle.getBundleId()); - val.append(")"); - } else { + val.append( bundle.getLocation() ); + val.append( " (" ).append( bundle.getBundleId() ); + val.append( ")" ); + } + else + { // fallback to just the bundle id // only append the bundle - val.append(bundle.getBundleId()); + val.append( bundle.getBundleId() ); } return val.toString(); } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleAction.java index 71d0e196051..f68f46ede00 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleAction.java @@ -16,19 +16,27 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import org.apache.felix.webconsole.Action; import org.apache.felix.webconsole.internal.BaseManagementPlugin; -abstract class BundleAction extends BaseManagementPlugin implements Action { - protected long getBundleId(HttpServletRequest request) { - String bundleIdPar = request.getParameter(BundleListRender.BUNDLE_ID); - if (bundleIdPar != null) { - try { - return Long.parseLong(bundleIdPar); - } catch (NumberFormatException nfe) { +abstract class BundleAction extends BaseManagementPlugin implements Action +{ + + protected long getBundleId( HttpServletRequest request ) + { + String bundleIdPar = request.getParameter( BundleListRender.BUNDLE_ID ); + if ( bundleIdPar != null ) + { + try + { + return Long.parseLong( bundleIdPar ); + } + catch ( NumberFormatException nfe ) + { // TODO: log } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleListRender.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleListRender.java index a8c041d245a..7498d7f33e4 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleListRender.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundleListRender.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; @@ -33,10 +34,12 @@ import org.osgi.framework.Version; import org.osgi.util.tracker.ServiceTracker; + /** * The BundleListRender TODO */ -public class BundleListRender extends BaseManagementPlugin implements Render { +public class BundleListRender extends BaseManagementPlugin implements Render +{ public static final String NAME = "list"; @@ -49,14 +52,16 @@ public class BundleListRender extends BaseManagementPlugin implements Render { // track the optional installer service manually private ServiceTracker installerService; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); - installerService = new ServiceTracker(bundleContext, - INSTALLER_SERVICE_NAME, null); + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); + + installerService = new ServiceTracker( bundleContext, INSTALLER_SERVICE_NAME, null ); installerService.open(); } + // protected void deactivate(ComponentContext context) { // if (installerService != null) { // installerService.close(); @@ -64,210 +69,220 @@ public void setBundleContext(BundleContext bundleContext) { // } // } - public String getName() { + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { + + public void render( HttpServletRequest request, HttpServletResponse response ) throws IOException + { PrintWriter pw = response.getWriter(); - this.header(pw); + this.header( pw ); - this.installForm(pw); - pw.println(""); - pw.println(" "); - pw.println(""); + this.installForm( pw ); + pw.println( "" ); + pw.println( " " ); + pw.println( "" ); - this.tableHeader(pw); + this.tableHeader( pw ); Bundle[] bundles = this.getBundles(); - if (bundles == null || bundles.length == 0) { - pw.println(""); - pw.println("No " + this.getLabel() - + " installed currently"); - pw.println(""); - } else { + if ( bundles == null || bundles.length == 0 ) + { + pw.println( "" ); + pw.println( "No " + this.getLabel() + " installed currently" ); + pw.println( "" ); + } + else + { - sort(bundles); + sort( bundles ); long previousBundle = -1; - for (int i = 0; i < bundles.length; i++) { + for ( int i = 0; i < bundles.length; i++ ) + { - if (previousBundle >= 0) { + if ( previousBundle >= 0 ) + { // prepare for injected table information row - pw.println(""); + pw.println( "" ); } - this.bundle(pw, bundles[i]); + this.bundle( pw, bundles[i] ); previousBundle = bundles[i].getBundleId(); } - if (previousBundle >= 0) { + if ( previousBundle >= 0 ) + { // prepare for injected table information row - pw.println(""); + pw.println( "" ); } } - pw.println(""); - pw.println(" "); - pw.println(""); + pw.println( "" ); + pw.println( " " ); + pw.println( "" ); - this.installForm(pw); + this.installForm( pw ); - this.footer(pw); + this.footer( pw ); } - protected Bundle[] getBundles() { + + protected Bundle[] getBundles() + { return getBundleContext().getBundles(); } - private void header(PrintWriter pw) { - Util.startScript(pw); - pw.println("function showDetails(bundleId) {"); - pw.println(" var span = document.getElementById('bundle' + bundleId);"); - pw.println(" if (!span) {"); - pw.println(" return;"); - pw.println(" }"); - pw.println(" if (span.innerHTML) {"); - pw.println(" span.innerHTML = '';"); - pw.println(" return;"); - pw.println(" }"); - pw.println(" var parm = '?" + Util.PARAM_ACTION + "=" - + AjaxBundleDetailsAction.NAME + "&" + BUNDLE_ID + "=' + bundleId;"); - pw.println(" sendRequest('GET', parm, displayBundleDetails);"); - pw.println("}"); - pw.println("function displayBundleDetails(obj) {"); - pw.println(" var span = document.getElementById('bundle' + obj." - + BUNDLE_ID + ");"); - pw.println(" if (!span) {"); - pw.println(" return;"); - pw.println(" }"); - pw.println(" var innerHtml = ' ';"); - pw.println(" var props = obj.props;"); - pw.println(" for (var i=0; i < props.length; i++) {"); - pw.println(" innerHtml += '';"); - pw.println(" }"); - pw.println(" innerHtml += '
' + props[i].key + '' + props[i].value + '
';"); - pw.println(" span.innerHTML = innerHtml;"); - pw.println("}"); - Util.endScript(pw); - - pw.println(""); + + private void header( PrintWriter pw ) + { + Util.startScript( pw ); + pw.println( "function showDetails(bundleId) {" ); + pw.println( " var span = document.getElementById('bundle' + bundleId);" ); + pw.println( " if (!span) {" ); + pw.println( " return;" ); + pw.println( " }" ); + pw.println( " if (span.innerHTML) {" ); + pw.println( " span.innerHTML = '';" ); + pw.println( " return;" ); + pw.println( " }" ); + pw.println( " var parm = '?" + Util.PARAM_ACTION + "=" + AjaxBundleDetailsAction.NAME + "&" + BUNDLE_ID + + "=' + bundleId;" ); + pw.println( " sendRequest('GET', parm, displayBundleDetails);" ); + pw.println( "}" ); + pw.println( "function displayBundleDetails(obj) {" ); + pw.println( " var span = document.getElementById('bundle' + obj." + BUNDLE_ID + ");" ); + pw.println( " if (!span) {" ); + pw.println( " return;" ); + pw.println( " }" ); + pw + .println( " var innerHtml = '';" ); + pw.println( " span.innerHTML = innerHtml;" ); + pw.println( "}" ); + Util.endScript( pw ); + + pw.println( "
 ';" ); + pw.println( " var props = obj.props;" ); + pw.println( " for (var i=0; i < props.length; i++) {" ); + pw + .println( " innerHtml += '';" ); + pw.println( " }" ); + pw.println( " innerHtml += '
' + props[i].key + '' + props[i].value + '
" ); } - private void tableHeader(PrintWriter pw) { + + private void tableHeader( PrintWriter pw ) + { // pw.println(""); // pw.println(""); // pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } - private void footer(PrintWriter pw) { - pw.println("
Installed " + // getLabel() + "
IDNameStatusActions
IDNameStatusActions
"); + + private void footer( PrintWriter pw ) + { + pw.println( "" ); } - private void bundle(PrintWriter pw, Bundle bundle) { - String name = getName(bundle); - pw.println(""); - pw.println("" + bundle.getBundleId() - + ""); - pw.println("" + name + ""); - pw.println("" - + this.toStateString(bundle.getState()) + ""); + private void bundle( PrintWriter pw, Bundle bundle ) + { + String name = getName( bundle ); + + pw.println( "" ); + pw.println( "" + bundle.getBundleId() + "" ); + pw.println( "" + name + + "" ); + pw.println( "" + this.toStateString( bundle.getState() ) + "" ); // no buttons for system bundle - if (bundle.getBundleId() == 0) { - pw.println(" "); - } else { - boolean enabled = bundle.getState() == Bundle.INSTALLED - || bundle.getState() == Bundle.RESOLVED; - this.actionForm(pw, enabled, bundle.getBundleId(), - StartAction.NAME, StartAction.LABEL); + if ( bundle.getBundleId() == 0 ) + { + pw.println( " " ); + } + else + { + boolean enabled = bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.RESOLVED; + this.actionForm( pw, enabled, bundle.getBundleId(), StartAction.NAME, StartAction.LABEL ); enabled = bundle.getState() == Bundle.ACTIVE; - this.actionForm(pw, enabled, bundle.getBundleId(), StopAction.NAME, - StopAction.LABEL); + this.actionForm( pw, enabled, bundle.getBundleId(), StopAction.NAME, StopAction.LABEL ); - enabled = bundle.getState() != Bundle.UNINSTALLED - && this.hasUpdates(bundle); - this.actionForm(pw, enabled, bundle.getBundleId(), - UpdateAction.NAME, UpdateAction.LABEL); + enabled = bundle.getState() != Bundle.UNINSTALLED && this.hasUpdates( bundle ); + this.actionForm( pw, enabled, bundle.getBundleId(), UpdateAction.NAME, UpdateAction.LABEL ); - enabled = bundle.getState() == Bundle.INSTALLED - || bundle.getState() == Bundle.RESOLVED + enabled = bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.ACTIVE; - this.actionForm(pw, enabled, bundle.getBundleId(), - UninstallAction.NAME, UninstallAction.LABEL); + this.actionForm( pw, enabled, bundle.getBundleId(), UninstallAction.NAME, UninstallAction.LABEL ); } - pw.println(""); + pw.println( "" ); } - private void actionForm(PrintWriter pw, boolean enabled, long bundleId, - String action, String actionLabel) { - pw.println("
"); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("
"); + + private void actionForm( PrintWriter pw, boolean enabled, long bundleId, String action, String actionLabel ) + { + pw.println( "
" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "
" ); } - private void installForm(PrintWriter pw) { + + private void installForm( PrintWriter pw ) + { int startLevel = getStartLevel().getInitialBundleStartLevel(); - pw.println("
"); - pw.println(""); - pw.println(" "); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(" - Start "); - pw.println(" - Start Level "); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(" "); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("
"); + pw.println( "
" ); + pw.println( "" ); + pw.println( " " ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( " - Start " ); + pw.println( " - Start Level " ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( " " ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "
" ); } - private String toStateString(int bundleState) { - switch (bundleState) { + + private String toStateString( int bundleState ) + { + switch ( bundleState ) + { case Bundle.INSTALLED: return "Installed"; case Bundle.RESOLVED: @@ -285,48 +300,59 @@ private String toStateString(int bundleState) { } } - private boolean hasUpdates(Bundle bundle) { + + private boolean hasUpdates( Bundle bundle ) + { // no updates if there is no installer service Object isObject = installerService.getService(); - if (isObject == null) { + if ( isObject == null ) + { return false; } // don't care for bundles with no symbolic name - if (bundle.getSymbolicName() == null) { + if ( bundle.getSymbolicName() == null ) + { return false; } -/* - Version bundleVersion = Version.parseVersion((String) bundle.getHeaders().get( - Constants.BUNDLE_VERSION)); - - BundleRepositoryAdmin repoAdmin = ((InstallerService) isObject).getBundleRepositoryAdmin(); - for (Iterator ri = repoAdmin.getResources(); ri.hasNext();) { - Resource res = ri.next(); - if (bundle.getSymbolicName().equals(res.getSymbolicName())) { - if (res.getVersion().compareTo(bundleVersion) > 0) { - return true; + /* + Version bundleVersion = Version.parseVersion((String) bundle.getHeaders().get( + Constants.BUNDLE_VERSION)); + + BundleRepositoryAdmin repoAdmin = ((InstallerService) isObject).getBundleRepositoryAdmin(); + for (Iterator ri = repoAdmin.getResources(); ri.hasNext();) { + Resource res = ri.next(); + if (bundle.getSymbolicName().equals(res.getSymbolicName())) { + if (res.getVersion().compareTo(bundleVersion) > 0) { + return true; + } + } } - } - } -*/ + */ return false; } - private void sort(Bundle[] bundles) { - Arrays.sort(bundles, BUNDLE_NAME_COMPARATOR); + + private void sort( Bundle[] bundles ) + { + Arrays.sort( bundles, BUNDLE_NAME_COMPARATOR ); } - private static String getName(Bundle bundle) { - String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME); - if (name == null || name.length() == 0) { + + private static String getName( Bundle bundle ) + { + String name = ( String ) bundle.getHeaders().get( Constants.BUNDLE_NAME ); + if ( name == null || name.length() == 0 ) + { name = bundle.getSymbolicName(); - if (name == null) { + if ( name == null ) + { name = bundle.getLocation(); - if (name == null) { - name = String.valueOf(bundle.getBundleId()); + if ( name == null ) + { + name = String.valueOf( bundle.getBundleId() ); } } } @@ -335,42 +361,52 @@ private static String getName(Bundle bundle) { // ---------- inner classes ------------------------------------------------ - private static final Comparator BUNDLE_NAME_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - return compare((Bundle) o1, (Bundle) o2); + private static final Comparator BUNDLE_NAME_COMPARATOR = new Comparator() + { + public int compare( Object o1, Object o2 ) + { + return compare( ( Bundle ) o1, ( Bundle ) o2 ); } - public int compare(Bundle b1, Bundle b2) { + + + public int compare( Bundle b1, Bundle b2 ) + { // the same bundles - if (b1 == b2 || b1.getBundleId() == b2.getBundleId()) { + if ( b1 == b2 || b1.getBundleId() == b2.getBundleId() ) + { return 0; } // special case for system bundle, which always is first - if (b1.getBundleId() == 0) { + if ( b1.getBundleId() == 0 ) + { return -1; - } else if (b2.getBundleId() == 0) { + } + else if ( b2.getBundleId() == 0 ) + { return 1; } // compare the symbolic names - int snComp = getName(b1).compareToIgnoreCase(getName(b2)); - if (snComp != 0) { + int snComp = getName( b1 ).compareToIgnoreCase( getName( b2 ) ); + if ( snComp != 0 ) + { return snComp; } // same names, compare versions - Version v1 = Version.parseVersion((String) b1.getHeaders().get( - Constants.BUNDLE_VERSION)); - Version v2 = Version.parseVersion((String) b2.getHeaders().get( - Constants.BUNDLE_VERSION)); - int vComp = v1.compareTo(v2); - if (vComp != 0) { + Version v1 = Version.parseVersion( ( String ) b1.getHeaders().get( Constants.BUNDLE_VERSION ) ); + Version v2 = Version.parseVersion( ( String ) b2.getHeaders().get( Constants.BUNDLE_VERSION ) ); + int vComp = v1.compareTo( v2 ); + if ( vComp != 0 ) + { return vComp; } // same version ? Not really, but then, we compare by bundle id - if (b1.getBundleId() < b2.getBundleId()) { + if ( b1.getBundleId() < b2.getBundleId() ) + { return -1; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/InstallAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/InstallAction.java index 15027736f0d..b839947a017 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/InstallAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/InstallAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -36,10 +37,12 @@ import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; + /** * The InstallAction TODO */ -public class InstallAction extends BundleAction { +public class InstallAction extends BundleAction +{ public static final String NAME = "install"; @@ -54,31 +57,37 @@ public class InstallAction extends BundleAction { // set to ask for PackageAdmin.refreshPackages() after install/update public static final String FIELD_REFRESH_PACKAGES = "refreshPackages"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) { + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { // get the uploaded data - Map params = (Map) request.getAttribute(Util.ATTR_FILEUPLOAD); - if (params == null) { + Map params = ( Map ) request.getAttribute( Util.ATTR_FILEUPLOAD ); + if ( params == null ) + { return true; } - FileItem startItem = getFileItem(params, FIELD_START, true); - FileItem startLevelItem = getFileItem(params, FIELD_STARTLEVEL, true); - FileItem bundleItem = getFileItem(params, FIELD_BUNDLEFILE, false); - FileItem refreshPackagesItem = getFileItem(params, - FIELD_REFRESH_PACKAGES, true); + FileItem startItem = getFileItem( params, FIELD_START, true ); + FileItem startLevelItem = getFileItem( params, FIELD_STARTLEVEL, true ); + FileItem bundleItem = getFileItem( params, FIELD_BUNDLEFILE, false ); + FileItem refreshPackagesItem = getFileItem( params, FIELD_REFRESH_PACKAGES, true ); // don't care any more if not bundle item - if (bundleItem == null || bundleItem.getSize() <= 0) { + if ( bundleItem == null || bundleItem.getSize() <= 0 ) + { return true; } @@ -88,52 +97,63 @@ public boolean performAction(HttpServletRequest request, String bundleLocation = "inputstream:"; // convert the start level value - if (startLevelItem != null) { - try { - startLevel = Integer.parseInt(startLevelItem.getString()); - } catch (NumberFormatException nfe) { - getLog().log( - LogService.LOG_INFO, - "Cannot parse start level parameter " + startLevelItem - + " to a number, not setting start level"); + if ( startLevelItem != null ) + { + try + { + startLevel = Integer.parseInt( startLevelItem.getString() ); + } + catch ( NumberFormatException nfe ) + { + getLog().log( LogService.LOG_INFO, + "Cannot parse start level parameter " + startLevelItem + " to a number, not setting start level" ); } } // write the bundle data to a temporary file to ease processing File tmpFile = null; - try { + try + { // copy the data to a file for better processing - tmpFile = File.createTempFile("install", ".tmp"); - bundleItem.write(tmpFile); - } catch (Exception e) { - getLog().log(LogService.LOG_ERROR, - "Problem accessing uploaded bundle file", e); + tmpFile = File.createTempFile( "install", ".tmp" ); + bundleItem.write( tmpFile ); + } + catch ( Exception e ) + { + getLog().log( LogService.LOG_ERROR, "Problem accessing uploaded bundle file", e ); // remove the tmporary file - if (tmpFile != null) { + if ( tmpFile != null ) + { tmpFile.delete(); tmpFile = null; } } // install or update the bundle now - if (tmpFile != null) { + if ( tmpFile != null ) + { // start, refreshPackages just needs to exist, don't care for value boolean start = startItem != null; boolean refreshPackages = refreshPackagesItem != null; bundleLocation = "inputstream:" + bundleItem.getName(); - installBundle(bundleLocation, tmpFile, startLevel, start, refreshPackages); + installBundle( bundleLocation, tmpFile, startLevel, start, refreshPackages ); } return true; } - private FileItem getFileItem(Map params, String name, boolean isFormField) { - FileItem[] items = (FileItem[]) params.get(name); - if (items != null) { - for (int i = 0; i < items.length; i++) { - if (items[i].isFormField() == isFormField) { + + private FileItem getFileItem( Map params, String name, boolean isFormField ) + { + FileItem[] items = ( FileItem[] ) params.get( name ); + if ( items != null ) + { + for ( int i = 0; i < items.length; i++ ) + { + if ( items[i].isFormField() == isFormField ) + { return items[i]; } } @@ -143,13 +163,16 @@ private FileItem getFileItem(Map params, String name, boolean isFormField) { return null; } - private void installBundle(String location, File bundleFile, - int startLevel, boolean start, boolean refreshPackages) { - if (bundleFile != null) { + + private void installBundle( String location, File bundleFile, int startLevel, boolean start, boolean refreshPackages ) + { + if ( bundleFile != null ) + { // try to get the bundle name, fail if none - String symbolicName = getSymbolicName(bundleFile); - if (symbolicName == null) { + String symbolicName = getSymbolicName( bundleFile ); + if ( symbolicName == null ) + { bundleFile.delete(); return; } @@ -157,47 +180,58 @@ private void installBundle(String location, File bundleFile, // check for existing bundle first Bundle updateBundle = null; Bundle[] bundles = getBundleContext().getBundles(); - for (int i = 0; i < bundles.length; i++) { - if ((bundles[i].getLocation() != null && bundles[i].getLocation().equals( - location)) - || (bundles[i].getSymbolicName() != null && bundles[i].getSymbolicName().equals( - symbolicName))) { + for ( int i = 0; i < bundles.length; i++ ) + { + if ( ( bundles[i].getLocation() != null && bundles[i].getLocation().equals( location ) ) + || ( bundles[i].getSymbolicName() != null && bundles[i].getSymbolicName().equals( symbolicName ) ) ) + { updateBundle = bundles[i]; break; } } - if (updateBundle != null) { + if ( updateBundle != null ) + { - updateBackground(updateBundle, bundleFile, refreshPackages); + updateBackground( updateBundle, bundleFile, refreshPackages ); - } else { + } + else + { - installBackground(bundleFile, location, startLevel, start, - refreshPackages); + installBackground( bundleFile, location, startLevel, start, refreshPackages ); } } } - private String getSymbolicName(File bundleFile) { + + private String getSymbolicName( File bundleFile ) + { JarFile jar = null; - try { - jar = new JarFile(bundleFile); + try + { + jar = new JarFile( bundleFile ); Manifest m = jar.getManifest(); - if (m != null) { - return m.getMainAttributes().getValue( - Constants.BUNDLE_SYMBOLICNAME); + if ( m != null ) + { + return m.getMainAttributes().getValue( Constants.BUNDLE_SYMBOLICNAME ); } - } catch (IOException ioe) { - getLog().log(LogService.LOG_WARNING, - "Cannot extract symbolic name of bundle file " + bundleFile, - ioe); - } finally { - if (jar != null) { - try { + } + catch ( IOException ioe ) + { + getLog().log( LogService.LOG_WARNING, "Cannot extract symbolic name of bundle file " + bundleFile, ioe ); + } + finally + { + if ( jar != null ) + { + try + { jar.close(); - } catch (IOException ioe) { + } + catch ( IOException ioe ) + { // ignore } } @@ -207,24 +241,26 @@ private String getSymbolicName(File bundleFile) { return null; } - private void installBackground(final File bundleFile, - final String location, final int startlevel, final boolean doStart, - final boolean refreshPackages) { - Thread t = new InstallHelper(this, "Background Install " + bundleFile, - bundleFile, refreshPackages) { + private void installBackground( final File bundleFile, final String location, final int startlevel, + final boolean doStart, final boolean refreshPackages ) + { + + Thread t = new InstallHelper( this, "Background Install " + bundleFile, bundleFile, refreshPackages ) + { - protected void doRun(InputStream bundleStream) - throws BundleException { - Bundle bundle = getBundleContext().installBundle(location, - bundleStream); + protected void doRun( InputStream bundleStream ) throws BundleException + { + Bundle bundle = getBundleContext().installBundle( location, bundleStream ); StartLevel sl = getStartLevel(); - if (sl != null) { - sl.setBundleStartLevel(bundle, startlevel); + if ( sl != null ) + { + sl.setBundleStartLevel( bundle, startlevel ); } - if (doStart) { + if ( doStart ) + { bundle.start(); } } @@ -233,22 +269,24 @@ protected void doRun(InputStream bundleStream) t.start(); } - private void updateBackground(final Bundle bundle, final File bundleFile, - final boolean refreshPackages) { - Thread t = new InstallHelper(this, "Background Update" - + bundle.getSymbolicName() + " (" + bundle.getBundleId() + ")", - bundleFile, refreshPackages) { - protected void doRun(InputStream bundleStream) - throws BundleException { - bundle.update(bundleStream); + private void updateBackground( final Bundle bundle, final File bundleFile, final boolean refreshPackages ) + { + Thread t = new InstallHelper( this, "Background Update" + bundle.getSymbolicName() + " (" + + bundle.getBundleId() + ")", bundleFile, refreshPackages ) + { + + protected void doRun( InputStream bundleStream ) throws BundleException + { + bundle.update( bundleStream ); } }; t.start(); } - private static abstract class InstallHelper extends Thread { + private static abstract class InstallHelper extends Thread + { private final InstallAction installAction; @@ -256,56 +294,78 @@ private static abstract class InstallHelper extends Thread { private final boolean refreshPackages; - InstallHelper(InstallAction installAction, String name, - File bundleFile, boolean refreshPackages) { - super(name); - setDaemon(true); + + InstallHelper( InstallAction installAction, String name, File bundleFile, boolean refreshPackages ) + { + super( name ); + setDaemon( true ); this.installAction = installAction; this.bundleFile = bundleFile; this.refreshPackages = refreshPackages; } - protected abstract void doRun(InputStream bundleStream) - throws BundleException; - public void run() { + protected abstract void doRun( InputStream bundleStream ) throws BundleException; + + + public void run() + { // wait some time for the request to settle - try { - sleep(500L); - } catch (InterruptedException ie) { + try + { + sleep( 500L ); + } + catch ( InterruptedException ie ) + { // don't care } // now deploy the resolved bundles InputStream bundleStream = null; - try { - bundleStream = new FileInputStream(bundleFile); - doRun(bundleStream); - - if (refreshPackages) { - try { + try + { + bundleStream = new FileInputStream( bundleFile ); + doRun( bundleStream ); + + if ( refreshPackages ) + { + try + { PackageAdmin pa = installAction.getPackageAdmin(); - if (pa != null) { - pa.refreshPackages(null); + if ( pa != null ) + { + pa.refreshPackages( null ); } - } catch (IllegalStateException ise) { + } + catch ( IllegalStateException ise ) + { // This exception is expected if the webconsole bundle // itself has just been updated. For now, we just // ignore this exception } } - } catch (IOException ioe) { - installAction.getLog().log(LogService.LOG_ERROR, - "Cannot install or update bundle from " + bundleFile, ioe); - } catch (BundleException be) { - installAction.getLog().log(LogService.LOG_ERROR, - "Cannot install or update bundle from " + bundleFile, be); - } finally { - if (bundleStream != null) { - try { + } + catch ( IOException ioe ) + { + installAction.getLog().log( LogService.LOG_ERROR, "Cannot install or update bundle from " + bundleFile, + ioe ); + } + catch ( BundleException be ) + { + installAction.getLog().log( LogService.LOG_ERROR, "Cannot install or update bundle from " + bundleFile, + be ); + } + finally + { + if ( bundleStream != null ) + { + try + { bundleStream.close(); - } catch (IOException ignore) { + } + catch ( IOException ignore ) + { } } bundleFile.delete(); diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/RefreshPackagesAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/RefreshPackagesAction.java index d4675c0bb99..b149d8cf058 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/RefreshPackagesAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/RefreshPackagesAction.java @@ -16,30 +16,38 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + /** * The RefreshPackagesAction TODO */ -public class RefreshPackagesAction extends BundleAction { +public class RefreshPackagesAction extends BundleAction +{ public static final String NAME = "refreshPackages"; public static final String LABEL = "Refresh Packages"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) { - getPackageAdmin().refreshPackages(null); + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { + + getPackageAdmin().refreshPackages( null ); return true; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/SetStartLevelAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/SetStartLevelAction.java index eea01a25837..5fb9681cef4 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/SetStartLevelAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/SetStartLevelAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -23,46 +24,61 @@ import org.apache.felix.webconsole.internal.BaseManagementPlugin; import org.osgi.service.startlevel.StartLevel; + /** * The SetStartLevelAction TODO */ -public class SetStartLevelAction extends BaseManagementPlugin implements Action { +public class SetStartLevelAction extends BaseManagementPlugin implements Action +{ public static final String NAME = "setStartLevel"; public static final String LABEL = "Set Start Level"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) { + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { StartLevel sl = getStartLevel(); - if (sl != null) { - int bundleSL = this.getParameterInt(request, "bundleStartLevel"); - if (bundleSL > 0 && bundleSL != sl.getInitialBundleStartLevel()) { - sl.setInitialBundleStartLevel(bundleSL); + if ( sl != null ) + { + int bundleSL = this.getParameterInt( request, "bundleStartLevel" ); + if ( bundleSL > 0 && bundleSL != sl.getInitialBundleStartLevel() ) + { + sl.setInitialBundleStartLevel( bundleSL ); } - int systemSL = this.getParameterInt(request, "systemStartLevel"); - if (systemSL > 0 && systemSL != sl.getStartLevel()) { - sl.setStartLevel(systemSL); + int systemSL = this.getParameterInt( request, "systemStartLevel" ); + if ( systemSL > 0 && systemSL != sl.getStartLevel() ) + { + sl.setStartLevel( systemSL ); } } return true; } - private int getParameterInt(HttpServletRequest request, String name) { - try { - return Integer.parseInt(request.getParameter(name)); - } catch (NumberFormatException nfe) { + + private int getParameterInt( HttpServletRequest request, String name ) + { + try + { + return Integer.parseInt( request.getParameter( name ) ); + } + catch ( NumberFormatException nfe ) + { // don't care } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StartAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StartAction.java index 33345463766..321321b9993 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StartAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StartAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -23,29 +24,42 @@ import org.osgi.framework.BundleException; import org.osgi.service.log.LogService; -public class StartAction extends BundleAction { + +public class StartAction extends BundleAction +{ public static final String NAME = "start"; public static final String LABEL = "Start"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, HttpServletResponse response) { - long bundleId = this.getBundleId(request); - if (bundleId > 0) { // cannot start system bundle !! - Bundle bundle = this.getBundleContext().getBundle(bundleId); - if (bundle != null) { - try { + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { + + long bundleId = this.getBundleId( request ); + if ( bundleId > 0 ) + { // cannot start system bundle !! + Bundle bundle = this.getBundleContext().getBundle( bundleId ); + if ( bundle != null ) + { + try + { bundle.start(); - } catch (BundleException be) { - getLog().log(LogService.LOG_ERROR, "Cannot start", be); + } + catch ( BundleException be ) + { + getLog().log( LogService.LOG_ERROR, "Cannot start", be ); } } @@ -53,4 +67,3 @@ public boolean performAction(HttpServletRequest request, HttpServletResponse res return true; } } - diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StopAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StopAction.java index 5b2a71f73a3..f876d1620c9 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StopAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/StopAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -23,32 +24,45 @@ import org.osgi.framework.BundleException; import org.osgi.service.log.LogService; + /** * The StopAction TODO */ -public class StopAction extends BundleAction { +public class StopAction extends BundleAction +{ public static final String NAME = "stop"; public static final String LABEL = "Stop"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, HttpServletResponse response) { - long bundleId = this.getBundleId(request); - if (bundleId > 0) { // cannot stop system bundle !! - Bundle bundle = this.getBundleContext().getBundle(bundleId); - if (bundle != null) { - try { + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { + + long bundleId = this.getBundleId( request ); + if ( bundleId > 0 ) + { // cannot stop system bundle !! + Bundle bundle = this.getBundleContext().getBundle( bundleId ); + if ( bundle != null ) + { + try + { bundle.stop(); - } catch (BundleException be) { - getLog().log(LogService.LOG_ERROR, "Cannot stop", be); + } + catch ( BundleException be ) + { + getLog().log( LogService.LOG_ERROR, "Cannot stop", be ); } } @@ -57,4 +71,3 @@ public boolean performAction(HttpServletRequest request, HttpServletResponse res return true; } } - diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UninstallAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UninstallAction.java index cf32ef9c5d2..32b451eb992 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UninstallAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UninstallAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -23,29 +24,42 @@ import org.osgi.framework.BundleException; import org.osgi.service.log.LogService; -public class UninstallAction extends BundleAction { + +public class UninstallAction extends BundleAction +{ public static final String NAME = "uninstall"; public static final String LABEL = "Uninstall"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, HttpServletResponse response) { - long bundleId = this.getBundleId(request); - if (bundleId > 0) { // cannot stop system bundle !! - Bundle bundle = this.getBundleContext().getBundle(bundleId); - if (bundle != null) { - try { + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { + + long bundleId = this.getBundleId( request ); + if ( bundleId > 0 ) + { // cannot stop system bundle !! + Bundle bundle = this.getBundleContext().getBundle( bundleId ); + if ( bundle != null ) + { + try + { bundle.uninstall(); - } catch (BundleException be) { - getLog().log(LogService.LOG_ERROR, "Cannot uninstall", be); + } + catch ( BundleException be ) + { + getLog().log( LogService.LOG_ERROR, "Cannot uninstall", be ); } } @@ -54,4 +68,3 @@ public boolean performAction(HttpServletRequest request, HttpServletResponse res return true; } } - diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UpdateAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UpdateAction.java index 8499afe30af..58e12847e39 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UpdateAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/UpdateAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.core; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -24,10 +25,12 @@ import org.osgi.service.log.LogService; import org.osgi.util.tracker.ServiceTracker; + /** * The UpdateAction TODO */ -public class UpdateAction extends BundleAction { +public class UpdateAction extends BundleAction +{ public static final String NAME = "update"; @@ -38,33 +41,44 @@ public class UpdateAction extends BundleAction { // track the optional installer service manually private ServiceTracker installerService; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); - installerService = new ServiceTracker(bundleContext, - INSTALLER_SERVICE_NAME, null); + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); + + installerService = new ServiceTracker( bundleContext, INSTALLER_SERVICE_NAME, null ); installerService.open(); } - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) { - - long bundleId = this.getBundleId(request); - if (bundleId > 0) { // cannot stop system bundle !! - Bundle bundle = this.getBundleContext().getBundle(bundleId); - if (bundle != null) { - try { - this.updateFromRepo(bundle); - } catch (Throwable t) { - getLog().log(LogService.LOG_ERROR, "Uncaught Problem", t); + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { + + long bundleId = this.getBundleId( request ); + if ( bundleId > 0 ) + { // cannot stop system bundle !! + Bundle bundle = this.getBundleContext().getBundle( bundleId ); + if ( bundle != null ) + { + try + { + this.updateFromRepo( bundle ); + } + catch ( Throwable t ) + { + getLog().log( LogService.LOG_ERROR, "Uncaught Problem", t ); } } @@ -73,51 +87,53 @@ public boolean performAction(HttpServletRequest request, return true; } - private void updateFromRepo(final Bundle bundle) { -/* - final InstallerService is = (InstallerService) installerService.getService(); - if (is == null) { - return; - } - - final String name = bundle.getSymbolicName(); - final String version = (String) bundle.getHeaders().get( - Constants.BUNDLE_VERSION); - - // the name is required, otherwise we can do nothing - if (name == null) { - return; - } - - // TODO: Should be restrict to same major.micro ?? - Thread t = new Thread("Background Update") { - public void run() { - // wait some time for the request to settle - try { - sleep(500L); - } catch (InterruptedException ie) { - // don't care + private void updateFromRepo( final Bundle bundle ) + { + /* + final InstallerService is = (InstallerService) installerService.getService(); + if (is == null) { + return; } - Installer installer = is.getInstaller(); - installer.addBundle(name, new VersionRange(version), -1); - try { - installer.install(false); - } catch (InstallerException ie) { - Throwable cause = (ie.getCause() != null) - ? ie.getCause() - : ie; - getLog().log(LogService.LOG_ERROR, "Cannot update", cause); - } finally { - installer.dispose(); + final String name = bundle.getSymbolicName(); + final String version = (String) bundle.getHeaders().get( + Constants.BUNDLE_VERSION); + + // the name is required, otherwise we can do nothing + if (name == null) { + return; } - } - }; - t.setDaemon(true); // make a daemon thread (detach from current thread) - t.start(); - */ + // TODO: Should be restrict to same major.micro ?? + + Thread t = new Thread("Background Update") { + public void run() { + // wait some time for the request to settle + try { + sleep(500L); + } catch (InterruptedException ie) { + // don't care + } + + Installer installer = is.getInstaller(); + installer.addBundle(name, new VersionRange(version), -1); + try { + installer.install(false); + } catch (InstallerException ie) { + Throwable cause = (ie.getCause() != null) + ? ie.getCause() + : ie; + getLog().log(LogService.LOG_ERROR, "Cannot update", cause); + } finally { + installer.dispose(); + } + } + }; + + t.setDaemon(true); // make a daemon thread (detach from current thread) + t.start(); + */ } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/AssemblyListRender.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/AssemblyListRender.java index 123e3257542..181c1bb8a3a 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/AssemblyListRender.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/AssemblyListRender.java @@ -16,33 +16,44 @@ */ package org.apache.felix.webconsole.internal.misc; + import java.util.ArrayList; import java.util.List; import org.apache.felix.webconsole.internal.core.BundleListRender; import org.osgi.framework.Bundle; -public class AssemblyListRender extends BundleListRender { + +public class AssemblyListRender extends BundleListRender +{ public static final String NAME = "assemblyList"; public static final String LABEL = "Assemblies"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - protected Bundle[] getBundles() { + + protected Bundle[] getBundles() + { Bundle[] bundles = this.getBundleContext().getBundles(); List assList = new ArrayList(); - for (int i=0; i < bundles.length; i++) { - if (bundles[i].getHeaders().get("Assembly-Bundles") != null) { - assList.add(bundles[i]); + for ( int i = 0; i < bundles.length; i++ ) + { + if ( bundles[i].getHeaders().get( "Assembly-Bundles" ) != null ) + { + assList.add( bundles[i] ); } } - return (Bundle[]) assList.toArray(new Bundle[assList.size()]); + return ( Bundle[] ) assList.toArray( new Bundle[assList.size()] ); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/ConfigurationRender.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/ConfigurationRender.java index fe1b0be50ef..67b899bf2de 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/ConfigurationRender.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/misc/ConfigurationRender.java @@ -16,10 +16,8 @@ */ package org.apache.felix.webconsole.internal.misc; -import java.io.File; -import java.io.FileInputStream; + import java.io.IOException; -import java.io.InputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -40,7 +38,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.io.IOUtils; import org.apache.felix.webconsole.ConfigurationPrinter; import org.apache.felix.webconsole.Render; import org.apache.felix.webconsole.internal.BaseManagementPlugin; @@ -55,7 +52,9 @@ import org.osgi.service.prefs.PreferencesService; import org.osgi.util.tracker.ServiceTracker; -public class ConfigurationRender extends BaseManagementPlugin implements Render { + +public class ConfigurationRender extends BaseManagementPlugin implements Render +{ public static final String NAME = "config"; @@ -67,66 +66,77 @@ public class ConfigurationRender extends BaseManagementPlugin implements Render private SortedMap configurationPrinters = new TreeMap(); - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { + + public void render( HttpServletRequest request, HttpServletResponse response ) throws IOException + { PrintWriter pw = response.getWriter(); - pw.println(""); + pw.println( "
" ); - pw.println(""); - pw.println(""); - pw.println(""); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); - pw.println(""); - pw.println("" ); + pw.println( ""); - pw.println(""); - pw.println("
Configuration Details
Configuration Details
"); - pw.println("
");
+        pw.println( "
" ); + pw.println( "
" );
 
-        pw.println("*** Date: "
-            + SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG,
-                SimpleDateFormat.LONG, Locale.US).format(new Date()));
+        pw.println( "*** Date: "
+            + SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.LONG, SimpleDateFormat.LONG, Locale.US ).format(
+                new Date() ) );
         pw.println();
 
-        this.printSystemProperties(pw);
-        this.printBundles(pw);
-        this.printServices(pw);
-        this.printPreferences(pw);
-        this.printConfigurations(pw);
+        this.printSystemProperties( pw );
+        this.printBundles( pw );
+        this.printServices( pw );
+        this.printPreferences( pw );
+        this.printConfigurations( pw );
 
-        for (Iterator cpi = getConfigurationPrinters().iterator(); cpi.hasNext();) {
-            printConfigurationPrinter(pw, (ConfigurationPrinter) cpi.next());
+        for ( Iterator cpi = getConfigurationPrinters().iterator(); cpi.hasNext(); )
+        {
+            printConfigurationPrinter( pw, ( ConfigurationPrinter ) cpi.next() );
         }
 
-        pw.println("
"); - pw.println("
"); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } - private Collection getConfigurationPrinters() { - if (cfgPrinterTracker == null) { - cfgPrinterTracker = new ServiceTracker(getBundleContext(), - ConfigurationPrinter.SERVICE, null); + + private Collection getConfigurationPrinters() + { + if ( cfgPrinterTracker == null ) + { + cfgPrinterTracker = new ServiceTracker( getBundleContext(), ConfigurationPrinter.SERVICE, null ); cfgPrinterTracker.open(); cfgPrinterTrackerCount = -1; } - if (cfgPrinterTrackerCount != cfgPrinterTracker.getTrackingCount()) { + if ( cfgPrinterTrackerCount != cfgPrinterTracker.getTrackingCount() ) + { SortedMap cp = new TreeMap(); Object[] services = cfgPrinterTracker.getServices(); - if (services != null) { - for (int i = 0; i < services.length; i++) { + if ( services != null ) + { + for ( int i = 0; i < services.length; i++ ) + { Object srv = services[i]; - ConfigurationPrinter cfgPrinter = (ConfigurationPrinter) srv; - cp.put(cfgPrinter.getTitle(), cfgPrinter); + ConfigurationPrinter cfgPrinter = ( ConfigurationPrinter ) srv; + cp.put( cfgPrinter.getTitle(), cfgPrinter ); } } configurationPrinters = cp; @@ -136,108 +146,122 @@ private Collection getConfigurationPrinters() { return configurationPrinters.values(); } - private void printSystemProperties(PrintWriter pw) { - pw.println("*** System properties:"); + + private void printSystemProperties( PrintWriter pw ) + { + pw.println( "*** System properties:" ); Properties props = System.getProperties(); - SortedSet keys = new TreeSet(props.keySet()); - for (Iterator ki = keys.iterator(); ki.hasNext();) { + SortedSet keys = new TreeSet( props.keySet() ); + for ( Iterator ki = keys.iterator(); ki.hasNext(); ) + { Object key = ki.next(); - this.infoLine(pw, null, (String) key, props.get(key)); + this.infoLine( pw, null, ( String ) key, props.get( key ) ); } pw.println(); } + // This is Sling stuff, we comment it out for now -// private void printRawFrameworkProperties(PrintWriter pw) { -// pw.println("*** Raw Framework properties:"); -// -// File file = new File(getBundleContext().getProperty("sling.home"), -// "sling.properties"); -// if (file.exists()) { -// Properties props = new Properties(); -// InputStream ins = null; -// try { -// ins = new FileInputStream(file); -// props.load(ins); -// } catch (IOException ioe) { -// // handle or ignore -// } finally { -// IOUtils.closeQuietly(ins); -// } -// -// SortedSet keys = new TreeSet(props.keySet()); -// for (Iterator ki = keys.iterator(); ki.hasNext();) { -// Object key = ki.next(); -// this.infoLine(pw, null, (String) key, props.get(key)); -// } -// -// } else { -// pw.println(" No Framework properties in " + file); -// } -// -// pw.println(); -// } - - private void printBundles(PrintWriter pw) { - pw.println("*** Bundles:"); + // private void printRawFrameworkProperties(PrintWriter pw) { + // pw.println("*** Raw Framework properties:"); + // + // File file = new File(getBundleContext().getProperty("sling.home"), + // "sling.properties"); + // if (file.exists()) { + // Properties props = new Properties(); + // InputStream ins = null; + // try { + // ins = new FileInputStream(file); + // props.load(ins); + // } catch (IOException ioe) { + // // handle or ignore + // } finally { + // IOUtils.closeQuietly(ins); + // } + // + // SortedSet keys = new TreeSet(props.keySet()); + // for (Iterator ki = keys.iterator(); ki.hasNext();) { + // Object key = ki.next(); + // this.infoLine(pw, null, (String) key, props.get(key)); + // } + // + // } else { + // pw.println(" No Framework properties in " + file); + // } + // + // pw.println(); + // } + + private void printBundles( PrintWriter pw ) + { + pw.println( "*** Bundles:" ); // biz.junginger.freemem.FreeMem (1.3.0) "FreeMem Eclipse Memory // Monitor" [Resolved] Bundle[] bundles = getBundleContext().getBundles(); SortedSet keys = new TreeSet(); - for (int i = 0; i < bundles.length; i++) { - keys.add(this.getBundleString(bundles[i], true)); + for ( int i = 0; i < bundles.length; i++ ) + { + keys.add( this.getBundleString( bundles[i], true ) ); } - for (Iterator ki = keys.iterator(); ki.hasNext();) { - this.infoLine(pw, null, null, ki.next()); + for ( Iterator ki = keys.iterator(); ki.hasNext(); ) + { + this.infoLine( pw, null, null, ki.next() ); } pw.println(); } - private void printServices(PrintWriter pw) { - pw.println("*** Services:"); + + private void printServices( PrintWriter pw ) + { + pw.println( "*** Services:" ); // get the list of services sorted by service ID (ascending) SortedMap srMap = new TreeMap(); - try { - ServiceReference[] srs = getBundleContext().getAllServiceReferences( - null, null); - for (int i = 0; i < srs.length; i++) { - srMap.put(srs[i].getProperty(Constants.SERVICE_ID), srs[i]); + try + { + ServiceReference[] srs = getBundleContext().getAllServiceReferences( null, null ); + for ( int i = 0; i < srs.length; i++ ) + { + srMap.put( srs[i].getProperty( Constants.SERVICE_ID ), srs[i] ); } - } catch (InvalidSyntaxException ise) { + } + catch ( InvalidSyntaxException ise ) + { // should handle, for now just print nothing, actually this is not // expected } - for (Iterator si = srMap.values().iterator(); si.hasNext();) { - ServiceReference sr = (ServiceReference) si.next(); + for ( Iterator si = srMap.values().iterator(); si.hasNext(); ) + { + ServiceReference sr = ( ServiceReference ) si.next(); - this.infoLine(pw, null, - String.valueOf(sr.getProperty(Constants.SERVICE_ID)), - sr.getProperty(Constants.OBJECTCLASS)); - this.infoLine(pw, " ", "Bundle", this.getBundleString( - sr.getBundle(), false)); + this.infoLine( pw, null, String.valueOf( sr.getProperty( Constants.SERVICE_ID ) ), sr + .getProperty( Constants.OBJECTCLASS ) ); + this.infoLine( pw, " ", "Bundle", this.getBundleString( sr.getBundle(), false ) ); Bundle[] users = sr.getUsingBundles(); - if (users != null && users.length > 0) { + if ( users != null && users.length > 0 ) + { List userString = new ArrayList(); - for (int i = 0; i < users.length; i++) { - userString.add(this.getBundleString(users[i], false)); + for ( int i = 0; i < users.length; i++ ) + { + userString.add( this.getBundleString( users[i], false ) ); } - this.infoLine(pw, " ", "Using Bundles", userString); + this.infoLine( pw, " ", "Using Bundles", userString ); } String[] keys = sr.getPropertyKeys(); - Arrays.sort(keys); - for (int i = 0; i < keys.length; i++) { - if (!Constants.SERVICE_ID.equals(keys[i]) - && !Constants.OBJECTCLASS.equals(keys[i])) { - this.infoLine(pw, " ", keys[i], sr.getProperty(keys[i])); + Arrays.sort( keys ); + for ( int i = 0; i < keys.length; i++ ) + { + if ( !Constants.SERVICE_ID.equals( keys[i] ) && !Constants.OBJECTCLASS.equals( keys[i] ) ) + { + this.infoLine( pw, " ", keys[i], sr.getProperty( keys[i] ) ); } } @@ -245,205 +269,256 @@ private void printServices(PrintWriter pw) { } } - private void printPreferences(PrintWriter pw) { - pw.println("*** System Preferences:"); - ServiceReference sr = getBundleContext().getServiceReference( - PreferencesService.class.getName()); - if (sr == null) { - pw.println(" Preferences Service not registered"); + private void printPreferences( PrintWriter pw ) + { + pw.println( "*** System Preferences:" ); + + ServiceReference sr = getBundleContext().getServiceReference( PreferencesService.class.getName() ); + if ( sr == null ) + { + pw.println( " Preferences Service not registered" ); pw.println(); return; } - PreferencesService ps = (PreferencesService) getBundleContext().getService( - sr); - try { - this.printPreferences(pw, ps.getSystemPreferences()); + PreferencesService ps = ( PreferencesService ) getBundleContext().getService( sr ); + try + { + this.printPreferences( pw, ps.getSystemPreferences() ); String[] users = ps.getUsers(); - for (int i = 0; users != null && i < users.length; i++) { - pw.println("*** User Preferences " + users[i] + ":"); - this.printPreferences(pw, ps.getUserPreferences(users[i])); + for ( int i = 0; users != null && i < users.length; i++ ) + { + pw.println( "*** User Preferences " + users[i] + ":" ); + this.printPreferences( pw, ps.getUserPreferences( users[i] ) ); } - } catch (BackingStoreException bse) { + } + catch ( BackingStoreException bse ) + { // todo or not :-) - } finally { - getBundleContext().ungetService(sr); + } + finally + { + getBundleContext().ungetService( sr ); } } - private void printPreferences(PrintWriter pw, Preferences prefs) - throws BackingStoreException { + + private void printPreferences( PrintWriter pw, Preferences prefs ) throws BackingStoreException + { String[] children = prefs.childrenNames(); - for (int i = 0; i < children.length; i++) { - this.printPreferences(pw, prefs.node(children[i])); + for ( int i = 0; i < children.length; i++ ) + { + this.printPreferences( pw, prefs.node( children[i] ) ); } String[] keys = prefs.keys(); - for (int i = 0; i < keys.length; i++) { - this.infoLine(pw, null, prefs.absolutePath() + "/" + keys[i], - prefs.get(keys[i], null)); + for ( int i = 0; i < keys.length; i++ ) + { + this.infoLine( pw, null, prefs.absolutePath() + "/" + keys[i], prefs.get( keys[i], null ) ); } pw.println(); } - private void printConfigurations(PrintWriter pw) { - pw.println("*** Configurations:"); - ServiceReference sr = getBundleContext().getServiceReference( - ConfigurationAdmin.class.getName()); - if (sr == null) { - pw.println(" Configuration Admin Service not registered"); - } else { + private void printConfigurations( PrintWriter pw ) + { + pw.println( "*** Configurations:" ); - ConfigurationAdmin ca = (ConfigurationAdmin) getBundleContext().getService( - sr); - try { - Configuration[] configs = ca.listConfigurations(null); - if (configs != null && configs.length > 0) { + ServiceReference sr = getBundleContext().getServiceReference( ConfigurationAdmin.class.getName() ); + if ( sr == null ) + { + pw.println( " Configuration Admin Service not registered" ); + } + else + { + + ConfigurationAdmin ca = ( ConfigurationAdmin ) getBundleContext().getService( sr ); + try + { + Configuration[] configs = ca.listConfigurations( null ); + if ( configs != null && configs.length > 0 ) + { SortedMap sm = new TreeMap(); - for (int i = 0; i < configs.length; i++) { - sm.put(configs[i].getPid(), configs[i]); + for ( int i = 0; i < configs.length; i++ ) + { + sm.put( configs[i].getPid(), configs[i] ); } - for (Iterator mi = sm.values().iterator(); mi.hasNext();) { - this.printConfiguration(pw, (Configuration) mi.next()); + for ( Iterator mi = sm.values().iterator(); mi.hasNext(); ) + { + this.printConfiguration( pw, ( Configuration ) mi.next() ); } - } else { - pw.println(" No Configurations available"); } - } catch (Exception e) { + else + { + pw.println( " No Configurations available" ); + } + } + catch ( Exception e ) + { // todo or not :-) - } finally { - getBundleContext().ungetService(sr); + } + finally + { + getBundleContext().ungetService( sr ); } } pw.println(); } - private void printConfigurationPrinter(PrintWriter pw, - ConfigurationPrinter cp) { - pw.println("*** " + cp.getTitle() + ":"); - cp.printConfiguration(pw); + + private void printConfigurationPrinter( PrintWriter pw, ConfigurationPrinter cp ) + { + pw.println( "*** " + cp.getTitle() + ":" ); + cp.printConfiguration( pw ); pw.println(); } - private void printConfiguration(PrintWriter pw, Configuration config) { - this.infoLine(pw, "", "PID", config.getPid()); - if (config.getFactoryPid() != null) { - this.infoLine(pw, " ", "Factory PID", config.getFactoryPid()); + private void printConfiguration( PrintWriter pw, Configuration config ) + { + this.infoLine( pw, "", "PID", config.getPid() ); + + if ( config.getFactoryPid() != null ) + { + this.infoLine( pw, " ", "Factory PID", config.getFactoryPid() ); } - String loc = (config.getBundleLocation() != null) - ? config.getBundleLocation() - : "Unbound"; - this.infoLine(pw, " ", "BundleLocation", loc); + String loc = ( config.getBundleLocation() != null ) ? config.getBundleLocation() : "Unbound"; + this.infoLine( pw, " ", "BundleLocation", loc ); Dictionary props = config.getProperties(); - if (props != null) { + if ( props != null ) + { SortedSet keys = new TreeSet(); - for (Enumeration ke = props.keys(); ke.hasMoreElements();) { - keys.add(ke.nextElement()); + for ( Enumeration ke = props.keys(); ke.hasMoreElements(); ) + { + keys.add( ke.nextElement() ); } - for (Iterator ki = keys.iterator(); ki.hasNext();) { - String key = (String) ki.next(); - this.infoLine(pw, " ", key, props.get(key)); + for ( Iterator ki = keys.iterator(); ki.hasNext(); ) + { + String key = ( String ) ki.next(); + this.infoLine( pw, " ", key, props.get( key ) ); } } pw.println(); } - private void infoLine(PrintWriter pw, String indent, String label, - Object value) { - if (indent != null) { - pw.print(indent); + + private void infoLine( PrintWriter pw, String indent, String label, Object value ) + { + if ( indent != null ) + { + pw.print( indent ); } - if (label != null) { - pw.print(label); - pw.print('='); + if ( label != null ) + { + pw.print( label ); + pw.print( '=' ); } - this.printObject(pw, value); + this.printObject( pw, value ); pw.println(); } - private void printObject(PrintWriter pw, Object value) { - if (value == null) { - pw.print("null"); - } else if (value.getClass().isArray()) { - this.printArray(pw, (Object[]) value); - } else { - pw.print(value); + + private void printObject( PrintWriter pw, Object value ) + { + if ( value == null ) + { + pw.print( "null" ); + } + else if ( value.getClass().isArray() ) + { + this.printArray( pw, ( Object[] ) value ); + } + else + { + pw.print( value ); } } - private void printArray(PrintWriter pw, Object[] values) { - pw.print('['); - if (values != null && values.length > 0) { - for (int i = 0; i < values.length; i++) { - if (i > 0) { - pw.print(", "); + + private void printArray( PrintWriter pw, Object[] values ) + { + pw.print( '[' ); + if ( values != null && values.length > 0 ) + { + for ( int i = 0; i < values.length; i++ ) + { + if ( i > 0 ) + { + pw.print( ", " ); } - this.printObject(pw, values[i]); + this.printObject( pw, values[i] ); } } - pw.print(']'); + pw.print( ']' ); } - private String getBundleString(Bundle bundle, boolean withState) { + + private String getBundleString( Bundle bundle, boolean withState ) + { StringBuffer buf = new StringBuffer(); - if (bundle.getSymbolicName() != null) { - buf.append(bundle.getSymbolicName()); - } else if (bundle.getLocation() != null) { - buf.append(bundle.getLocation()); - } else { - buf.append(bundle.getBundleId()); + if ( bundle.getSymbolicName() != null ) + { + buf.append( bundle.getSymbolicName() ); + } + else if ( bundle.getLocation() != null ) + { + buf.append( bundle.getLocation() ); + } + else + { + buf.append( bundle.getBundleId() ); } Dictionary headers = bundle.getHeaders(); - if (headers.get(Constants.BUNDLE_VERSION) != null) { - buf.append(" (").append(headers.get(Constants.BUNDLE_VERSION)).append( - ')'); + if ( headers.get( Constants.BUNDLE_VERSION ) != null ) + { + buf.append( " (" ).append( headers.get( Constants.BUNDLE_VERSION ) ).append( ')' ); } - if (headers.get(Constants.BUNDLE_NAME) != null) { - buf.append(" \"").append(headers.get(Constants.BUNDLE_NAME)).append( - '"'); + if ( headers.get( Constants.BUNDLE_NAME ) != null ) + { + buf.append( " \"" ).append( headers.get( Constants.BUNDLE_NAME ) ).append( '"' ); } - if (withState) { - buf.append(" ["); - switch (bundle.getState()) { + if ( withState ) + { + buf.append( " [" ); + switch ( bundle.getState() ) + { case Bundle.INSTALLED: - buf.append("Installed"); + buf.append( "Installed" ); break; case Bundle.RESOLVED: - buf.append("Resolved"); + buf.append( "Resolved" ); break; case Bundle.STARTING: - buf.append("Starting"); + buf.append( "Starting" ); break; case Bundle.ACTIVE: - buf.append("Active"); + buf.append( "Active" ); break; case Bundle.STOPPING: - buf.append("Stopping"); + buf.append( "Stopping" ); break; case Bundle.UNINSTALLED: - buf.append("Uninstalled"); + buf.append( "Uninstalled" ); break; } - buf.append(']'); + buf.append( ']' ); } return buf.toString(); diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/AbstractObrPlugin.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/AbstractObrPlugin.java index 479ccbf2097..0252f025306 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/AbstractObrPlugin.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/AbstractObrPlugin.java @@ -18,38 +18,43 @@ */ package org.apache.felix.webconsole.internal.obr; + import org.apache.felix.webconsole.internal.BaseManagementPlugin; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; -public class AbstractObrPlugin extends BaseManagementPlugin { + +public class AbstractObrPlugin extends BaseManagementPlugin +{ // track the optional installer service manually private ServiceTracker installerService; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); + + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); } -/* - protected InstallerService getInstallerService() { - if (installerService == null) { - try { - installerService = new ServiceTracker(getBundleContext(), - InstallerService.class.getName(), null); - installerService.open(); - } catch (Throwable t) { - // missing InstallerService class ?? - return null; + /* + protected InstallerService getInstallerService() { + if (installerService == null) { + try { + installerService = new ServiceTracker(getBundleContext(), + InstallerService.class.getName(), null); + installerService.open(); + } catch (Throwable t) { + // missing InstallerService class ?? + return null; + } + } + return (InstallerService) installerService.getService(); } - return (InstallerService) installerService.getService(); - } - - protected BundleRepositoryAdmin getBundleRepositoryAdmin() { - InstallerService is = getInstallerService(); - return (is != null) ? is.getBundleRepositoryAdmin() : null; - }*/ + protected BundleRepositoryAdmin getBundleRepositoryAdmin() { + InstallerService is = getInstallerService(); + return (is != null) ? is.getBundleRepositoryAdmin() : null; + }*/ } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/BundleRepositoryRender.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/BundleRepositoryRender.java index 2a4a70f00cf..cdd97abb60a 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/BundleRepositoryRender.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/BundleRepositoryRender.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.obr; + import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; @@ -30,7 +31,9 @@ import org.osgi.framework.Constants; import org.osgi.framework.Version; -public abstract class BundleRepositoryRender extends AbstractObrPlugin implements Render { + +public abstract class BundleRepositoryRender extends AbstractObrPlugin implements Render +{ public static final String NAME = "bundlerepo"; @@ -44,231 +47,257 @@ public abstract class BundleRepositoryRender extends AbstractObrPlugin implement private String[] repoURLs; - public void setBundleContext(BundleContext bundleContext) { - super.setBundleContext(bundleContext); - String urlStr = bundleContext.getProperty(REPOSITORY_PROPERTY); + public void setBundleContext( BundleContext bundleContext ) + { + super.setBundleContext( bundleContext ); + + String urlStr = bundleContext.getProperty( REPOSITORY_PROPERTY ); List urlList = new ArrayList(); - if (urlStr != null) { - StringTokenizer st = new StringTokenizer(urlStr); - while (st.hasMoreTokens()) { - urlList.add(st.nextToken()); + if ( urlStr != null ) + { + StringTokenizer st = new StringTokenizer( urlStr ); + while ( st.hasMoreTokens() ) + { + urlList.add( st.nextToken() ); } } - this.repoURLs = (String[]) urlList.toArray(new String[urlList.size()]); + this.repoURLs = ( String[] ) urlList.toArray( new String[urlList.size()] ); } - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } -/* - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { - - PrintWriter pw = response.getWriter(); - this.header(pw); - - Iterator repos; - BundleRepositoryAdmin repoAdmin = getBundleRepositoryAdmin(); - if (repoAdmin != null) { - repos = repoAdmin.getRepositories(); - } else { - repos = Collections.emptyList().iterator(); - } - Set activeURLs = new HashSet(); - if (!repos.hasNext()) { - pw.println(""); - pw.println("No Active Repositories"); - pw.println(""); - } else { - while (repos.hasNext()) { - Repository repo = (Repository) repos.next(); - activeURLs.add(repo.getURL().toString()); + /* + public void render(HttpServletRequest request, HttpServletResponse response) + throws IOException { - pw.println(""); - pw.println("" + repo.getName() + ""); - pw.println("" + repo.getURL() + ""); - pw.println("" - + new Date(repo.getLastModified()) + ""); - pw.println(""); - pw.println("
"); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("
"); - pw.println(""); - pw.println(""); + PrintWriter pw = response.getWriter(); + this.header(pw); + + Iterator repos; + BundleRepositoryAdmin repoAdmin = getBundleRepositoryAdmin(); + if (repoAdmin != null) { + repos = repoAdmin.getRepositories(); + } else { + repos = Collections.emptyList().iterator(); } - } - // list any repositories configured but not active - for (int i = 0; i < this.repoURLs.length; i++) { - if (!activeURLs.contains(this.repoURLs[i])) { + Set activeURLs = new HashSet(); + if (!repos.hasNext()) { pw.println(""); - pw.println("-"); - pw.println("" + this.repoURLs[i] + ""); - pw.println("[inactive, click Refresh to activate]"); - pw.println(""); - pw.println("
"); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("
"); - pw.println(""); + pw.println("No Active Repositories"); pw.println(""); + } else { + while (repos.hasNext()) { + Repository repo = (Repository) repos.next(); + + activeURLs.add(repo.getURL().toString()); + + pw.println(""); + pw.println("" + repo.getName() + ""); + pw.println("" + repo.getURL() + ""); + pw.println("" + + new Date(repo.getLastModified()) + ""); + pw.println(""); + pw.println("
"); + pw.println(""); + pw.println(""); + pw.println(""); + pw.println("
"); + pw.println(""); + pw.println(""); + } } - } - this.footer(pw); + // list any repositories configured but not active + for (int i = 0; i < this.repoURLs.length; i++) { + if (!activeURLs.contains(this.repoURLs[i])) { + pw.println(""); + pw.println("-"); + pw.println("" + this.repoURLs[i] + ""); + pw.println("[inactive, click Refresh to activate]"); + pw.println(""); + pw.println("
"); + pw.println(""); + pw.println(""); + pw.println(""); + pw.println("
"); + pw.println(""); + pw.println(""); + } + } - this.listResources(pw); - } -*/ - private void header(PrintWriter pw) { - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); + this.footer(pw); + + this.listResources(pw); + } + */ + private void header( PrintWriter pw ) + { + pw.println( "
Bundle Repositories
NameURLLast Modification Time 
" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } - private void footer(PrintWriter pw) { - pw.println("
Bundle Repositories
NameURLLast Modification Time 
"); + + private void footer( PrintWriter pw ) + { + pw.println( "" ); } - private void resourcesHeader(PrintWriter pw, boolean doForm) { - if (doForm) { - pw.println("
"); - pw.println(""); + private void resourcesHeader( PrintWriter pw, boolean doForm ) + { + + if ( doForm ) + { + pw.println( "" ); + pw.println( "" ); } - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); + pw.println( "
Available Resources
DeployNameVersion
" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } -/* - private void listResources(PrintWriter pw) { - InstallerService is = getInstallerService(); - if (is == null) { - return; - } - Map bundles = this.getBundles(); - Iterator resources = is.getBundleRepositoryAdmin().getResources(); - SortedSet resSet = new TreeSet( - new Comparator() { - public int compare(Resource o1, Resource o2) { - if (o1 == o2 || o1.equals(o2)) { - return 0; - } + /* + private void listResources(PrintWriter pw) { + InstallerService is = getInstallerService(); + if (is == null) { + return; + } + + Map bundles = this.getBundles(); + + Iterator resources = is.getBundleRepositoryAdmin().getResources(); + SortedSet resSet = new TreeSet( + new Comparator() { + public int compare(Resource o1, Resource o2) { + if (o1 == o2 || o1.equals(o2)) { + return 0; + } - if (o1.getPresentationName().equals( - o2.getPresentationName())) { - return o1.getVersion().compareTo(o2.getVersion()); + if (o1.getPresentationName().equals( + o2.getPresentationName())) { + return o1.getVersion().compareTo(o2.getVersion()); + } + + return o1.getPresentationName().compareTo( + o2.getPresentationName()); } + }); - return o1.getPresentationName().compareTo( - o2.getPresentationName()); + while (resources.hasNext()) { + Resource res = (Resource) resources.next(); + Version ver = bundles.get(res.getSymbolicName()); + if (ver == null || ver.compareTo(res.getVersion()) < 0) { + resSet.add(res); } - }); - - while (resources.hasNext()) { - Resource res = (Resource) resources.next(); - Version ver = bundles.get(res.getSymbolicName()); - if (ver == null || ver.compareTo(res.getVersion()) < 0) { - resSet.add(res); } - } - this.resourcesHeader(pw, !resSet.isEmpty()); + this.resourcesHeader(pw, !resSet.isEmpty()); - for (Resource resource : resSet) { - this.printResource(pw, resource); - } + for (Resource resource : resSet) { + this.printResource(pw, resource); + } - this.resourcesFooter(pw, !resSet.isEmpty()); - } + this.resourcesFooter(pw, !resSet.isEmpty()); + } - private void printResource(PrintWriter pw, Resource res) { - pw.println(""); - pw.println(""); - - // check whether the resource is an assembly (category name) - String style = ""; - String[] cat = res.getCategories(); - for (int i = 0; cat != null && i < cat.length; i++) { - if ("assembly".equals(cat[i])) { - style = "style='font-weight:bold'"; + private void printResource(PrintWriter pw, Resource res) { + pw.println(""); + pw.println(""); + + // check whether the resource is an assembly (category name) + String style = ""; + String[] cat = res.getCategories(); + for (int i = 0; cat != null && i < cat.length; i++) { + if ("assembly".equals(cat[i])) { + style = "style='font-weight:bold'"; + } } - } - pw.println(""); - pw.println(""); + pw.println(""); + pw.println(""); - pw.println(""); - } -*/ - private void resourcesButtons(PrintWriter pw) { - pw.println(""); - pw.println(""); - pw.println(""); + pw.println(""); + } + */ + private void resourcesButtons( PrintWriter pw ) + { + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } - private void resourcesFooter(PrintWriter pw, boolean doForm) { - if (doForm) { - this.resourcesButtons(pw); + + private void resourcesFooter( PrintWriter pw, boolean doForm ) + { + if ( doForm ) + { + this.resourcesButtons( pw ); } - pw.println("
Available Resources
DeployNameVersion
" - + res.getPresentationName() + " (" + res.getSymbolicName() - + ")" - + res.getVersion() + "" + + res.getPresentationName() + " (" + res.getSymbolicName() + + ")" + + res.getVersion() + "
 "); - pw.println(""); - pw.println("   "); - pw.println(""); - pw.println("
 " ); + pw.println( "" ); + pw.println( "   " ); + pw + .println( "" ); + pw.println( "
"); + pw.println( "" ); } - private Map getBundles() { + + private Map getBundles() + { Map bundles = new HashMap(); Bundle[] installed = getBundleContext().getBundles(); - for (int i = 0; i < installed.length; i++) { - String ver = (String) installed[i].getHeaders().get( - Constants.BUNDLE_VERSION); - Version bundleVersion = Version.parseVersion(ver); + for ( int i = 0; i < installed.length; i++ ) + { + String ver = ( String ) installed[i].getHeaders().get( Constants.BUNDLE_VERSION ); + Version bundleVersion = Version.parseVersion( ver ); // assume one bundle instance per symbolic name !! // only add if there is a symbolic name ! - if (installed[i].getSymbolicName() != null) { - bundles.put(installed[i].getSymbolicName(), bundleVersion); + if ( installed[i].getSymbolicName() != null ) + { + bundles.put( installed[i].getSymbolicName(), bundleVersion ); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/InstallFromRepoAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/InstallFromRepoAction.java index 93a1eb78c1b..109f09589a1 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/InstallFromRepoAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/InstallFromRepoAction.java @@ -16,17 +16,24 @@ */ package org.apache.felix.webconsole.internal.obr; + import org.apache.felix.webconsole.Action; -public abstract class InstallFromRepoAction extends AbstractObrPlugin implements Action { + +public abstract class InstallFromRepoAction extends AbstractObrPlugin implements Action +{ public static final String NAME = "installFromOBR"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return NAME; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/RefreshRepoAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/RefreshRepoAction.java index 100f736b3dc..aa495a141dd 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/RefreshRepoAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/obr/RefreshRepoAction.java @@ -16,72 +16,79 @@ */ package org.apache.felix.webconsole.internal.obr; + import org.apache.felix.webconsole.Action; -public abstract class RefreshRepoAction extends AbstractObrPlugin implements Action { + +public abstract class RefreshRepoAction extends AbstractObrPlugin implements Action +{ public static final String NAME = "refreshOBR"; public static final String PARAM_REPO = "repository"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return NAME; } -/* - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) { - - BundleRepositoryAdmin repoAdmin = getBundleRepositoryAdmin(); - if (repoAdmin != null) { - String repositoryURL = request.getParameter("repository"); - Iterator repos = repoAdmin.getRepositories(); - Repository repo = this.getRepository(repos, repositoryURL); - - URL repoURL = null; - if (repo != null) { - repoURL = repo.getURL(); - } else { - try { - repoURL = new URL(repositoryURL); - } catch (Throwable t) { - // don't care, just ignore + /* + public boolean performAction(HttpServletRequest request, + HttpServletResponse response) { + + BundleRepositoryAdmin repoAdmin = getBundleRepositoryAdmin(); + if (repoAdmin != null) { + String repositoryURL = request.getParameter("repository"); + Iterator repos = repoAdmin.getRepositories(); + Repository repo = this.getRepository(repos, repositoryURL); + + URL repoURL = null; + if (repo != null) { + repoURL = repo.getURL(); + } else { + try { + repoURL = new URL(repositoryURL); + } catch (Throwable t) { + // don't care, just ignore + } } - } - // log.log(LogService.LOG_DEBUG, "Refreshing " + repo.getURL()); - if (repoURL != null) { - try { - repoAdmin.addRepository(repoURL); - } catch (Exception e) { - // TODO: log.log(LogService.LOG_ERROR, "Cannot refresh - // Repository " + repo.getURL()); + // log.log(LogService.LOG_DEBUG, "Refreshing " + repo.getURL()); + if (repoURL != null) { + try { + repoAdmin.addRepository(repoURL); + } catch (Exception e) { + // TODO: log.log(LogService.LOG_ERROR, "Cannot refresh + // Repository " + repo.getURL()); + } } } - } - return true; - } + return true; + } - // ---------- internal ----------------------------------------------------- + // ---------- internal ----------------------------------------------------- - private Repository getRepository(Iterator repos, - String repositoryUrl) { - if (repositoryUrl == null || repositoryUrl.length() == 0) { - return null; - } + private Repository getRepository(Iterator repos, + String repositoryUrl) { + if (repositoryUrl == null || repositoryUrl.length() == 0) { + return null; + } - while (repos.hasNext()) { - Repository repo = repos.next(); - if (repositoryUrl.equals(repo.getURL().toString())) { - return repo; + while (repos.hasNext()) { + Repository repo = repos.next(); + if (repositoryUrl.equals(repo.getURL().toString())) { + return repo; + } } - } - return null; - } -*/ + return null; + } + */ } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/ConfigurationListener.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/ConfigurationListener.java index 172ebbb6330..bc6e1f40ded 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/ConfigurationListener.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/ConfigurationListener.java @@ -18,6 +18,7 @@ */ package org.apache.felix.webconsole.internal.servlet; + import java.util.Dictionary; import java.util.Hashtable; @@ -25,28 +26,34 @@ import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ManagedService; -class ConfigurationListener implements ManagedService { + +class ConfigurationListener implements ManagedService +{ private final OsgiManager osgiManager; - static ServiceRegistration create(OsgiManager osgiManager) { - ConfigurationListener cl = new ConfigurationListener(osgiManager); + + static ServiceRegistration create( OsgiManager osgiManager ) + { + ConfigurationListener cl = new ConfigurationListener( osgiManager ); Dictionary props = new Hashtable(); - props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation"); - props.put(Constants.SERVICE_DESCRIPTION, - "OSGi Management Console Configuration Receiver"); - props.put(Constants.SERVICE_PID, osgiManager.getClass().getName()); + props.put( Constants.SERVICE_VENDOR, "The Apache Software Foundation" ); + props.put( Constants.SERVICE_DESCRIPTION, "OSGi Management Console Configuration Receiver" ); + props.put( Constants.SERVICE_PID, osgiManager.getClass().getName() ); - return osgiManager.getBundleContext().registerService( - ManagedService.class.getName(), cl, props); + return osgiManager.getBundleContext().registerService( ManagedService.class.getName(), cl, props ); } - private ConfigurationListener(OsgiManager osgiManager) { + + private ConfigurationListener( OsgiManager osgiManager ) + { this.osgiManager = osgiManager; } - public void updated(Dictionary config) { - osgiManager.updateConfiguration(config); + + public void updated( Dictionary config ) + { + osgiManager.updateConfiguration( config ); } } \ No newline at end of file diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/Logger.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/Logger.java index 28d9dff3ad7..7ff6f1011f3 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/Logger.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/Logger.java @@ -18,37 +18,52 @@ */ package org.apache.felix.webconsole.internal.servlet; + import org.osgi.framework.BundleContext; import org.osgi.service.log.LogService; import org.osgi.util.tracker.ServiceTracker; -public class Logger { + +public class Logger +{ private ServiceTracker logTracker; - Logger(BundleContext bundleContext) { - logTracker = new ServiceTracker(bundleContext, - LogService.class.getName(), null); + + Logger( BundleContext bundleContext ) + { + logTracker = new ServiceTracker( bundleContext, LogService.class.getName(), null ); logTracker.open(); } - void dispose() { - if (logTracker != null) { + + void dispose() + { + if ( logTracker != null ) + { logTracker.close(); } } - public void log(int logLevel, String message) { - log(logLevel, message, null); + + public void log( int logLevel, String message ) + { + log( logLevel, message, null ); } - public void log(int logLevel, String message, Throwable t) { + + public void log( int logLevel, String message, Throwable t ) + { Object log = logTracker.getService(); - if (log != null) { - ((LogService) log).log(logLevel, message, t); - } else { + if ( log != null ) + { + ( ( LogService ) log ).log( logLevel, message, t ); + } + else + { String level; - switch (logLevel) { + switch ( logLevel ) + { case LogService.LOG_DEBUG: level = "*DEBUG*"; break; @@ -66,13 +81,15 @@ public void log(int logLevel, String message, Throwable t) { break; } - if (message == null && t != null) { + if ( message == null && t != null ) + { message = t.getMessage(); } - System.out.println(level + " " + message); - if (t != null) { - t.printStackTrace(System.out); + System.out.println( level + " " + message ); + if ( t != null ) + { + t.printStackTrace( System.out ); } } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManager.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManager.java index d5b33e480d2..f5b5c6e60a8 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManager.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManager.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.servlet; + import java.io.IOException; import java.io.PrintWriter; import java.util.Dictionary; @@ -70,13 +71,15 @@ import org.osgi.service.log.LogService; import org.osgi.util.tracker.ServiceTracker; + /** * The OSGi Manager TODO * * @scr.component ds="no" label="%manager.name" * description="%manager.description" */ -public class OsgiManager extends GenericServlet { +public class OsgiManager extends GenericServlet +{ /** Pseudo class version ID to keep the IDE quite. */ private static final long serialVersionUID = 1L; @@ -119,15 +122,12 @@ public class OsgiManager extends GenericServlet { */ private static final String DEFAULT_MANAGER_ROOT = "/system/console"; - private static final Class[] PLUGIN_CLASSES = { - AjaxConfigManagerAction.class, ComponentConfigurationPrinter.class, - ComponentRenderAction.class, ConfigManager.class, - AjaxBundleDetailsAction.class, BundleListRender.class, - InstallAction.class, RefreshPackagesAction.class, - SetStartLevelAction.class, StartAction.class, StopAction.class, - UninstallAction.class, UpdateAction.class, - ConfigurationRender.class, GCAction.class, - ShutdownAction.class, ShutdownRender.class, VMStatRender.class }; + private static final Class[] PLUGIN_CLASSES = + { AjaxConfigManagerAction.class, ComponentConfigurationPrinter.class, ComponentRenderAction.class, + ConfigManager.class, AjaxBundleDetailsAction.class, BundleListRender.class, InstallAction.class, + RefreshPackagesAction.class, SetStartLevelAction.class, StartAction.class, StopAction.class, + UninstallAction.class, UpdateAction.class, ConfigurationRender.class, GCAction.class, ShutdownAction.class, + ShutdownRender.class, VMStatRender.class }; private BundleContext bundleContext; @@ -155,65 +155,83 @@ public class OsgiManager extends GenericServlet { private Dictionary configuration; - public OsgiManager(BundleContext bundleContext) { + + public OsgiManager( BundleContext bundleContext ) + { this.bundleContext = bundleContext; - this.log = new Logger(bundleContext); + this.log = new Logger( bundleContext ); - updateConfiguration(null); + updateConfiguration( null ); - try { - this.configurationListener = ConfigurationListener.create(this); - } catch (Throwable t) { + try + { + this.configurationListener = ConfigurationListener.create( this ); + } + catch ( Throwable t ) + { // might be caused by CM not available } // track renders and operations - operationsTracker = new OperationServiceTracker(this); + operationsTracker = new OperationServiceTracker( this ); operationsTracker.open(); - rendersTracker = new RenderServiceTracker(this); + rendersTracker = new RenderServiceTracker( this ); rendersTracker.open(); - httpServiceTracker = new HttpServiceTracker(this); + httpServiceTracker = new HttpServiceTracker( this ); httpServiceTracker.open(); - for (int i=0; i < PLUGIN_CLASSES.length; i++) { + for ( int i = 0; i < PLUGIN_CLASSES.length; i++ ) + { Class pluginClass = PLUGIN_CLASSES[i]; - try { + try + { Object plugin = pluginClass.newInstance(); - if (plugin instanceof BaseManagementPlugin) { - ((BaseManagementPlugin) plugin).setBundleContext(bundleContext); - ((BaseManagementPlugin) plugin).setLogger(log); + if ( plugin instanceof BaseManagementPlugin ) + { + ( ( BaseManagementPlugin ) plugin ).setBundleContext( bundleContext ); + ( ( BaseManagementPlugin ) plugin ).setLogger( log ); } - if (plugin instanceof Action) { - bindOperation((Action) plugin); + if ( plugin instanceof Action ) + { + bindOperation( ( Action ) plugin ); } - if (plugin instanceof Render) { - bindRender((Render) plugin); + if ( plugin instanceof Render ) + { + bindRender( ( Render ) plugin ); } - } catch (Throwable t) { + } + catch ( Throwable t ) + { // todo: log } } } - public void dispose() { - if (configurationListener != null) { + public void dispose() + { + + if ( configurationListener != null ) + { configurationListener.unregister(); configurationListener = null; } - if (operationsTracker != null) { + if ( operationsTracker != null ) + { operationsTracker.close(); operationsTracker = null; } - if (rendersTracker != null) { + if ( rendersTracker != null ) + { rendersTracker.close(); rendersTracker = null; } - if (httpServiceTracker != null) { + if ( httpServiceTracker != null ) + { httpServiceTracker.close(); httpServiceTracker = null; } @@ -223,35 +241,39 @@ public void dispose() { this.operations.clear(); this.renders.clear(); - if (log != null) { + if ( log != null ) + { log.dispose(); } this.bundleContext = null; } - public void service(ServletRequest req, ServletResponse res) - throws ServletException, IOException { - HttpServletRequest request = (HttpServletRequest) req; - HttpServletResponse response = (HttpServletResponse) res; + public void service( ServletRequest req, ServletResponse res ) throws ServletException, IOException + { + + HttpServletRequest request = ( HttpServletRequest ) req; + HttpServletResponse response = ( HttpServletResponse ) res; // handle the request action, terminate if done - if (this.handleAction(request, response)) { + if ( this.handleAction( request, response ) ) + { return; } // check whether we are not at .../{webManagerRoot} - if (request.getRequestURI().endsWith(this.webManagerRoot)) { - response.sendRedirect(request.getRequestURI() + "/" - + this.defaultRender.getName()); + if ( request.getRequestURI().endsWith( this.webManagerRoot ) ) + { + response.sendRedirect( request.getRequestURI() + "/" + this.defaultRender.getName() ); return; } // otherwise we render the response - Render render = this.getRender(request); - if (render == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND); + Render render = this.getRender( request ); + if ( render == null ) + { + response.sendError( HttpServletResponse.SC_NOT_FOUND ); return; } @@ -260,47 +282,56 @@ public void service(ServletRequest req, ServletResponse res) // account: // Boolean.valueOf(request.getParameter("disabled")).booleanValue(); - PrintWriter pw = Util.startHtml(response, render.getLabel()); - Util.navigation(pw, this.renders.values(), current, disabled); + PrintWriter pw = Util.startHtml( response, render.getLabel() ); + Util.navigation( pw, this.renders.values(), current, disabled ); - render.render(request, response); + render.render( request, response ); - Util.endHhtml(pw); + Util.endHhtml( pw ); } - protected boolean handleAction(HttpServletRequest req, - HttpServletResponse resp) throws IOException { + + protected boolean handleAction( HttpServletRequest req, HttpServletResponse resp ) throws IOException + { // check action - String actionName = this.getParameter(req, Util.PARAM_ACTION); - if (actionName != null) { - Action action = (Action) this.operations.get(actionName); - if (action != null) { + String actionName = this.getParameter( req, Util.PARAM_ACTION ); + if ( actionName != null ) + { + Action action = ( Action ) this.operations.get( actionName ); + if ( action != null ) + { boolean redirect = true; - try { - redirect = action.performAction(req, resp); - } catch (IOException ioe) { - this.log(ioe.getMessage(), ioe); - } catch (ServletException se) { - this.log(se.getMessage(), se.getRootCause()); + try + { + redirect = action.performAction( req, resp ); + } + catch ( IOException ioe ) + { + this.log( ioe.getMessage(), ioe ); + } + catch ( ServletException se ) + { + this.log( se.getMessage(), se.getRootCause() ); } // maybe overwrite redirect - if (PARAM_NO_REDIRECT_AFTER_ACTION.equals(getParameter(req, - PARAM_NO_REDIRECT_AFTER_ACTION))) { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/html"); - resp.getWriter().println("Ok"); + if ( PARAM_NO_REDIRECT_AFTER_ACTION.equals( getParameter( req, PARAM_NO_REDIRECT_AFTER_ACTION ) ) ) + { + resp.setStatus( HttpServletResponse.SC_OK ); + resp.setContentType( "text/html" ); + resp.getWriter().println( "Ok" ); return true; } - if (redirect) { + if ( redirect ) + { String uri = req.getRequestURI(); // Object pars = // req.getAttribute(Action.ATTR_REDIRECT_PARAMETERS); // if (pars instanceof String) { // uri += "?" + pars; // } - resp.sendRedirect(uri); + resp.sendRedirect( uri ); } return true; } @@ -309,72 +340,89 @@ protected boolean handleAction(HttpServletRequest req, return false; } - protected Render getRender(HttpServletRequest request) { + + protected Render getRender( HttpServletRequest request ) + { String page = request.getRequestURI(); // remove trailing slashes - while (page.endsWith("/")) { - page = page.substring(0, page.length() - 1); + while ( page.endsWith( "/" ) ) + { + page = page.substring( 0, page.length() - 1 ); } // take last part of the name - int lastSlash = page.lastIndexOf('/'); - if (lastSlash >= 0) { - page = page.substring(lastSlash + 1); + int lastSlash = page.lastIndexOf( '/' ); + if ( lastSlash >= 0 ) + { + page = page.substring( lastSlash + 1 ); } - Render render = (Render) this.renders.get(page); - return (render == null) ? this.defaultRender : render; + Render render = ( Render ) this.renders.get( page ); + return ( render == null ) ? this.defaultRender : render; } - private String getParameter(HttpServletRequest request, String name) { + + private String getParameter( HttpServletRequest request, String name ) + { // just get the parameter if not a multipart/form-data POST - if (!ServletFileUpload.isMultipartContent(new ServletRequestContext( - request))) { - return request.getParameter(name); + if ( !ServletFileUpload.isMultipartContent( new ServletRequestContext( request ) ) ) + { + return request.getParameter( name ); } // check, whether we alread have the parameters - Map params = (Map) request.getAttribute(Util.ATTR_FILEUPLOAD); - if (params == null) { + Map params = ( Map ) request.getAttribute( Util.ATTR_FILEUPLOAD ); + if ( params == null ) + { // parameters not read yet, read now // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); - factory.setSizeThreshold(256000); + factory.setSizeThreshold( 256000 ); // Create a new file upload handler - ServletFileUpload upload = new ServletFileUpload(factory); - upload.setSizeMax(-1); + ServletFileUpload upload = new ServletFileUpload( factory ); + upload.setSizeMax( -1 ); // Parse the request params = new HashMap(); - try { - List items = upload.parseRequest(request); - for (Iterator fiter=items.iterator(); fiter.hasNext(); ) { - FileItem fi = (FileItem) fiter.next(); - FileItem[] current = (FileItem[]) params.get(fi.getFieldName()); - if (current == null) { - current = new FileItem[] { fi }; - } else { + try + { + List items = upload.parseRequest( request ); + for ( Iterator fiter = items.iterator(); fiter.hasNext(); ) + { + FileItem fi = ( FileItem ) fiter.next(); + FileItem[] current = ( FileItem[] ) params.get( fi.getFieldName() ); + if ( current == null ) + { + current = new FileItem[] + { fi }; + } + else + { FileItem[] newCurrent = new FileItem[current.length + 1]; - System.arraycopy(current, 0, newCurrent, 0, - current.length); + System.arraycopy( current, 0, newCurrent, 0, current.length ); newCurrent[current.length] = fi; current = newCurrent; } - params.put(fi.getFieldName(), current); + params.put( fi.getFieldName(), current ); } - } catch (FileUploadException fue) { + } + catch ( FileUploadException fue ) + { // TODO: log } - request.setAttribute(Util.ATTR_FILEUPLOAD, params); + request.setAttribute( Util.ATTR_FILEUPLOAD, params ); } - FileItem[] param = (FileItem[]) params.get(name); - if (param != null) { - for (int i = 0; i < param.length; i++) { - if (param[i].isFormField()) { + FileItem[] param = ( FileItem[] ) params.get( name ); + if ( param != null ) + { + for ( int i = 0; i < param.length; i++ ) + { + if ( param[i].isFormField() ) + { return param[i].getString(); } } @@ -384,188 +432,245 @@ private String getParameter(HttpServletRequest request, String name) { return null; } - BundleContext getBundleContext() { + + BundleContext getBundleContext() + { return bundleContext; } - private static class HttpServiceTracker extends ServiceTracker { + private static class HttpServiceTracker extends ServiceTracker + { private final OsgiManager osgiManager; - HttpServiceTracker(OsgiManager osgiManager) { - super(osgiManager.getBundleContext(), HttpService.class.getName(), - null); + + HttpServiceTracker( OsgiManager osgiManager ) + { + super( osgiManager.getBundleContext(), HttpService.class.getName(), null ); this.osgiManager = osgiManager; } - public Object addingService(ServiceReference reference) { - Object operation = super.addingService(reference); - if (operation instanceof HttpService) { - osgiManager.bindHttpService((HttpService) operation); + + public Object addingService( ServiceReference reference ) + { + Object operation = super.addingService( reference ); + if ( operation instanceof HttpService ) + { + osgiManager.bindHttpService( ( HttpService ) operation ); } return operation; } - public void removedService(ServiceReference reference, Object service) { - if (service instanceof HttpService) { - osgiManager.unbindHttpService((HttpService) service); + + public void removedService( ServiceReference reference, Object service ) + { + if ( service instanceof HttpService ) + { + osgiManager.unbindHttpService( ( HttpService ) service ); } - super.removedService(reference, service); + super.removedService( reference, service ); } } - private static class OperationServiceTracker extends ServiceTracker { + private static class OperationServiceTracker extends ServiceTracker + { private final OsgiManager osgiManager; - OperationServiceTracker(OsgiManager osgiManager) { - super(osgiManager.getBundleContext(), Action.SERVICE, null); + + OperationServiceTracker( OsgiManager osgiManager ) + { + super( osgiManager.getBundleContext(), Action.SERVICE, null ); this.osgiManager = osgiManager; } - public Object addingService(ServiceReference reference) { - Object operation = super.addingService(reference); - if (operation instanceof Action) { - osgiManager.bindOperation((Action) operation); + + public Object addingService( ServiceReference reference ) + { + Object operation = super.addingService( reference ); + if ( operation instanceof Action ) + { + osgiManager.bindOperation( ( Action ) operation ); } return operation; } - public void removedService(ServiceReference reference, Object service) { - if (service instanceof Action) { - osgiManager.bindOperation((Action) service); + + public void removedService( ServiceReference reference, Object service ) + { + if ( service instanceof Action ) + { + osgiManager.bindOperation( ( Action ) service ); } - super.removedService(reference, service); + super.removedService( reference, service ); } } - private static class RenderServiceTracker extends ServiceTracker { + private static class RenderServiceTracker extends ServiceTracker + { private final OsgiManager osgiManager; - RenderServiceTracker(OsgiManager osgiManager) { - super(osgiManager.getBundleContext(), Render.SERVICE, null); + + RenderServiceTracker( OsgiManager osgiManager ) + { + super( osgiManager.getBundleContext(), Render.SERVICE, null ); this.osgiManager = osgiManager; } - public Object addingService(ServiceReference reference) { - Object operation = super.addingService(reference); - if (operation instanceof Render) { - osgiManager.bindRender((Render) operation); + + public Object addingService( ServiceReference reference ) + { + Object operation = super.addingService( reference ); + if ( operation instanceof Render ) + { + osgiManager.bindRender( ( Render ) operation ); } return operation; } - public void removedService(ServiceReference reference, Object service) { - if (service instanceof Render) { - osgiManager.bindRender((Render) service); + + public void removedService( ServiceReference reference, Object service ) + { + if ( service instanceof Render ) + { + osgiManager.bindRender( ( Render ) service ); } - super.removedService(reference, service); + super.removedService( reference, service ); } } - protected synchronized void bindHttpService(HttpService httpService) { + + protected synchronized void bindHttpService( HttpService httpService ) + { Dictionary config = getConfiguration(); // get authentication details - String realm = this.getProperty(config, PROP_REALM, - "OSGi Management Console"); - String userId = this.getProperty(config, PROP_USER_NAME, null); - String password = this.getProperty(config, PROP_PASSWORD, null); + String realm = this.getProperty( config, PROP_REALM, "OSGi Management Console" ); + String userId = this.getProperty( config, PROP_USER_NAME, null ); + String password = this.getProperty( config, PROP_PASSWORD, null ); // register the servlet and resources - try { - HttpContext httpContext = new OsgiManagerHttpContext(httpService, realm, - userId, password); + try + { + HttpContext httpContext = new OsgiManagerHttpContext( httpService, realm, userId, password ); - Dictionary servletConfig = toStringConfig(config); + Dictionary servletConfig = toStringConfig( config ); - httpService.registerServlet(this.webManagerRoot, this, - servletConfig, httpContext); - httpService.registerResources(this.webManagerRoot + "/res", "/res", - httpContext); + httpService.registerServlet( this.webManagerRoot, this, servletConfig, httpContext ); + httpService.registerResources( this.webManagerRoot + "/res", "/res", httpContext ); - } catch (Exception e) { - log.log(LogService.LOG_ERROR, "Problem setting up", e); + } + catch ( Exception e ) + { + log.log( LogService.LOG_ERROR, "Problem setting up", e ); } this.httpService = httpService; } - protected synchronized void unbindHttpService(HttpService httpService) { - httpService.unregister(this.webManagerRoot + "/res"); - httpService.unregister(this.webManagerRoot); - if (this.httpService == httpService) { + protected synchronized void unbindHttpService( HttpService httpService ) + { + httpService.unregister( this.webManagerRoot + "/res" ); + httpService.unregister( this.webManagerRoot ); + + if ( this.httpService == httpService ) + { this.httpService = null; } } - protected void bindOperation(Action operation) { - this.operations.put(operation.getName(), operation); + + protected void bindOperation( Action operation ) + { + this.operations.put( operation.getName(), operation ); } - protected void unbindOperation(Action operation) { - this.operations.remove(operation.getName()); + + protected void unbindOperation( Action operation ) + { + this.operations.remove( operation.getName() ); } - protected void bindRender(Render render) { - this.renders.put(render.getName(), render); - if (this.defaultRender == null) { + protected void bindRender( Render render ) + { + this.renders.put( render.getName(), render ); + + if ( this.defaultRender == null ) + { this.defaultRender = render; - } else if (render.getName().equals(this.defaultRenderName)) { + } + else if ( render.getName().equals( this.defaultRenderName ) ) + { this.defaultRender = render; } } - protected void unbindRender(Render render) { - this.renders.remove(render.getName()); - if (this.defaultRender == render) { - if (this.renders.isEmpty()) { + protected void unbindRender( Render render ) + { + this.renders.remove( render.getName() ); + + if ( this.defaultRender == render ) + { + if ( this.renders.isEmpty() ) + { this.defaultRender = null; - } else { - this.defaultRender = (Render) renders.values().iterator().next(); + } + else + { + this.defaultRender = ( Render ) renders.values().iterator().next(); } } } - private Dictionary getConfiguration() { + + private Dictionary getConfiguration() + { return configuration; } - void updateConfiguration(Dictionary config) { - if (config == null) { + + void updateConfiguration( Dictionary config ) + { + if ( config == null ) + { config = new Hashtable(); } configuration = config; - defaultRenderName = (String) config.get(PROP_DEFAULT_RENDER); - if (defaultRenderName != null && renders.get(defaultRenderName) != null) { - defaultRender = (Render) renders.get(defaultRenderName); + defaultRenderName = ( String ) config.get( PROP_DEFAULT_RENDER ); + if ( defaultRenderName != null && renders.get( defaultRenderName ) != null ) + { + defaultRender = ( Render ) renders.get( defaultRenderName ); } // get the web manager root path - webManagerRoot = this.getProperty(config, PROP_MANAGER_ROOT, DEFAULT_MANAGER_ROOT); - if (!webManagerRoot.startsWith("/")) { + webManagerRoot = this.getProperty( config, PROP_MANAGER_ROOT, DEFAULT_MANAGER_ROOT ); + if ( !webManagerRoot.startsWith( "/" ) ) + { webManagerRoot = "/" + webManagerRoot; } // might update http service registration HttpService httpService = this.httpService; - if (httpService != null) { - synchronized (this) { - unbindHttpService(httpService); - bindHttpService(httpService); + if ( httpService != null ) + { + synchronized ( this ) + { + unbindHttpService( httpService ); + bindHttpService( httpService ); } } } + /** * Returns the named property from the configuration. If the property does * not exist, the default value def is returned. @@ -576,25 +681,30 @@ void updateConfiguration(Dictionary config) { * @return The value of the named property as a string or def * if the property does not exist */ - private String getProperty(Dictionary config, String name, - String def) { - Object value = config.get(name); - if (value instanceof String) { - return (String) value; + private String getProperty( Dictionary config, String name, String def ) + { + Object value = config.get( name ); + if ( value instanceof String ) + { + return ( String ) value; } - if (value == null) { + if ( value == null ) + { return def; } - return String.valueOf(value); + return String.valueOf( value ); } - private Dictionary toStringConfig(Dictionary config) { + + private Dictionary toStringConfig( Dictionary config ) + { Dictionary stringConfig = new Hashtable(); - for (Enumeration ke = config.keys(); ke.hasMoreElements();) { + for ( Enumeration ke = config.keys(); ke.hasMoreElements(); ) + { Object key = ke.nextElement(); - stringConfig.put(key.toString(), String.valueOf(config.get(key))); + stringConfig.put( key.toString(), String.valueOf( config.get( key ) ) ); } return stringConfig; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManagerHttpContext.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManagerHttpContext.java index fe705c9a040..8ae382cc6db 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManagerHttpContext.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/servlet/OsgiManagerHttpContext.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.servlet; + import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; @@ -26,7 +27,9 @@ import org.osgi.service.http.HttpContext; import org.osgi.service.http.HttpService; -final class OsgiManagerHttpContext implements HttpContext { + +final class OsgiManagerHttpContext implements HttpContext +{ private static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate"; @@ -52,25 +55,33 @@ final class OsgiManagerHttpContext implements HttpContext { private final HttpContext base; - OsgiManagerHttpContext(HttpService httpService, String realm, String userId, String password) { + + OsgiManagerHttpContext( HttpService httpService, String realm, String userId, String password ) + { this.base = httpService.createDefaultHttpContext(); this.realm = realm; this.userId = userId; - this.user = encode(userId, password); + this.user = encode( userId, password ); } - public String getMimeType(String name) { - return this.base.getMimeType(name); + + public String getMimeType( String name ) + { + return this.base.getMimeType( name ); } - public URL getResource(String name) { - URL url = this.base.getResource(name); - if (url == null && name.endsWith("/")) { - return this.base.getResource(name.substring(0, name.length() - 1)); + + public URL getResource( String name ) + { + URL url = this.base.getResource( name ); + if ( url == null && name.endsWith( "/" ) ) + { + return this.base.getResource( name.substring( 0, name.length() - 1 ) ); } return url; } + /** * Checks the Authorization header of the request for Basic * authentication user name and password. If contained, the credentials are @@ -86,34 +97,37 @@ public URL getResource(String name) { * @return true if authentication is required and not * satisfied by the request. */ - public boolean handleSecurity(HttpServletRequest request, - HttpServletResponse response) { + public boolean handleSecurity( HttpServletRequest request, HttpServletResponse response ) + { // don't care for authentication if no user name is configured - if (this.user == null) { + if ( this.user == null ) + { return true; } // Return immediately if the header is missing - String authHeader = request.getHeader(HEADER_AUTHORIZATION); - if (authHeader != null && authHeader.length() > 0) { + String authHeader = request.getHeader( HEADER_AUTHORIZATION ); + if ( authHeader != null && authHeader.length() > 0 ) + { // Get the authType (Basic, Digest) and authInfo (user/password) // from // the header authHeader = authHeader.trim(); - int blank = authHeader.indexOf(' '); - if (blank > 0) { - String authType = authHeader.substring(0, blank); - String authInfo = authHeader.substring(blank).trim(); + int blank = authHeader.indexOf( ' ' ); + if ( blank > 0 ) + { + String authType = authHeader.substring( 0, blank ); + String authInfo = authHeader.substring( blank ).trim(); // Check whether authorization type matches - if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC) - && this.user.equals(authInfo)) { + if ( authType.equalsIgnoreCase( AUTHENTICATION_SCHEME_BASIC ) && this.user.equals( authInfo ) ) + { // as per the spec, set attributes - request.setAttribute(HttpContext.AUTHENTICATION_TYPE, ""); - request.setAttribute(HttpContext.REMOTE_USER, this.userId); + request.setAttribute( HttpContext.AUTHENTICATION_TYPE, "" ); + request.setAttribute( HttpContext.REMOTE_USER, this.userId ); // succeed return true; @@ -122,13 +136,15 @@ public boolean handleSecurity(HttpServletRequest request, } // request authentication - response.setHeader(HEADER_WWW_AUTHENTICATE, AUTHENTICATION_SCHEME_BASIC - + " realm=\"" + this.realm + "\""); - try { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED); - } catch (IOException ioe) { + response.setHeader( HEADER_WWW_AUTHENTICATE, AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\"" ); + try + { + response.sendError( HttpServletResponse.SC_UNAUTHORIZED ); + } + catch ( IOException ioe ) + { // failed sending the error, fall back to setting the status - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setStatus( HttpServletResponse.SC_UNAUTHORIZED ); } // inform HttpService that authentication failed @@ -145,21 +161,27 @@ public boolean handleSecurity(HttpServletRequest request, * @return The Base64 encoded username/password pair or null * if user is null or empty. */ - public static String encode(String user, String password) { + public static String encode( String user, String password ) + { /* check arguments */ - if (user == null || user.length() == 0) return null; + if ( user == null || user.length() == 0 ) + return null; String srcString = user + ":"; - if (password != null && password.length() > 0) { + if ( password != null && password.length() > 0 ) + { srcString += password; } // need bytes byte[] src; - try { - src = srcString.getBytes("ISO-8859-1"); - } catch (UnsupportedEncodingException uee) { + try + { + src = srcString.getBytes( "ISO-8859-1" ); + } + catch ( UnsupportedEncodingException uee ) + { // we do not expect this, the API presribes ISO-8859-1 to be present // anyway, fallback to platform default src = srcString.getBytes(); @@ -168,7 +190,7 @@ public static String encode(String user, String password) { int srcsize = src.length; int tbllen = base64Table.length(); - StringBuffer result = new StringBuffer(srcsize); + StringBuffer result = new StringBuffer( srcsize ); /* encode */ int tblpos = 0; @@ -177,12 +199,17 @@ public static String encode(String user, String password) { int inpos = 0; int pos = 0; - while (inpos <= srcsize) { + while ( inpos <= srcsize ) + { - if (bitsread < 0) { - if (inpos < srcsize) { + if ( bitsread < 0 ) + { + if ( inpos < srcsize ) + { pos = src[inpos++]; - } else { + } + else + { // inpos++; // pos = 0; break; @@ -192,34 +219,40 @@ public static String encode(String user, String password) { tblpos = 0; bitpos = tbllen / 2; - while (bitpos > 0) { - if (bitsread < 0) { - pos = (inpos < srcsize) ? src[inpos] : '\0'; + while ( bitpos > 0 ) + { + if ( bitsread < 0 ) + { + pos = ( inpos < srcsize ) ? src[inpos] : '\0'; inpos++; bitsread = 7; } /* test if bit at pos in is set.. */ - if (((1 << bitsread) & pos) != 0) tblpos += bitpos; + if ( ( ( 1 << bitsread ) & pos ) != 0 ) + tblpos += bitpos; bitpos /= 2; bitsread--; } // got one - result.append(base64Table.charAt(tblpos)); + result.append( base64Table.charAt( tblpos ) ); } /* add the padding bytes */ - while (bitsread != -1) { + while ( bitsread != -1 ) + { bitpos = tbllen / 2; - while (bitpos > 0) { - if (bitsread < 0) bitsread = 7; + while ( bitpos > 0 ) + { + if ( bitsread < 0 ) + bitsread = 7; bitpos /= 2; bitsread--; } - result.append(base64Pad); + result.append( base64Pad ); } return result.toString(); diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/GCAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/GCAction.java index e2deacfa72e..0c54c01aed0 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/GCAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/GCAction.java @@ -16,25 +16,34 @@ */ package org.apache.felix.webconsole.internal.system; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.felix.webconsole.Action; -public class GCAction implements Action { + +public class GCAction implements Action +{ public static final String NAME = "gc"; public static final String LABEL = "Collect Garbage"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public boolean performAction(HttpServletRequest request, HttpServletResponse response) { + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { System.gc(); return false; } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownAction.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownAction.java index b176aa3b51d..105f97d439d 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownAction.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownAction.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.system; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -24,37 +25,51 @@ import org.osgi.framework.BundleException; import org.osgi.service.log.LogService; -public class ShutdownAction extends BaseManagementPlugin implements Action { + +public class ShutdownAction extends BaseManagementPlugin implements Action +{ public static final String NAME = "shutdown"; - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return NAME; } - public boolean performAction(HttpServletRequest request, - HttpServletResponse response) { + + public boolean performAction( HttpServletRequest request, HttpServletResponse response ) + { // simply terminate VM in case of shutdown :-) - Thread t = new Thread("Stopper") { - public void run() { - try { - Thread.sleep(2000L); - } catch (InterruptedException ie) { + Thread t = new Thread( "Stopper" ) + { + public void run() + { + try + { + Thread.sleep( 2000L ); + } + catch ( InterruptedException ie ) + { // ignore } - getLog().log(LogService.LOG_INFO, "Shutting down server now!"); + getLog().log( LogService.LOG_INFO, "Shutting down server now!" ); // stopping bundle 0 (system bundle) stops the framework - try { - getBundleContext().getBundle(0).stop(); - } catch (BundleException be) { - getLog().log(LogService.LOG_ERROR, - "Problem stopping Framework", be); + try + { + getBundleContext().getBundle( 0 ).stop(); + } + catch ( BundleException be ) + { + getLog().log( LogService.LOG_ERROR, "Problem stopping Framework", be ); } } }; diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownRender.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownRender.java index 9ed13642970..7382b1332f7 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownRender.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/ShutdownRender.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.system; + import java.io.IOException; import java.io.PrintWriter; @@ -24,33 +25,40 @@ import org.apache.felix.webconsole.Render; -public class ShutdownRender implements Render { + +public class ShutdownRender implements Render +{ public static final String NAME = "shutdown"; public static final String LABEL = null; // hide from navigation - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { + + public void render( HttpServletRequest request, HttpServletResponse response ) throws IOException + { PrintWriter pw = response.getWriter(); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("
Server terminated
"); - pw.println(""); - pw.println(""); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "
Server terminated
" ); + pw.println( "" ); + pw.println( "" ); } } diff --git a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/VMStatRender.java b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/VMStatRender.java index d501cf90555..9bf359bf43d 100644 --- a/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/VMStatRender.java +++ b/webconsole/src/main/java/org/apache/felix/webconsole/internal/system/VMStatRender.java @@ -16,6 +16,7 @@ */ package org.apache.felix.webconsole.internal.system; + import java.io.IOException; import java.io.PrintWriter; import java.util.Date; @@ -28,145 +29,152 @@ import org.apache.felix.webconsole.internal.Util; import org.apache.felix.webconsole.internal.core.SetStartLevelAction; -public class VMStatRender extends BaseManagementPlugin implements Render { + +public class VMStatRender extends BaseManagementPlugin implements Render +{ public static final String NAME = "vmstat"; public static final String LABEL = "System Information"; - private static final long startDate = (new Date()).getTime(); + private static final long startDate = ( new Date() ).getTime(); - public String getName() { + + public String getName() + { return NAME; } - public String getLabel() { + + public String getLabel() + { return LABEL; } - public void render(HttpServletRequest request, HttpServletResponse response) - throws IOException { + + public void render( HttpServletRequest request, HttpServletResponse response ) throws IOException + { PrintWriter pw = response.getWriter(); - pw.println(""); + pw.println( "" ); boolean shutdown = false; String target = request.getRequestURI(); - if (request.getParameter(Util.PARAM_SHUTDOWN) != null) { + if ( request.getParameter( Util.PARAM_SHUTDOWN ) != null ) + { target = ShutdownRender.NAME; shutdown = true; } - pw.println(""); - - pw.println(""); - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - pw.println(""); - pw.println("" ); + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + + this.infoLine( pw, "Java Runtime", "ABOUT_JRT" ); + this.infoLine( pw, "Java Virtual Machine", "ABOUT_JVM" ); + this.infoLine( pw, "Total Memory", "ABOUT_MEM" ); + this.infoLine( pw, "Used Memory", "ABOUT_USED" ); + this.infoLine( pw, "Free Memory", "ABOUT_FREE" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + + pw.println( "
Start Level Information:
System Start Level"); - pw.println("
"); - pw.println(""); - pw.println(""); - pw.println("  "); - pw.println("
"); - pw.println("
Default Bundle Start Level"); - pw.println("
"); - pw.println(""); - pw.println(""); - pw.println("  "); - pw.println("
"); - pw.println("
 "); - pw.println("
Server Information:
Last Started"); - pw.println(""); - pw.println("
Server"); - - if (!shutdown) { - pw.println(""); - pw.println(""); - } else { - pw.println(" "); - pw.println(""); - pw.println("Shutdown in  "); - pw.println(""); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( ""); - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - - pw.println(""); - pw.println(""); - pw.println(""); - - this.infoLine(pw, "Java Runtime", "ABOUT_JRT"); - this.infoLine(pw, "Java Virtual Machine", "ABOUT_JVM"); - this.infoLine(pw, "Total Memory", "ABOUT_MEM"); - this.infoLine(pw, "Used Memory", "ABOUT_USED"); - this.infoLine(pw, "Free Memory", "ABOUT_FREE"); - - pw.println(""); - pw.println(""); - pw.println(""); - pw.println(""); - - pw.println("
Start Level Information:
System Start Level" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "  " ); + pw.println( "" ); + pw.println( "
Default Bundle Start Level" ); + pw.println( "
" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "  " ); + pw.println( "
" ); + pw.println( "
 " ); + pw.println( "
Server Information:
Last Started" ); + pw.println( "" ); + pw.println( "
Server" ); + + if ( !shutdown ) + { + pw.println( "" ); + pw + .println( "" ); + } + else + { + pw.println( " " ); + pw.println( "" ); + pw.println( "Shutdown in  " ); + pw.println( "" ); } - pw.println("
 "); - pw.println("
Java Information:
Garbage Collection"); - pw.println(""); - pw.println(""); - pw.println("
"); + pw.println( "
 " ); + pw.println( "
Java Information:
Garbage Collection" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "
" ); } - private void infoLine(PrintWriter pw, String label, String jsName) { - pw.println(""); - pw.println("" + label + ""); - pw.println(""); - pw.println(""); - pw.println(""); + + private void infoLine( PrintWriter pw, String label, String jsName ) + { + pw.println( "" ); + pw.println( "" + label + "" ); + pw.println( "" ); + pw.println( "" ); + pw.println( "" ); } }