KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > connectors > ConnectorServiceImpl


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.connectors;
25
26 import com.sun.logging.LogDomains;
27
28 import java.util.Iterator JavaDoc;
29 import java.util.Set JavaDoc;
30 import java.util.logging.*;
31
32 import com.sun.enterprise.*;
33 import com.sun.enterprise.admin.monitor.registry.MonitoredObjectType;
34 import com.sun.enterprise.admin.monitor.registry.MonitoringRegistry;
35 import com.sun.enterprise.config.*;
36 import com.sun.enterprise.connectors.util.*;
37 import com.sun.enterprise.connectors.work.monitor.ConnectorWorkMonitoringLevelListener;
38 import com.sun.enterprise.deployment.*;
39 import com.sun.enterprise.deployment.archivist.ApplicationArchivist;
40 import com.sun.enterprise.deployment.deploy.shared.FileArchive;
41 import com.sun.enterprise.resource.*;
42 import com.sun.enterprise.server.*;
43 import com.sun.enterprise.util.*;
44
45 import java.io.IOException JavaDoc;
46 import java.security.AccessController JavaDoc;
47 import java.security.PrivilegedAction JavaDoc;
48
49 import org.xml.sax.SAXParseException JavaDoc;
50
51
52 /**
53  * This is the base class for all the connector services. It defines the
54  * enviroment of execution (client or server), and holds the reference to
55  * connector runtime for inter service method invocations.
56  * @author Srikanth P
57  */

