Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.apache.felix.webconsole.internal.servlet;
 
 
 import java.util.*;
 
 
 import  org.osgi.framework.*;
 import  org.osgi.service.http.HttpContext;
 import  org.osgi.service.http.HttpService;
 import  org.osgi.service.log.LogService;
The OSGi Manager TODO
 
 public class OsgiManager extends GenericServlet
 {

    
Pseudo class version ID to keep the IDE quite.
 
     private static final long serialVersionUID = 1L;

    
Old name of the request attribute provding the root to the web console. This attribute is no deprecated and replaced by WebConsoleConstants.ATTR_APP_ROOT.

Deprecated:
use WebConsoleConstants.ATTR_APP_ROOT instead
 
     private static final String ATTR_APP_ROOT_OLD = OsgiManager.class.getName() + ".appRoot";

    
Old name of the request attribute provding the mappings from label to page title. This attribute is no deprecated and replaced by WebConsoleConstants.ATTR_LABEL_MAP.

Deprecated:
use WebConsoleConstants.ATTR_LABEL_MAP instead
 
     private static final String ATTR_LABEL_MAP_OLD = OsgiManager.class.getName() + ".labelMap";

    
The name and value of a parameter which will prevent redirection to a render after the action has been executed (value is "_noredir_"). This may be used by programmatic action submissions.
 
     public static final String PARAM_NO_REDIRECT_AFTER_ACTION = "_noredir_";
 
     static final String PROP_MANAGER_ROOT = "manager.root";
 
     static final String PROP_DEFAULT_RENDER = "default.render";
 
     static final String PROP_REALM = "realm";
 
     static final String PROP_USER_NAME = "username";
 
     static final String PROP_PASSWORD = "password";
 
     static final String PROP_ENABLED_PLUGINS = "plugins";
 
     static final String DEFAULT_PAGE = .;
 
     static final String DEFAULT_REALM = "OSGi Management Console";
 
     static final String DEFAULT_USER_NAME = "admin";
 
     static final String DEFAULT_PASSWORD = "admin";

    
The default value for the PROP_MANAGER_ROOT configuration property (value is "/system/console").
 
     static final String DEFAULT_MANAGER_ROOT = "/system/console";
 
     static final String[] PLUGIN_CLASSES =
         {
             "org.apache.felix.webconsole.internal.compendium.ComponentConfigurationPrinter",
            "org.apache.felix.webconsole.internal.compendium.ComponentsServlet",
            "org.apache.felix.webconsole.internal.compendium.ConfigManager",
            "org.apache.felix.webconsole.internal.compendium.ConfigurationAdminConfigurationPrinter",
            "org.apache.felix.webconsole.internal.compendium.LogServlet",
            "org.apache.felix.webconsole.internal.compendium.PreferencesConfigurationPrinter",
            "org.apache.felix.webconsole.internal.core.BundlesServlet",
            "org.apache.felix.webconsole.internal.core.InstallAction",
            "org.apache.felix.webconsole.internal.core.SetStartLevelAction",
            "org.apache.felix.webconsole.internal.deppack.DepPackServlet",
            "org.apache.felix.webconsole.internal.misc.LicenseServlet",
            "org.apache.felix.webconsole.internal.misc.ConfigurationRender",
            "org.apache.felix.webconsole.internal.misc.ShellServlet",
            "org.apache.felix.webconsole.internal.obr.BundleRepositoryRender",
            "org.apache.felix.webconsole.internal.obr.InstallFromRepoAction",
            "org.apache.felix.webconsole.internal.obr.RefreshRepoAction",
            "org.apache.felix.webconsole.internal.system.GCAction",
            "org.apache.felix.webconsole.internal.system.VMStatPlugin"
        };
    private BundleContext bundleContext;
    private Logger log;
    private HttpService httpService;
    private ServiceRegistration configurationListener;
    private Map plugins = new HashMap();
    private Map labelMap = new HashMap();
    private Map operations = new HashMap();
    private Servlet defaultRender;
    private String defaultRenderName;
    private String webManagerRoot;
    // true if the OsgiManager is registered as a Servlet with the HttpService
    private boolean httpServletRegistered;
    // true if the resources have been registered with the HttpService
    private boolean httpResourcesRegistered;
    private Dictionary configuration;
    private Set enabledPlugins;
    public OsgiManager( BundleContext bundleContext )
    {
        this. = bundleContext;
        this. = new LoggerbundleContext );
        updateConfigurationnull );
        try
        {
            this. = ConfigurationListener.createthis );
        }
        catch ( Throwable t )
        {
            // might be caused by CM not available
        }
        // get at the HttpService first, this should initialize
        // the OSGi Manager and start the initial setup
         = new HttpServiceTrackerthis );
        .open();
    }
    public void dispose()
    {
        // now drop the HttpService and continue with further destroyals
        if (  != null )
        {
            .close();
             = null;
        }
        // stop listening for configuration
        if (  != null )
        {
            .unregister();
             = null;
        }
        if (  != null )
        {
            .dispose();
        }
        this. = null;
        this. = null;
    }
    //---------- Servlet API
    public void init()
    {
        // base class initialization not needed, since the GenericServlet.init
        // is an empty method
        // setup the included plugins
        ClassLoader classLoader = getClass().getClassLoader();
        for ( int i = 0; i < .i++ )
        {
            String pluginClassName = [i];
            try
            {
                Class pluginClass = classLoader.loadClasspluginClassName );
                Object plugin = pluginClass.newInstance();
                // check whether enabled by configuration
                if ( isPluginDisabledpluginClassNameplugin ) )
                {
                    .log( LogService.LOG_INFO, "Ignoring plugin " + pluginClassName + ": Disabled by configuration" );
                    continue;
                }
                if ( plugin instanceof OsgiManagerPlugin )
                {
                    ( ( OsgiManagerPlugin ) plugin ).activate );
                }
                if ( plugin instanceof AbstractWebConsolePlugin )
                {
                    AbstractWebConsolePlugin amp = ( AbstractWebConsolePlugin ) plugin;
                    bindServletamp.getLabel(), amp );
                }
                else
                {
                    if ( plugin instanceof Action )
                    {
                        bindOperation( ( Action ) plugin );
                    }
                    if ( plugin instanceof BrandingPlugin )
                    {
                        AbstractWebConsolePlugin.setBrandingPlugin((BrandingPluginplugin);
                    }
                }
            }
            catch ( Throwable t )
            {
                .log( LogService.LOG_INFO, "Failed to instantiate plugin " + pluginClassName + ". Reason: " + t );
            }
        }
        // start tracking external plugins after setting up our own plugins
         = new OperationServiceTrackerthis );
        .open();
         = new PluginServiceTrackerthis );
        .open();
         = new BrandingServiceTracker(this);
        .open();
    }
    public void serviceServletRequest reqServletResponse res ) throws ServletExceptionIOException
    {
        HttpServletRequest request = ( HttpServletRequest ) req;
        HttpServletResponse response = ( HttpServletResponse ) res;
        // handle the request action, terminate if done
        if ( this.handleActionrequestresponse ) )
        {
            return;
        }
        // check whether we are not at .../{webManagerRoot}
        if ( request.getPathInfo() == null || request.getPathInfo().equals"/" ) )
        {
            String path = request.getRequestURI();
            if ( !path.endsWith"/" ) )
            {
                path = path.concat"/" );
            }
            path = path.concat );
            response.sendRedirectpath );
            return;
        }
        String label = request.getPathInfo();
        int slash = label.indexOf"/", 1 );
        if ( slash < 2 )
        {
            slash = label.length();
        }
        label = label.substring( 1, slash );
        Servlet plugin = ( Servlet ) .getlabel );
        if ( plugin != null )
        {
            // the official request attributes
            req.setAttribute. );
            req.setAttribute.request.getContextPath() + request.getServletPath() );
            req.setAttribute.request.getContextPath() + request.getServletPath() + '/' + label);
            // deprecated request attributes
            req.setAttribute );
            req.setAttributerequest.getContextPath() + request.getServletPath() );
            plugin.servicereqres );
        }
        else
        {
            response.sendError. );
            return;
        }
    }
    public void destroy()
    {
        // base class destroy not needed, since the GenericServlet.destroy
        // is an empty method
        // stop listening for plugins
        if (  != null )
        {
            .close();
             = null;
        }
        if (  != null )
        {
            .close();
             = null;
        }
        if != null )
        {
            .close();
             = null;
        }
        // deactivate any remaining plugins
        for ( Iterator pi = .values().iterator(); pi.hasNext(); )
        {
            Object plugin = pi.next();
            if ( plugin instanceof OsgiManagerPlugin )
            {
                ( ( OsgiManagerPlugin ) plugin ).deactivate();
            }
        }
        // simply remove all operations, we should not be used anymore
        this..clear();
        this..clear();
        this..clear();
    }
    //---------- internal
    protected boolean handleActionHttpServletRequest reqHttpServletResponse resp ) throws IOExceptionServletException
    {
        // check action
        String actionName = AbstractWebConsolePlugin.getParameterreq. );
        if ( actionName != null )
        {
            Action action = ( Action ) this..getactionName );
            if ( action != null )
            {
                boolean redirect = true;
                try
                {
                    redirect = action.performActionreqresp );
                }
                catch ( IOException ioe )
                {
                    .log( LogService.LOG_WARNING, ioe.getMessage(), ioe );
                }
                catch ( ServletException se )
                {
                    .log( LogService.LOG_WARNING, se.getMessage(), se.getRootCause() );
                }
                // maybe overwrite redirect
                if ( .equals( AbstractWebConsolePlugin.getParameterreq,
                     ) ) )
                {
                    resp.setStatus. );
                    resp.setContentType"text/html" );
                    resp.getWriter().println"Ok" );
                    return true;
                }
                if ( redirect )
                {
                    String uri = req.getRequestURI();
                    // Object pars =
                    // req.getAttribute(Action.ATTR_REDIRECT_PARAMETERS);
                    // if (pars instanceof String) {
                    // uri += "?" + pars;
                    // }
                    resp.sendRedirecturi );
                }
                return true;
            }
        }
        return false;
    }
    BundleContext getBundleContext()
    {
        return ;
    }
    private static class HttpServiceTracker extends ServiceTracker
    {
        private final OsgiManager osgiManager;
        HttpServiceTrackerOsgiManager osgiManager )
        {
            superosgiManager.getBundleContext(), HttpService.class.getName(), null );
            this. = osgiManager;
        }
        public Object addingService( ServiceReference reference )
        {
            Object service = super.addingServicereference );
            if ( service instanceof HttpService )
            {
                .bindHttpService( ( HttpService ) service );
            }
            return service;
        }
        public void removedService( ServiceReference referenceObject service )
        {
            if ( service instanceof HttpService )
            {
                .unbindHttpService( ( HttpService ) service );
            }
            super.removedServicereferenceservice );
        }
    }
    private static class OperationServiceTracker extends ServiceTracker
    {
        private final OsgiManager osgiManager;
        OperationServiceTrackerOsgiManager osgiManager )
        {
            superosgiManager.getBundleContext(), .null );
            this. = osgiManager;
        }
        public Object addingService( ServiceReference reference )
        {
            Object operation = super.addingServicereference );
            if ( operation instanceof Action )
            {
                .bindOperation( ( Action ) operation );
            }
            return operation;
        }
        public void removedService( ServiceReference referenceObject service )
        {
            if ( service instanceof Action )
            {
                .bindOperation( ( Action ) service );
            }
            super.removedServicereferenceservice );
        }
    }
    private static class PluginServiceTracker extends ServiceTracker
    {
        private final OsgiManager osgiManager;
        PluginServiceTrackerOsgiManager osgiManager )
        {
            superosgiManager.getBundleContext(), .null );
            this. = osgiManager;
        }
        public Object addingService( ServiceReference reference )
        {
            Object label = reference.getProperty( . );
            if ( label instanceof String )
            {
                Object operation = super.addingServicereference );
                if ( operation instanceof Servlet )
                {
                    // wrap the servlet if it is not an AbstractWebConsolePlugin
                    // but has a title in the service properties
                    if ( !( operation instanceof AbstractWebConsolePlugin ) )
                    {
                        Object title = reference.getProperty( . );
                        if ( title instanceof String )
                        {
                            WebConsolePluginAdapter pluginAdapter = new WebConsolePluginAdapter( ( String ) label,
                                ( String ) title, ( Servlet ) operationreference );
                            // ensure the AbstractWebConsolePlugin is correctly setup
                            Bundle pluginBundle = reference.getBundle();
                            pluginAdapter.activatepluginBundle.getBundleContext() );
                            // now use this adapter as the operation
                            operation = pluginAdapter;
                        }
                    }
                    // TODO: check reference properties !!
                    .bindServlet( ( String ) label, ( Servlet ) operation );
                }
                return operation;
            }
            return null;
        }
        public void removedService( ServiceReference referenceObject service )
        {
            Object label = reference.getProperty( . );
            if ( label instanceof String )
            {
                // TODO: check reference properties !!
                .unbindServlet( ( String ) label );
                // check whether the service is a WebConsolePluginAdapter in
                // which case we have to deactivate it here (as we activated it
                // while adding the service
                if ( service instanceof WebConsolePluginAdapter )
                {
                    ( ( WebConsolePluginAdapter ) service ).deactivate();
                }
            }
            super.removedServicereferenceservice );
        }
    }
    private static class BrandingServiceTracker extends ServiceTracker
    {
        private final OsgiManager osgiManager;
        BrandingServiceTrackerOsgiManager osgiManager ){
            superosgiManager.getBundleContext(), BrandingPlugin.class.getName(), null );
            this. = osgiManager;
        }
        public Object addingService( ServiceReference reference ){
            Object plugin = super.addingServicereference );
            if ( plugin instanceof BrandingPlugin )
            {
                AbstractWebConsolePlugin.setBrandingPlugin((BrandingPluginplugin);
            }
            return plugin;
        }
        public void removedService( ServiceReference referenceObject service ){
            if ( service instanceof BrandingPlugin )
            {
                AbstractWebConsolePlugin.setBrandingPlugin(null);
            }
            super.removedServicereferenceservice );
        }
    }
    protected synchronized void bindHttpService( HttpService httpService )
    {
        // do not bind service, when we are already bound
        if ( this. != null )
        {
            .log( LogService.LOG_DEBUG,
                "bindHttpService: Already bound to an HTTP Service, ignoring further services" );
            return;
        }
        Dictionary config = getConfiguration();
        // get authentication details
        String realm = this.getPropertyconfig );
        String userId = this.getPropertyconfig );
        String password = this.getPropertyconfig );
        // register the servlet and resources
        try
        {
            HttpContext httpContext = new OsgiManagerHttpContexthttpServicerealmuserIdpassword );
            Dictionary servletConfig = toStringConfigconfig );
            // register this servlet and take note of this
            httpService.registerServlet( this.thisservletConfighttpContext );
             = true;
            // register resources and take of this
            httpService.registerResources( this. + "/res""/res"httpContext );
             = true;
        }
        catch ( Exception e )
        {
            .log( LogService.LOG_ERROR, "bindHttpService: Problem setting up"e );
        }
        this. = httpService;
    }
    protected synchronized void unbindHttpService( HttpService httpService )
    {
        if ( this. != httpService )
        {
            .log( LogService.LOG_DEBUG,
                "unbindHttpService: Ignoring unbind of an HttpService to which we are not registered" );
            return;
        }
        // drop the service reference
        this. = null;
        if (  )
        {
            try
            {
                httpService.unregister( this. + "/res" );
            }
            catch ( Throwable t )
            {
                .log( LogService.LOG_WARNING, "unbindHttpService: Failed unregistering Resources"t );
            }
             = false;
        }
        if (  )
        {
            try
            {
                httpService.unregister( this. );
            }
            catch ( Throwable t )
            {
                .log( LogService.LOG_WARNING, "unbindHttpService: Failed unregistering Servlet"t );
            }
             = false;
        }
    }
    protected void bindServletString labelServlet servlet )
    {
        try
        {
            servlet.initgetServletConfig() );
            .putlabelservlet );
            if ( servlet instanceof GenericServlet )
            {
                String title = ( ( GenericServlet ) servlet ).getServletName();
                if ( title != null )
                {
                    .putlabeltitle );
                }
            }
            if ( this. == null )
            {
                this. = servlet;
            }
            else if ( label.equalsthis. ) )
            {
                this. = servlet;
            }
        }
        catch ( ServletException se )
        {
            // TODO: log
        }
    }
    protected void unbindServletString label )
    {
        Servlet servlet = ( Servlet ) .removelabel );
        if ( servlet != null )
        {
            .removelabel );
            if ( this. == servlet )
            {
                if ( this..isEmpty() )
                {
                    this. = null;
                }
                else
                {
                    this. = ( Servlet ) .values().iterator().next();
                }
            }
            servlet.destroy();
        }
    }
    protected void bindOperationAction operation )
    {
        .putoperation.getName(), operation );
    }
    protected void unbindOperationAction operation )
    {
        .removeoperation.getName() );
    }
    private Dictionary getConfiguration()
    {
        return ;
    }
    synchronized void updateConfigurationDictionary config )
    {
        if ( config == null )
        {
            config = new Hashtable();
        }
         = config;
        if (  != null && .get ) != null )
        {
             = ( Servlet ) .get );
        }
        // get the web manager root path
         = this.getPropertyconfig );
        if ( !.startsWith"/" ) )
        {
             = "/" + ;
        }
        // get enabled plugins
        Object pluginValue = config.get );
        if ( pluginValue == null )
        {
             = null;
        }
        else if ( pluginValue.getClass().isArray() )
        {
            final Object[] names = ( Object[] ) pluginValue;
             = new HashSet();
            for ( int i = 0; i < names.lengthi++ )
            {
                .add( String.valueOfnames[i] ) );
            }
        }
        else if ( pluginValue instanceof Collection )
        {
             = new HashSet();
            .addAll( ( Collection ) pluginValue );
        }
        // might update http service registration
        HttpService httpService = this.;
        if ( httpService != null )
        {
            synchronized ( this )
            {
                unbindHttpServicehttpService );
                bindHttpServicehttpService );
            }
        }
    }


    
