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.Map;
 
 
The PluginHolder class implements the maintenance and lazy access to web console plugin services.
 
 class PluginHolder implements ServiceListener
 {
 
     // The Web Console's bundle context to access the plugin services
     private final BundleContext bundleContext;
 
     // registered plugins (Map<String label, Plugin plugin>)
     private final Map plugins;
 
     // The servlet context used to initialize plugin services
     private ServletContext servletContext;
 
     // the label of the default plugin
     private String defaultPluginLabel;
 
 
     PluginHolderfinal BundleContext context )
     {
         this. = context;
         this. = new HashMap();
     }
 
 
     //---------- OsgiManager support API
 
    
Start using the plugin manager with registration as a service listener and getting references to all plugins already registered in the framework.
 
     void open()
     {
         try
         {
             .addServiceListenerthis"(" + . + "="
                 + . + ")" );
         }
         catch ( InvalidSyntaxException ise )
         {
             // not expected, thus fail hard
             throw new InternalError"Failed registering for Servlet service events: " + ise.getMessage() );
         }
 
         try
         {
             ServiceReference[] refs = .getServiceReferences.null );
             if ( refs != null )
            {
                for ( int i = 0; i < refs.lengthi++ )
                {
                    serviceAddedrefs[i] );
                }
            }
        }
        catch ( InvalidSyntaxException ise )
        {
            // not expected, thus fail hard
            throw new InternalError"Failed getting existing Servlet services: " + ise.getMessage() );
        }
    }


    
Stop using the plugin manager by removing as a service listener and releasing all held plugins, which includes ungetting and destroying any held plugin services.
    void close()
    {
        .removeServiceListenerthis );
        Plugin[] plugin = getPlugins();
        for ( int i = 0; i < plugin.lengthi++ )
        {
            plugin[i].dispose();
        }
        .clear();
         = null;
    }


    
Returns label of the default plugin

Returns:
label of the default plugin
    {
        return ;
    }


    
Sets the label of the default plugin

Parameters:
defaultPluginLabel
    void setDefaultPluginLabelString defaultPluginLabel )
    {
        this. = defaultPluginLabel;
    }
    void addInternalPluginfinal OsgiManager osgiManagerfinal String pluginClassNamefinal String label)
    {
        final Plugin plugin = new InternalPlugin(thisosgiManagerpluginClassNamelabel);
        addPluginlabelplugin );
    }

    
Adds an internal Web Console plugin

Parameters:
consolePlugin The internal Web Console plugin to add
    void addOsgiManagerPluginfinal AbstractWebConsolePlugin consolePlugin )
    {
        final String label = consolePlugin.getLabel();
        final Plugin plugin = new PluginthisconsolePluginlabel );
        addPluginlabelplugin );
    }


    
Remove the internal Web Console plugin registered under the given label

Parameters:
label The label of the Web Console internal plugin to remove
    void removeOsgiManagerPluginfinal String label )
    {
        removePluginlabel );
    }


    
Returns the plugin registered under the given label or null if none is registered under that label. If the label is null or empty, any registered plugin is returned or null if no plugin is registered

Parameters:
label The label of the plugin to return
Returns:
The plugin or null if no plugin is registered with the given label.
    AbstractWebConsolePlugin getPluginfinal String label )
    {
        AbstractWebConsolePlugin consolePlugin = null;
        if ( label != null && label.length() > 0 )
        {
            final Plugin plugin;
            synchronized (  )
            {
                plugin = ( Plugin ) .getlabel );
            }
            if ( plugin != null )
            {
                consolePlugin = plugin.getConsolePlugin();
            }
        }
        else
        {
            Plugin[] plugins = getPlugins();
            for ( int i = 0; i < plugins.length && consolePlugin == nulli++ )
            {
                consolePlugin = plugins[i].getConsolePlugin();
            }
        }
        return consolePlugin;
    }


    
Builds the map of labels to plugin titles to be stored as the felix.webconsole.labelMap request attribute. This map optionally localizes the plugin title using the providing bundle's resource bundle if the first character of the title is a percent sign (%). Titles not prefixed with a percent sign are added to the map unmodified.