58
59
60 public class ConnectorServiceImpl implements ConnectorConstants {
61     static Logger _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
62      
63     protected static ConnectorRegistry _registry =
64                          ConnectorRegistry.getInstance();
65
66     protected static ConnectorRuntime _runtime = ConnectorRuntime.getRuntime();
67
68  
69     private boolean debug=true;
70     protected static int environment = CLIENT;
71
72     /**
73      * Default Constructor
74      */

75
76     public ConnectorServiceImpl() {
77     }
78
79     /** Initializes the execution environment. If the execution environment
80      * is appserv runtime it is set to ConnectorConstants.SERVER else
81      * it is set ConnectorConstants.CLIENT
82      * @param environment set to ConnectorConstants.SERVER if execution
83      * environment is appserv runtime else set to
84      * ConnectorConstants.CLIENT
85      */

86
87     public static void initialize(int environ) {
88         environment = environ;
89     }
90
91     /**
92      * Returns the execution environment.
93      * @return ConnectorConstants.SERVER if execution environment is
94      * appserv runtime
95      * else it returns ConnectorConstants.CLIENT
96      */

97
98     public static int getEnviron() {
99         return environment;
100     }
101
102     /**
103      * Returns the generated default poolName of JMS resources.
104      * @jndiName jndi of the resources for which pool is to be created,
105      * @return generated poolname
106      */

107
108     public String JavaDoc getDefaultPoolName(String JavaDoc jndiName) {
109         //This is called by the JMS Deployers alone
110
return jndiName;
111     }
112
113     /**
114      * Returns the generated default connection poolName for a
115      * connection definition.
116      * @moduleName rar module name
117      * @connectionDefName connection definition name
118      * @return generated connection poolname
119      */

120
121     public String JavaDoc getDefaultPoolName(String JavaDoc moduleName,
122                        String JavaDoc connectionDefName) {
123         return moduleName+POOLNAME_APPENDER+connectionDefName;
124     }
125
126     /**
127      * Returns the generated default connector resource for a
128      * connection definition.
129      * @moduleName rar module name
130      * @connectionDefName connection definition name
131      * @return generated default connector resource name
132      */

133     public String JavaDoc getDefaultResourceName(String JavaDoc moduleName,
134                        String JavaDoc connectionDefName) {
135         //Construct the default resource name as
136
// <JNDIName_of_RA>#<connectionDefnName>
137
String JavaDoc resourceJNDIName = ConnectorAdminServiceUtils.
138                     getReservePrefixedJNDINameForResource(moduleName);
139         return resourceJNDIName + RESOURCENAME_APPENDER + connectionDefName;
140     }
141
142     /** These two methods are NOP. They will be used for future
143      * enhancements.
144      */

145
146     public void create() throws ConnectorRuntimeException {
147
148     }
149
150     public void destroy() throws ConnectorRuntimeException {
151
152     }
153
154     /** Checks whether the executing environment is application server
155      * @return true if execution environment is server
156      * false if it is client
157      */

158
159     public static boolean isServer() {
160         if(getEnviron() == SERVER) {
161             return true;
162         } else {
163             return false;
164         }
165     }
166
167     /**
168      * Internal API to lazily load Connector/JDBC/JMS and other resources on
169      * first lookup. All dependent resources and related infrastructure are also
170      * loaded.
171      */

172     public boolean checkAndLoadResource(String JavaDoc resname) {
173         //Resolve actual JNDI name. Connector and JDBC connection Pools are
174
//internally reserve prefixed while binding in JNDI.
175
//The Connector backend OTOH uses the actual JNDI name for all checks.
176
//So unmap the transformation here before proceeding to load the resource
177
//and its dependents
178
resname = ConnectorAdminServiceUtils.getOriginalResourceName(resname);
179         _logger.fine("ConnectorServiceImpl :: checkAndLoadResource resolved to " +
180                 "load " + resname);
181
182         ResourcesUtil resutil = ResourcesUtil.getInstance();
183         DeferredResourceConfig defResConfig = resutil.getDeferredResourceConfig(
184                                         resname);
185         return loadResourcesAndItsRar(defResConfig);
186     }
187
188     public boolean checkAndLoadPoolResource(String JavaDoc poolName) {
189
190        ResourcesUtil resutil = ResourcesUtil.getInstance();
191        DeferredResourceConfig defResConfig = resutil.getDeferredPoolConfig(
192                                 poolName);
193        return loadResourcesAndItsRar(defResConfig);
194     }
195
196     public boolean loadResourcesAndItsRar(DeferredResourceConfig defResConfig) {
197        if(defResConfig != null) {
198            try {
199                loadDeferredResources(defResConfig.getResourceAdapterConfig());
200                String JavaDoc rarName = defResConfig.getRarName();
201                loadDeferredResourceAdapter(rarName);
202                final ConfigBean[] resToLoad = defResConfig.getResourcesToLoad();
203                AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
204                    public Object JavaDoc run() {
205                        try {
206                            loadDeferredResources(resToLoad);
207                        } catch(Exception JavaDoc ex) {
208                            _logger.log( Level.SEVERE,
209                                 "failed to load resources/ResourceAdapter");
210                            _logger.log(Level.SEVERE,"" ,ex);
211                        }
212                        return null;
213                    }
214                });
215            } catch(Exception JavaDoc ex) {
216                _logger.log(
217                   Level.SEVERE,"failed to load resources/ResourceAdapter");
218                _logger.log(Level.SEVERE,"" ,ex);
219                return false;
220            }
221            return true;
222        }
223        return false;
224     }
225
226     
227     public void loadDeferredResourceAdapter(String JavaDoc rarName)
228                             throws ConnectorRuntimeException
229     {
230        try {
231            ManagerFactory.getSAConnectorModulesManager().
232            loadOneSystemApp(rarName, true);
233        } catch (Exception JavaDoc e) {
234            ConnectorRuntimeException ce =
235            new ConnectorRuntimeException(e.getMessage());
236            ce.initCause(e);
237            throw ce;
238        }
239     }
240
241     public void loadDeferredResources(ConfigBean[] resourcesToLoad)
242                                      throws Exception JavaDoc
243     {
244         if(resourcesToLoad == null || resourcesToLoad.length == 0) {
245             return;
246         }
247         String JavaDoc resourceType = null;
248         ResourceDeployer deployer = null;
249         ResourcesUtil resourceUtil = ResourcesUtil.getInstance();
250         for(int i=0;i<resourcesToLoad.length;++i) {
251             if(resourcesToLoad[i] == null) {
252                 continue;
253             } else if (resourceUtil.isEnabled(resourcesToLoad[i])) {
254                 resourceType = resourceUtil.getResourceType(resourcesToLoad[i]);
255                 deployer = resourceUtil.getResourceDeployer(resourceType);
256                 if(deployer != null) {
257                     deployer.deployResource(resourcesToLoad[i]);
258                 }
259             }
260         }
261     }
262
263     public void ifSystemRarLoad(String JavaDoc rarName)
264                            throws ConnectorRuntimeException
265     {
266         ResourcesUtil resUtil = ResourcesUtil.getInstance();
267         if(resUtil.belongToSystemRar(rarName)){
268             loadDeferredResourceAdapter(rarName);
269         }
270     }
271
272     /**
273      * Check whether ClassLoader is permitted to access this resource adapter.
274      * If the RAR is deployed and is not a standalone RAR, then only ClassLoader
275      * that loader the archive should be able to access it. Otherwise everybody can
276      * access the RAR.
277      *
278      * @param rarName Resource adapter module name.
279      * @param loader <code>ClassLoader</code> to verify.
280      */