Returns the named property from the configuration. If the property does not exist, the default value def is returned.

Parameters:
config The properties from which to returned the named one
name The name of the property to return
def The default value if the named property does not exist
Returns:
The value of the named property as a string or def if the property does not exist
    private String getPropertyDictionary configString nameString def )
    {
        Object value = config.getname );
        if ( value instanceof String )
        {
            return ( String ) value;
        }
        if ( value == null )
        {
            return def;
        }
        return String.valueOfvalue );
    }


    
Returns true if the plugin is an AbstractWebConsolePlugin and a list of enabled plugins is configured but the plugin is not contained in that list.

This method is intended to be used only for plugins contained in the web console bundle itself, namely plugins listed in the .PLUGIN_CLASSES list.

    private boolean isPluginDisabledString pluginClassObject plugin )
    {
        return  != null && !.containspluginClass )
            && ( plugin instanceof AbstractWebConsolePlugin );
    }
    private Dictionary toStringConfigDictionary config )
    {
        Dictionary stringConfig = new Hashtable();
        for ( Enumeration ke = config.keys(); ke.hasMoreElements(); )
        {
            Object key = ke.nextElement();
            stringConfig.putkey.toString(), String.valueOfconfig.getkey ) ) );
        }
        return stringConfig;
    }
New to GrepCode? Check out our FAQ X