The special entry felix.webconsole.labelMap is the flat, unstructured map of labels to titles which is used as the respective request attribute (see FELIX-3833).

Parameters:
resourceBundleManager The ResourceBundleManager providing localized titles
locale The locale to which the titles are to be localized
Returns:
The localized map of labels to titles
    Map getLocalizedLabelMapfinal ResourceBundleManager resourceBundleManagerfinal Locale localefinal String defaultCategory )
    {
        final Map map = new HashMap();
        final Map flatMap = new HashMap();
        Plugin[] plugins = getPlugins();
        for ( int i = 0; i < plugins.lengthi++ )
        {
            final Plugin plugin = plugins[i];
            if ( !plugin.isEnabled() )
            {
                continue;
            }
            // support only one level for now
            Map categoryMap = null;
            String category = plugin.getCategory();
            if ( category == null || category.trim().length() == 0 )
            {
                // FELIX-3798 configured default category
                category = defaultCategory;
            }
            // TODO: FELIX-3769; translate the Category
            categoryMap = findCategoryMapmapcategory );
            final String label = plugin.getLabel();
            String title = plugin.getTitle();
            if ( title.startsWith"%" ) )
            {
                try
                {
                    final ResourceBundle resourceBundle = resourceBundleManager.getResourceBundleplugin.getBundle(),
                        locale );
                    title = resourceBundle.getStringtitle.substring( 1 ) );
                }
                catch ( Throwable e )
                {
                    /* ignore missing resource - use default title */
                }
            }
            categoryMap.putlabeltitle );
            flatMap.putlabeltitle );
        }
        // flat map of labels to titles (FELIX-3833)
        map.put.flatMap );
        return map;
    }
    private Map findCategoryMapMap mapString categoryPath )
    {
        Map categoryMap = null;
        Map searchMap = map;
        String categories[] = categoryPath.split"/" );
        for ( int i = 0; i < categories.lengthi++ )
        {
            String categoryKey = "category." + categories[i];
            if ( searchMap.containsKeycategoryKey ) )
            {
                categoryMap = ( Map ) searchMap.getcategoryKey );
            }
            else
            {
                categoryMap = new HashMap();
                searchMap.putcategoryKeycategoryMap );
            }
            searchMap = categoryMap;
        }
        return categoryMap;
    }


    
Returns the bundle context of the Web Console itself.

Returns:
the bundle context of the Web Console itself.
    {
        return ;
    }


    
Sets the servlet context to be used to initialize plugin services

Parameters:
servletContext
    void setServletContextServletContext servletContext )
    {
        final Plugin[] plugin = getPlugins();
        if ( servletContext != null )
        {
            this. = servletContext;
            for ( int i = 0; i < plugin.lengthi++ )
            {
                try
                {
                    plugin[i].init();
                }
                catch ( ServletException se )
                {
                    // TODO: log !!
                }
            }
        }
        else
        {
            for ( int i = 0; i < plugin.lengthi++ )
            {
                try {
                    plugin[i].destroy();
                } catch (Throwable t) {
                    // TODO: log !!
                }
            }
            this. = null;
        }
    }


    
Returns the servlet context to be used to initialize plugin services

Returns:
the servlet context to be used to initialize plugin services
    {
        return ;
    }
    //---------- ServletListener

    