281     public boolean checkAccessibility(String JavaDoc rarName, ClassLoader JavaDoc loader) {
282         ActiveResourceAdapter ar = _registry.getActiveResourceAdapter(rarName);
283         if (ar != null && loader != null) { // If RA is deployed
284
ClassLoader JavaDoc rarLoader = ar.getClassLoader();
285         //If the RAR is not standalone.
286
if (rarLoader != null && (!(rarLoader instanceof ConnectorClassLoader))) {
287         ClassLoader JavaDoc parent = loader;
288         while (true) {
289             if (parent.equals(rarLoader)) {
290                         return true;
291             }
292
293                     final ClassLoader JavaDoc temp = parent;
294                     Object JavaDoc obj = AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
295                         public Object JavaDoc run() {
296                     return temp.getParent();
297                         }
298                     });
299
300                     if (obj == null) {
301                         break;
302                     } else {
303                         parent = (ClassLoader JavaDoc) obj;
304                     }
305                 }
306         // If no parent matches return false;
307
return false;
308         }
309     }
310     return true;
311     }
312
313     /**
314      * Obtains the connector Descriptor pertaining to rar.
315      * If ConnectorDescriptor is present in registry, it is obtained from
316      * registry and returned. Else it is explicitly read from directory
317      * where rar is exploded.
318      * @param rarName Name of the rar
319      * @return ConnectorDescriptor pertaining to rar.
320      */

321
322     public ConnectorDescriptor getConnectorDescriptor(String JavaDoc rarName)
323                    throws ConnectorRuntimeException
324     {
325         
326         if(rarName == null) {
327             return null;
328         }
329         ConnectorDescriptor desc = null;
330         desc = _registry.getDescriptor(rarName);
331         if(desc != null) {
332             return desc;
333         }
334         String JavaDoc moduleDir = null;
335         ResourcesUtil resUtil = ResourcesUtil.getInstance();
336
337         //If the RAR is embedded try loading the descriptor directly
338
//using the applicationarchivist
339
if (rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER) != -1){
340             try {
341                 desc = loadConnectorDescriptorForEmbeddedRAR(rarName);
342                 if (desc != null) return desc;
343             } catch (ConnectorRuntimeException e) {
344                 throw e;
345             }
346         }
347         
348         if(resUtil.belongToSystemRar(rarName)){
349             ResourceInstaller installer =
350                        Switch.getSwitch().getResourceInstaller();
351             moduleDir = installer.getSystemModuleLocation(rarName);
352         } else {
353             moduleDir = resUtil.getLocation(rarName);
354         }
355         if (moduleDir != null) {
356             desc = ConnectorDDTransformUtils.getConnectorDescriptor(moduleDir);
357         } else {
358             _logger.log(Level.SEVERE,
359                    "rardeployment.no_module_deployed", rarName);
360         }
361         return desc;
362     }
363     
364     private ConnectorDescriptor loadConnectorDescriptorForEmbeddedRAR(String JavaDoc rarName) throws ConnectorRuntimeException {
365         //If the RAR is embedded try loading the descriptor directly
366
//using the applicationarchivist
367
try {
368             String JavaDoc appName = rarName.substring(0, rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER));
369             String JavaDoc actualRarName = rarName.substring(rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER) + 1);
370             String JavaDoc appDeployLocation = ResourcesUtil.getInstance().getApplicationDeployLocation(appName);
371             
372             FileArchive in = new FileArchive();
373             in.open(appDeployLocation);
374             ApplicationArchivist archivist = new ApplicationArchivist();
375             Application application = (Application) archivist.open(in);
376             //get all RAR descriptors and try searching for this embedded RAR
377
Set JavaDoc s = application.getRarDescriptors();
378             for (Iterator JavaDoc iter = s.iterator(); iter.hasNext();) {
379                 ConnectorDescriptor element = (ConnectorDescriptor) iter.next();
380                 //Strip ".rar" from deployname before using it.
381
String JavaDoc rardescname = element.getDeployName().substring(
382                                 0, element.getDeployName().indexOf(".rar"));
383                 if(rardescname.equals(actualRarName)){
384                     return element;
385                 }
386             }
387         } catch (SAXParseException JavaDoc e) {
388             ConnectorRuntimeException crex = new ConnectorRuntimeException("" +
389                     "SAXParseException while trying to load connector descriptor for embedded RAR");
390             crex.initCause(e);
391             throw crex;
392         } catch (IOException JavaDoc e) {
393             ConnectorRuntimeException crex = new ConnectorRuntimeException("" +
394             "SAXParseException while trying to load connector descriptor for embedded RAR");
395             crex.initCause(e);
396             throw crex;
397         }
398         return null;
399         
400     }
401
402     /**
403      * Matching will be switched off in the pool, by default. This will be
404      * switched on if the connections with different resource principals reach the pool.
405      *
406      * @param poolName Name of the pool to switchOn matching.
407      * @param rarName Name of the resource adater.
408      */

