001    /**
002     *  Licensed to the Apache Software Foundation (ASF) under one or more
003     *  contributor license agreements.  See the NOTICE file distributed with
004     *  this work for additional information regarding copyright ownership.
005     *  The ASF licenses this file to You under the Apache License, Version 2.0
006     *  (the "License"); you may not use this file except in compliance with
007     *  the License.  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    package org.apache.geronimo.console.util;
018    
019    import java.io.File;
020    import java.util.Map;
021    import java.util.regex.Pattern;
022    
023    import javax.enterprise.deploy.spi.DeploymentManager;
024    import javax.enterprise.deploy.spi.exceptions.DeploymentManagerCreationException;
025    import javax.enterprise.deploy.spi.factories.DeploymentFactory;
026    import javax.naming.InitialContext;
027    import javax.naming.NamingException;
028    import javax.portlet.PortletRequest;
029    import javax.portlet.PortletSession;
030    import javax.portlet.RenderResponse;
031    import javax.security.auth.Subject;
032    import javax.security.auth.login.LoginException;
033    import javax.security.auth.spi.LoginModule;
034    import javax.servlet.http.HttpServletRequest;
035    import javax.servlet.http.HttpSession;
036    
037    import org.apache.commons.logging.Log;
038    import org.apache.commons.logging.LogFactory;
039    import org.apache.geronimo.deployment.plugin.factories.DeploymentFactoryWithKernel;
040    import org.apache.geronimo.gbean.AbstractName;
041    import org.apache.geronimo.gbean.GBeanData;
042    import org.apache.geronimo.kernel.Kernel;
043    import org.apache.geronimo.kernel.KernelRegistry;
044    import org.apache.geronimo.kernel.config.ConfigurationModuleType;
045    import org.apache.geronimo.kernel.proxy.GeronimoManagedBean;
046    import org.apache.geronimo.kernel.repository.Artifact;
047    import org.apache.geronimo.kernel.repository.Repository;
048    import org.apache.geronimo.management.J2EEDeployedObject;
049    import org.apache.geronimo.management.geronimo.J2EEDomain;
050    import org.apache.geronimo.management.geronimo.J2EEServer;
051    import org.apache.geronimo.management.geronimo.JCAAdminObject;
052    import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory;
053    import org.apache.geronimo.management.geronimo.JCAResource;
054    import org.apache.geronimo.management.geronimo.JMSBroker;
055    import org.apache.geronimo.management.geronimo.JMSConnector;
056    import org.apache.geronimo.management.geronimo.JMSManager;
057    import org.apache.geronimo.management.geronimo.JVM;
058    import org.apache.geronimo.management.geronimo.NetworkConnector;
059    import org.apache.geronimo.management.geronimo.ResourceAdapter;
060    import org.apache.geronimo.management.geronimo.ResourceAdapterModule;
061    import org.apache.geronimo.management.geronimo.WebAccessLog;
062    import org.apache.geronimo.management.geronimo.WebConnector;
063    import org.apache.geronimo.management.geronimo.WebContainer;
064    import org.apache.geronimo.management.geronimo.WebManager;
065    import org.apache.geronimo.system.logging.SystemLog;
066    
067    /**
068     * @version $Rev: 562301 $ $Date: 2007-08-02 20:28:32 -0400 (Thu, 02 Aug 2007) $
069     */
070    public class PortletManager {
071        private final static Log log = LogFactory.getLog(PortletManager.class);
072        // The following are currently static due to having only one server/JVM/etc. per Geronimo
073        private final static String HELPER_KEY = "org.apache.geronimo.console.ManagementHelper";
074        private final static String DOMAIN_KEY = "org.apache.geronimo.console.J2EEDomain";
075        private final static String SERVER_KEY = "org.apache.geronimo.console.J2EEServer";
076        private final static String JVM_KEY = "org.apache.geronimo.console.JVM";
077        private final static String SYSTEM_LOG_KEY = "org.apache.geronimo.console.SystemLog";
078        // The following may change based on the user's selections
079        // nothing yet
080    
081        private static ManagementHelper createHelper() {
082            Kernel kernel = getKernel();
083            return new KernelManagementHelper(kernel);
084        }
085    
086        private static Kernel getKernel() {
087            //todo: consider making this configurable; we could easily connect to a remote kernel if we wanted to
088            Kernel kernel = null;
089            try {
090                kernel = (Kernel) new InitialContext().lookup("java:comp/GeronimoKernel");
091            } catch (NamingException e) {
092    //            log.error("Unable to look up kernel in JNDI", e);
093            }
094            if (kernel == null) {
095                log.debug("Unable to find kernel in JNDI; using KernelRegistry instead");
096                kernel = KernelRegistry.getSingleKernel();
097            }
098            return kernel;
099        }
100    
101        public static DeploymentManager getDeploymentManager(PortletRequest request) {
102            Kernel kernel = getKernel();
103            DeploymentFactory factory = new DeploymentFactoryWithKernel(kernel);
104            try {
105                return factory.getDeploymentManager("deployer:geronimo:inVM", null, null);
106            } catch (DeploymentManagerCreationException e) {
107                log.error(e.getMessage(), e);
108                return null;
109            }
110        }
111    
112        public static ManagementHelper getManagementHelper(PortletRequest request) {
113            ManagementHelper helper = (ManagementHelper) request.getPortletSession(true).getAttribute(HELPER_KEY, PortletSession.APPLICATION_SCOPE);
114            if (helper == null) {
115                helper = createHelper();
116                request.getPortletSession().setAttribute(HELPER_KEY, helper, PortletSession.APPLICATION_SCOPE);
117            }
118            return helper;
119        }
120    
121        public static ManagementHelper getManagementHelper(HttpSession session) {
122            ManagementHelper helper = (ManagementHelper) session.getAttribute(HELPER_KEY);
123            if (helper == null) {
124                helper = createHelper();
125                session.setAttribute(HELPER_KEY, helper);
126            }
127            return helper;
128        }
129    
130        public static J2EEDomain getCurrentDomain(PortletRequest request) {
131            J2EEDomain domain = (J2EEDomain) request.getPortletSession(true).getAttribute(DOMAIN_KEY, PortletSession.APPLICATION_SCOPE);
132            if (domain == null) {
133                domain = getManagementHelper(request).getDomains()[0]; //todo: some day, select a domain
134                request.getPortletSession().setAttribute(DOMAIN_KEY, domain, PortletSession.APPLICATION_SCOPE);
135            }
136            return domain;
137    
138        }
139    
140        public static J2EEServer getCurrentServer(PortletRequest request) {
141            J2EEServer server = (J2EEServer) request.getPortletSession(true).getAttribute(SERVER_KEY, PortletSession.APPLICATION_SCOPE);
142            if (server == null) {
143                server = getCurrentDomain(request).getServerInstances()[0]; //todo: some day, select a server from the domain
144                request.getPortletSession().setAttribute(SERVER_KEY, server, PortletSession.APPLICATION_SCOPE);
145            } else {
146                // to do     handle "should not occur" error   - message?
147            }
148            return server;
149        }
150    
151        public static JVM getCurrentJVM(PortletRequest request) {
152            JVM jvm = (JVM) request.getPortletSession(true).getAttribute(JVM_KEY, PortletSession.APPLICATION_SCOPE);
153            if (jvm == null) {
154                ManagementHelper helper = getManagementHelper(request);
155                jvm = helper.getJavaVMs(getCurrentServer(request))[0]; //todo: some day, select a JVM from the server
156                request.getPortletSession().setAttribute(JVM_KEY, jvm, PortletSession.APPLICATION_SCOPE);
157            }
158            return jvm;
159        }
160    
161        public static void testLoginModule(PortletRequest request, LoginModule module, Map options) {
162            ManagementHelper helper = getManagementHelper(request);
163            helper.testLoginModule(getCurrentServer(request), module, options);
164        }
165    
166        public static Subject testLoginModule(PortletRequest request, LoginModule module, Map options, String username, String password) throws LoginException {
167            ManagementHelper helper = getManagementHelper(request);
168            return helper.testLoginModule(getCurrentServer(request), module, options, username, password);
169        }
170    
171        public static ResourceAdapterModule[] getOutboundRAModules(PortletRequest request, String iface) {
172            ManagementHelper helper = getManagementHelper(request);
173            return helper.getOutboundRAModules(getCurrentServer(request), iface);
174        }
175    
176        public static ResourceAdapterModule[] getOutboundRAModules(PortletRequest request, String[] iface) {
177            ManagementHelper helper = getManagementHelper(request);
178            return helper.getOutboundRAModules(getCurrentServer(request), iface);
179        }
180    
181        public static ResourceAdapterModule[] getAdminObjectModules(PortletRequest request, String[] ifaces) {
182            ManagementHelper helper = getManagementHelper(request);
183            return helper.getAdminObjectModules(getCurrentServer(request), ifaces);
184        }
185    
186        public static JCAManagedConnectionFactory[] getOutboundFactoriesOfType(PortletRequest request, String iface) {
187            ManagementHelper helper = getManagementHelper(request);
188            return helper.getOutboundFactories(getCurrentServer(request), iface);
189        }
190    
191        public static JCAManagedConnectionFactory[] getOutboundFactoriesForRA(PortletRequest request, AbstractName resourceAdapterModuleName) {
192            ManagementHelper helper = getManagementHelper(request);
193            return helper.getOutboundFactories((ResourceAdapterModule) helper.getObject(resourceAdapterModuleName));
194        }
195    
196        public static JCAManagedConnectionFactory[] getOutboundFactoriesForRA(PortletRequest request, AbstractName resourceAdapterModuleName, String iface) {
197            ManagementHelper helper = getManagementHelper(request);
198            return helper.getOutboundFactories((ResourceAdapterModule) helper.getObject(resourceAdapterModuleName), iface);
199        }
200    
201        public static JCAManagedConnectionFactory[] getOutboundFactoriesForRA(PortletRequest request, ResourceAdapterModule module) {
202            ManagementHelper helper = getManagementHelper(request);
203            return helper.getOutboundFactories(module);
204        }
205    
206        public static JCAManagedConnectionFactory[] getOutboundFactoriesForRA(PortletRequest request, ResourceAdapterModule module, String iface) {
207            ManagementHelper helper = getManagementHelper(request);
208            return helper.getOutboundFactories(module, iface);
209        }
210    
211        public static JCAManagedConnectionFactory[] getOutboundFactoriesForRA(PortletRequest request, ResourceAdapterModule module, String[] iface) {
212            ManagementHelper helper = getManagementHelper(request);
213            return helper.getOutboundFactories(module, iface);
214        }
215    
216        //todo: Create an interface for admin objects
217        public static JCAAdminObject[] getAdminObjectsForRA(PortletRequest request, ResourceAdapterModule module, String[] ifaces) {
218            ManagementHelper helper = getManagementHelper(request);
219            return helper.getAdminObjects(module, ifaces);
220        }
221    
222        public static WebManager[] getWebManagers(PortletRequest request) {
223            return getCurrentServer(request).getWebManagers();
224        }
225    
226        public static WebManager getWebManager(PortletRequest request, AbstractName managerName) {
227            ManagementHelper helper = getManagementHelper(request);
228            return (WebManager) helper.getObject(managerName);
229        }
230    
231    //    private static String[] namesToStrings(AbstractName[] names) {
232    //        String[] result = new String[names.length];
233    //        for (int i = 0; i < names.length; i++) {
234    //            AbstractName name = names[i];
235    //            result[i] = name.toURI().toString();
236    //        }
237    //        return result;
238    //    }
239    //
240    
241        public static WebAccessLog getWebAccessLog(PortletRequest request, AbstractName managerName, AbstractName containerName) {
242            ManagementHelper helper = getManagementHelper(request);
243            WebManager manager = (WebManager) helper.getObject(managerName);
244            return manager.getAccessLog((WebContainer) helper.getObject(containerName));
245        }
246    
247        public static WebContainer getWebContainer(PortletRequest request, AbstractName containerName) {
248            ManagementHelper helper = getManagementHelper(request);
249            return (WebContainer) helper.getObject(containerName);
250        }
251    
252        public static NetworkConnector[] getNetworkConnectors(PortletRequest request, AbstractName managerName) {
253            ManagementHelper helper = getManagementHelper(request);
254            WebManager manager = (WebManager) helper.getObject(managerName);
255            return manager.getConnectors();
256        }
257    
258        public static NetworkConnector[] getNetworkConnectors(PortletRequest request, AbstractName managerName, String protocol) {
259            ManagementHelper helper = getManagementHelper(request);
260            WebManager manager = (WebManager) helper.getObject(managerName);
261            return manager.getConnectors(protocol);
262        }
263    
264        public static NetworkConnector getNetworkConnector(PortletRequest request, AbstractName connectorName) {
265            ManagementHelper helper = getManagementHelper(request);
266            return (NetworkConnector) helper.getObject(connectorName);
267        }
268    
269        public static NetworkConnector[] getNetworkConnectorsForContainer(PortletRequest request, AbstractName managerName, AbstractName containerName, String protocol) {
270            ManagementHelper helper = getManagementHelper(request);
271            WebManager manager = (WebManager) helper.getObject(managerName);
272            return manager.getConnectorsForContainer(containerName, protocol);
273        }
274    
275        public static JMSBroker getJMSBroker(PortletRequest request, AbstractName brokerName) {
276            ManagementHelper helper = getManagementHelper(request);
277            return (JMSBroker) helper.getObject(brokerName);
278        }
279    
280        public static JMSConnector createJMSConnector(PortletRequest request, JMSManager manager, AbstractName containerName, String name, String protocol, String host, int port) {
281            return manager.addConnector(getJMSBroker(request, containerName), name, protocol, host, port);
282        }
283    
284        public static JMSConnector[] getJMSConnectors(PortletRequest request, AbstractName managerName) {
285            ManagementHelper helper = getManagementHelper(request);
286            JMSManager manager = (JMSManager) helper.getObject(managerName);
287            return (JMSConnector[]) manager.getConnectors();
288        }
289    
290        public static JMSConnector[] getJMSConnectors(PortletRequest request, AbstractName managerName, String protocol) {
291            ManagementHelper helper = getManagementHelper(request);
292            JMSManager manager = (JMSManager) helper.getObject(managerName);
293            return (JMSConnector[]) manager.getConnectors(protocol);
294        }
295    
296        public static JMSConnector[] getJMSConnectorsForContainer(PortletRequest request, AbstractName managerName, AbstractName brokerName) {
297            ManagementHelper helper = getManagementHelper(request);
298            JMSManager manager = (JMSManager) helper.getObject(managerName);
299            return (JMSConnector[]) manager.getConnectorsForContainer(brokerName);
300        }
301    
302        public static JMSConnector[] getJMSConnectorsForContainer(PortletRequest request, AbstractName managerName, AbstractName brokerName, String protocol) {
303            ManagementHelper helper = getManagementHelper(request);
304            JMSManager manager = (JMSManager) helper.getObject(managerName);
305            return (JMSConnector[]) manager.getConnectorsForContainer(brokerName, protocol);
306        }
307    
308        public static ResourceAdapter[] getResourceAdapters(PortletRequest request, ResourceAdapterModule module) {
309            ManagementHelper helper = getManagementHelper(request);
310            return helper.getResourceAdapters(module);
311        }
312    
313        public static JCAResource[] getJCAResources(PortletRequest request, ResourceAdapter adapter) {
314            ManagementHelper helper = getManagementHelper(request);
315            return helper.getRAResources(adapter);
316        }
317    
318        public static String getGBeanDescription(PortletRequest request, AbstractName objectName) {
319            ManagementHelper helper = getManagementHelper(request);
320            return helper.getGBeanDescription(objectName);
321        }
322    
323        public static SystemLog getCurrentSystemLog(PortletRequest request) {
324            SystemLog log = (SystemLog) request.getPortletSession(true).getAttribute(SYSTEM_LOG_KEY, PortletSession.APPLICATION_SCOPE);
325            if (log == null) {
326                ManagementHelper helper = getManagementHelper(request);
327                log = helper.getSystemLog(getCurrentJVM(request));
328                request.getPortletSession().setAttribute(SYSTEM_LOG_KEY, log, PortletSession.APPLICATION_SCOPE);
329            }
330            return log;
331        }
332    
333        public static GeronimoManagedBean[] getManagedBeans(PortletRequest request, Class intrface) {
334            ManagementHelper helper = getManagementHelper(request);
335            Object[] obs = helper.findByInterface(intrface);
336            GeronimoManagedBean[] results = new GeronimoManagedBean[obs.length];
337            for (int i = 0; i < results.length; i++) {
338                results[i] = (GeronimoManagedBean) obs[i];
339            }
340            return results;
341        }
342    
343        public static GeronimoManagedBean getManagedBean(PortletRequest request, AbstractName name) {
344            ManagementHelper helper = getManagementHelper(request);
345            return (GeronimoManagedBean) helper.getObject(name);
346        }
347    
348        public static Artifact getConfigurationFor(PortletRequest request, AbstractName objectName) {
349            ManagementHelper helper = getManagementHelper(request);
350            return helper.getConfigurationNameFor(objectName);
351        }
352    
353        public static AbstractName getNameFor(PortletRequest request, Object component) {
354            ManagementHelper helper = getManagementHelper(request);
355            return helper.getNameFor(component);
356        }
357    
358        public static File getRepositoryEntry(PortletRequest request, String repositoryURI) {
359            J2EEServer server = getCurrentServer(request);
360            Repository[] repos = server.getRepositories();
361            Artifact uri = Artifact.create(repositoryURI);
362            if (!uri.isResolved()) {
363                Artifact[] all = server.getConfigurationManager().getArtifactResolver().queryArtifacts(uri);
364                if (all.length == 0) {
365                    return null;
366                } else {
367                    uri = all[all.length - 1];
368                }
369            }
370            for (int i = 0; i < repos.length; i++) {
371                Repository repo = repos[i];
372                if (repo.contains(uri)) {
373                    return repo.getLocation(uri);
374                }
375            }
376            return null;
377        }
378    
379        public static J2EEDeployedObject getModule(PortletRequest request, Artifact configuration) {
380            ManagementHelper helper = getManagementHelper(request);
381            return helper.getModuleForConfiguration(configuration);
382        }
383    
384        public static ConfigurationData[] getConfigurations(PortletRequest request, ConfigurationModuleType type, boolean includeChildModules) {
385            ManagementHelper helper = getManagementHelper(request);
386            return helper.getConfigurations(type, includeChildModules);
387        }
388        
389        public static Object[] getGBeansImplementing(PortletRequest request, Class iface) {
390            ManagementHelper helper = getManagementHelper(request);
391            return helper.getGBeansImplementing(iface);
392        }    
393    
394        /**
395         * This methods adds a GBean to an existing configuration.
396         * @param request PortletRequest object to get hold of ManagementHelper
397         * @param configID  The configuration to add the GBean to.
398         * @param gbean     The data representing the GBean to add.
399         * @param start     If true, the GBean should be started as part of this call.
400         */
401        public static void addGBeanToConfiguration(PortletRequest request, Artifact configID, GBeanData gbean, boolean start) {
402            ManagementHelper helper = getManagementHelper(request);
403            helper.addGBeanToConfiguration(configID, gbean, start);
404        }
405    
406        /**
407         * Looks up the context prefix used by the portal, even if the thing running
408         * is in one of the portlets.  We're kind of hacking our way there, but hey,
409         * it beats hardcoding.
410         */
411        public static String getConsoleFrameworkServletPath(HttpServletRequest request) {
412            String contextPath;
413            Object response = request.getAttribute("javax.portlet.response");
414            if (response != null && response instanceof RenderResponse) { // request came from a portlet
415                String pathInfo = request.getPathInfo();
416                String portletPath = Pattern.compile("/").split(pathInfo)[1];
417                contextPath = ((RenderResponse) response).createRenderURL().toString();
418                contextPath = Pattern.compile("/" + portletPath).split(contextPath)[0];
419            } else { // request did not come from a portlet
420                contextPath = request.getContextPath();
421            }
422            return contextPath;
423        }
424    }