Called when plugin services are registered or unregistered (or modified, which is currently ignored)

    public void serviceChangedServiceEvent event )
    {
        switch ( event.getType() )
        {
            case .:
                // add service
                serviceAddedevent.getServiceReference() );
                break;
            case .:
                // remove service
                serviceRemovedevent.getServiceReference() );
                break;
            default:
                // update service
                break;
        }
    }
    private void serviceAddedfinal ServiceReference serviceReference )
    {
        final String label = getPropertyserviceReference. );
        if ( label != null )
        {
            addPluginlabelnew ServletPluginthisserviceReferencelabel ) );
        }
    }
    private void serviceRemovedfinal ServiceReference serviceReference )
    {
        final String label = getPropertyserviceReference. );
        if ( label != null )
        {
            removePluginlabel );
        }
    }
    private void addPluginfinal String labelfinal Plugin plugin )
    {
        synchronized (  )
        {
            .putlabelplugin );
        }
    }
    private void removePluginfinal String label )
    {
        final Plugin oldPlugin;
        synchronized (  )
        {
            oldPlugin = ( Plugin ) .removelabel );
        }
        if ( oldPlugin != null )
        {
            oldPlugin.dispose();
        }
    }
    private Plugin[] getPlugins()
    {
        synchronized (  )
        {
            return ( Plugin[] ) .values().toArraynew Plugin[.size()] );
        }
    }
    static String getPropertyfinal ServiceReference servicefinal String propertyName )
    {
        final Object property = service.getPropertypropertyName );
        if ( property instanceof String )
        {
            return ( String ) property;
        }
        return null;
    }
    private static class Plugin implements ServletConfig
    {
        private final PluginHolder holder;
        private final String label;
        private String title;
        private AbstractWebConsolePlugin consolePlugin;
        protected Pluginfinal PluginHolder holderfinal String label )
        {
            this. = holder;
            this. = label;
        }
        protected Pluginfinal PluginHolder holderfinal AbstractWebConsolePlugin pluginfinal String label )
        {
            thisholderlabel );
            if ( plugin == null )
            {
                throw new NullPointerException"plugin" );
            }
            this. = plugin;
        }
        void init() throws ServletException {
            if ( != null) {
                .initthis );
            }
        }
        void destroy()
        {
            if ( != null) {
                .destroy();
            }
        }

        