409     public void switchOnMatching(String JavaDoc rarName, String JavaDoc poolName) {
410         // At present it is applicable to only JDBC resource adapters
411
// Later other resource adapters also become applicable.
412
if (rarName.equals(ConnectorRuntime.JDBCDATASOURCE_RA_NAME) ||
413             rarName.equals(ConnectorRuntime.JDBCCONNECTIONPOOLDATASOURCE_RA_NAME) ||
414             rarName.equals(ConnectorRuntime.JDBCXA_RA_NAME)) {
415            
416              PoolManager poolMgr = Switch.getSwitch().getPoolManager();
417              boolean result = poolMgr.switchOnMatching(poolName);
418              if (result == false) {
419                  try {
420                      _runtime.switchOnMatchingInJndi(poolName);
421                  } catch (ConnectorRuntimeException cre) {
422                      // This will never happen.
423
}
424              }
425         }
426              
427     }
428
429     /**
430      * Initialize the monitoring listeners for connection pools, work management
431      * and message end point factory related stats
432      */

433     public void initializeConnectorMonitoring() {
434         Switch.getSwitch().getPoolManager().initializeMonitoring();
435         initializeWorkMgmtAndEndPointMonitoring();
436     }
437
438     /**
439      * Initialize the monitoring listeners for connection pools, work management
440      * and message end point factory related stats
441      */

442     private void initializeWorkMgmtAndEndPointMonitoring() {
443         try {
444             final ConnectorWorkMonitoringLevelListener cwmll
445                         = new ConnectorWorkMonitoringLevelListener();
446             //@todo Do for Connector EPF Monitoring as well
447

448             AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
449                 public Object JavaDoc run() {
450                     ServerContext ctxt = ApplicationServer.getServerContext();
451                     if (ctxt != null) {
452                         MonitoringRegistry monitoringRegistry_
453                             = ctxt.getMonitoringRegistry();
454                         //@todo: for EFT level listeners
455
monitoringRegistry_.registerMonitoringLevelListener(cwmll,
456                                         MonitoredObjectType.CONNECTOR_WORKMGMT);
457                                         
458 /* monitoringRegistry_.registerMonitoringLevelListener(
459                                         ccpPoolMonitoringLevelListener_,
460                                         MonitoredObjectType.CONNECTOR_CONN_POOL );
461 */

462                 }
463                 return null;
464             }
465             });
466     
467             _logger.log( Level.FINE, "poolmon.init_monitoring_registry");
468         } catch(Exception JavaDoc e) {
469             _logger.log( Level.INFO, "poolmon.error_registering_listener",
470             e);
471         }
472     }
473 }
474
Popular Tags