Cleans up this plugin when it is not used any longer. This means destroying the plugin servlet and, if it was registered as an OSGi service, ungetting the service.
        final void dispose()
        {
            if (  != null )
            {
                try
                {
                    .destroy();
                }
                catch ( Exception e )
                {
                    // TODO: handle
                }
                doUngetConsolePlugin );
                 = null;
            }
        }
        protected PluginHolder getHolder()
        {
            return ;
        }
        Bundle getBundle()
        {
            return getHolder().getBundleContext().getBundle();
        }
        final String getLabel()
        {
            return ;
        }
        protected void setTitleString title )
        {
            this. = title;
        }
        final String getTitle()
        {
            if (  == null )
            {
                final String title = doGetTitle();
                this. = ( title == null ) ? getLabel() : title;
            }
            return ;
        }
        protected String doGetTitle()
        {
            // get the service now
            final AbstractWebConsolePlugin consolePlugin = getConsolePlugin();
            // reset the title:
            // - null if the servlet cannot be loaded
            // - to the servlet's actual title if the servlet is loaded
            return ( consolePlugin != null ) ? consolePlugin.getTitle() : null;
        }
        // methods added to support categories
        final String getCategory() {
        	return doGetCategory();
        }
        protected String doGetCategory() {
        	// get the service now
            final AbstractWebConsolePlugin consolePlugin = getConsolePlugin();
            return ( consolePlugin != null ) ? consolePlugin.getCategory() : null;
        }
        {
            if (  == null )
            {
                final AbstractWebConsolePlugin consolePlugin = doGetConsolePlugin();
                if ( consolePlugin != null )
                {
                    try
                    {
                        this. = consolePlugin;
                        init();
                    }
                    catch ( ServletException se )
                    {
                        // TODO: log
                        this. = null;
                    }
                } else {
                    // TODO: log !!
                }
            }
            return ;
        }
        protected boolean isEnabled() {
            return true;
        }
        protected AbstractWebConsolePlugin doGetConsolePlugin()
        {
            return ;
        }
        protected void doUngetConsolePluginAbstractWebConsolePlugin consolePlugin )
        {
        }
        //---------- ServletConfig interface
        public String getInitParameterString name )
        {
            return null;
        }
        public Enumeration getInitParameterNames()
        {
            return new Enumeration()
            {
                public boolean hasMoreElements()
                {
                    return false;
                }
                public Object nextElement()
                {
                    throw new NoSuchElementException();
                }
            };
        }
        public ServletContext getServletContext()
        {
            return getHolder().getServletContext();
        }
        public String getServletName()
        {
            return getTitle();
        }
    }
    private static class ServletPlugin extends Plugin
    {
        private final ServiceReference serviceReference;
        ServletPluginfinal PluginHolder holderfinal ServiceReference serviceReferencefinal String label )
        {
            super(holderlabel);
            this. = serviceReference;
        }
        Bundle getBundle()
        {
            return .getBundle();
        }
        protected String doGetTitle() {
            // check service Reference
            final String title = getProperty. );
            if ( title != null )
            {
                return title;
            }
            // temporarily set the title to a non-null value to prevent
            // recursion issues if this method or the getServletName
            // method is called while the servlet is being acquired
            setTitle(getLabel());
            return super.doGetTitle();
        }
        // added to support categories
        protected String doGetCategory() {
            // check service Reference
            final String category = getProperty. );
            if ( category != null )
            {
                return category;
            }
            return super.doGetCategory();
        }
        protected AbstractWebConsolePlugin doGetConsolePlugin()
        {
            Object service = getHolder().getBundleContext().getService );
            if ( service instanceof Servlet )
            {
                final AbstractWebConsolePlugin servlet;
                if ( service instanceof AbstractWebConsolePlugin )
                {
                    servlet = ( AbstractWebConsolePlugin ) service;
                }
                else
                {
                    servlet = new WebConsolePluginAdaptergetLabel(), ( Servlet ) service );
                }
                return servlet;
            }
            return null;
        }
        protected void doUngetConsolePluginAbstractWebConsolePlugin consolePlugin )
        {
        }
        //---------- ServletConfig overwrite (based on ServletReference)
        public String getInitParameterString name )
        {
            Object property = .getPropertyname );
            if ( property != null && !property.getClass().isArray() )
            {
                return property.toString();
            }
            return super.getInitParametername );
        }
        public Enumeration getInitParameterNames()
        {
            final String[] keys = .getPropertyKeys();
            return new Enumeration()
            {
                int idx = 0;
                public boolean hasMoreElements()
                {
                    return  < keys.length;
                }
                public Object nextElement()
                {
                    if ( hasMoreElements() )
                    {
                        return keys[++];
                    }
                    throw new NoSuchElementException();
                }
            };
        }
    }
    static class InternalPlugin extends Plugin
    {
        final String pluginClassName;
        final OsgiManager osgiManager;
        boolean doLog = true;
        protected InternalPlugin(PluginHolder holderOsgiManager osgiManagerString pluginClassNameString label)
        {
            super(holderlabel);
            this. = osgiManager;
            this. = pluginClassName;
        }
        protected final boolean isEnabled() {
            // check if the plugin is enabled
            return !.isPluginDisabled();
        }
        protected AbstractWebConsolePlugin doGetConsolePlugin()
        {
            if (null == ) {
                if (!isEnabled())
                {
                    if ()
                    {
                        .log."Ignoring plugin " +  + ": Disabled by configuration" );
                         = false;
                    }
                    return null;
                }
                try
                {
                    Class pluginClass = getClass().getClassLoader().loadClass();
                     = (AbstractWebConsolePluginpluginClass.newInstance();
                    if ( instanceof OsgiManagerPlugin)
                    {
                        ((OsgiManagerPlugin).activate(getBundle().getBundleContext());
                    }
                     = true// reset logging if it succeeded
                }
                catch (Throwable t)
                {
                     = null// in case only activate has faled!
                    if ()
                    {
                        .log."Failed to instantiate plugin " + t );
                         = false;
                    }
                }
            }
            return ;
        }
        protected void doUngetConsolePlugin(AbstractWebConsolePlugin consolePlugin)
        {
            if (consolePlugin ==  = null;
            if (consolePlugin instanceof OsgiManagerPlugin)
            {
                ((OsgiManagerPluginconsolePlugin).deactivate();
            }
            super.doUngetConsolePlugin(consolePlugin);
        }
    }
New to GrepCode? Check out our FAQ X