FileDocCategorySizeDatePackage
JmsRaUtil.javaAPI DocGlassfish v2 API16070Fri May 04 22:34:26 BST 2007com.sun.enterprise.connectors.util

JmsRaUtil.java

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package com.sun.enterprise.connectors.util;

import com.sun.enterprise.config.serverbeans.*;
import com.sun.enterprise.config.*;
import com.sun.enterprise.server.*;
import com.sun.enterprise.deployment.*;
import com.sun.enterprise.server.*;
import com.sun.enterprise.connectors.*;
import com.sun.enterprise.connectors.system.*;
import com.sun.enterprise.connectors.inflow.*;
import com.sun.enterprise.util.zip.*;
import com.sun.logging.LogDomains;
import java.io.*;
import java.util.logging.*;
import java.util.jar.*;

/**
 * 
 * @author	
 */
public class JmsRaUtil {

    private final String MQ_RAR = "imqjmsra.rar";

    private final String SYSTEM_APP_DIR = 
        "lib" + File.separator + "install" + File.separator + "applications"; 

    private final String MQ_RAR_MANIFEST = 
        ConnectorConstants.DEFAULT_JMS_ADAPTER + File.separator + "META-INF" 
        + File.separator + "MANIFEST.MF";

    // Manifest version tag.
    private final String MANIFEST_TAG = "Implementation-Version";

    private static final String propName_reconnect_delay_in_seconds =
        "reconnect-delay-in-seconds";
    private static final String propName_reconnect_max_retries =
        "reconnect-max-retries";
    private static final String propName_reconnect_enabled =
        "reconnect-enabled";
    private static final int DEFAULT_RECONNECT_DELAY = 60;
    private static final int DEFAULT_RECONNECT_RETRIES = 60;

    private static final String propName_cmt_max_runtime_exceptions 
        = "cmt-max-runtime-exceptions";
    private static final int DEFAULT_CMT_MAX_RUNTIME_EXCEPTIONS = 1;
	
    private static final String ENABLE_AUTO_CLUSTERING = "com.sun.enterprise.connectors.system.enableAutoClustering";

    private int cmtMaxRuntimeExceptions = DEFAULT_CMT_MAX_RUNTIME_EXCEPTIONS;

    private int reconnectDelayInSeconds = DEFAULT_RECONNECT_DELAY;
    private int reconnectMaxRetries = DEFAULT_RECONNECT_RETRIES;
    private boolean reconnectEnabled = false;

    ServerContext sc = null;
    ConfigContext ctx = null;
    JmsService js = null;
    MQAddressList list = null;

    static Logger _mdblogger = LogDomains.getLogger(LogDomains.MDB_LOGGER);
    static Logger _rarlogger = LogDomains.getLogger(LogDomains.RSR_LOGGER);

    public JmsRaUtil() throws ConnectorRuntimeException {
        this(null);
    }

    public JmsRaUtil(JmsService js) throws ConnectorRuntimeException {
        try {
            if (js != null) {
	        this.js = js;
            } else {
	        sc = ApplicationServer.getServerContext();
	        ctx = sc.getConfigContext();
	        this.js = ServerBeansFactory.getJmsServiceBean(ctx);
            }
            list = new MQAddressList(this.js);
//            if (isClustered() && ! this.js.getType().equals(
//                ActiveJmsResourceAdapter.REMOTE)) {
//                list.setupForLocalCluster();
//            } else {
//                list.setup();
//            }
        } catch(ConfigException ce) {
            throw handleException(ce);
        }
    }

    public void setupAddressList() throws ConnectorRuntimeException{
      try {
	list.setup();
	} catch (Exception e) {
		throw handleException(e);
	}
    }

    public String getUrl() {
	try {	
            return list.toString();
	} catch (Exception e) {
	    return null;
	}
    }
    
    public static boolean isClustered() throws ConnectorRuntimeException {
        try {
              ConfigContext ctxt = ApplicationServer.getServerContext().getConfigContext();
              return (enableClustering() && 
		ServerHelper.isServerClustered(ctxt,
                ApplicationServer.getServerContext().getInstanceName())
		);
          } catch (Exception e) {
              throw handleException(e);
          }
     }

     private static boolean enableClustering() {
	 try {
		/* This flag disables the auto clustering functionality
		 * No MQ clusters will  be created with AS cluster if 
		 * this flag is set to false. Default is true.
		 */
		String enablecluster = System.getProperty(ENABLE_AUTO_CLUSTERING);
		_rarlogger.log(Level.FINE,"Sun MQ Auto cluster system property" + enablecluster);
              	if ((enablecluster != null) && 
			(enablecluster.trim().equals("false"))){
		_rarlogger.log(Level.FINE,"Disabling Sun MQ Auto Clustering");
       	         return false;
  	        }
	 }catch (Exception e) {
		;	
	 }
	_rarlogger.log(Level.FINE,"Enabling Sun MQ Auto Clustering");
	return true;
      }
  	
    public String getJMSServiceType(){
 	return this.js.getType();
    }

    public MQAddressList getUrlList() {
        return list;
    }

    public boolean getReconnectEnabled() {
        return js.isReconnectEnabled();
    }

    public String getReconnectInterval() {
        return js.getReconnectIntervalInSeconds();
    }

    public String getReconnectAttempts() { 
        return js.getReconnectAttempts();
    }

    public String getAddressListIterations() {
        return js.getAddresslistIterations();
    }

    public String getAddressListBehaviour() {
        return js.getAddresslistBehavior();
    }

    public void setMdbContainerProperties(){
        com.sun.enterprise.config.serverbeans.MdbContainer mdbc = null;
        try {
            com.sun.enterprise.server.ServerContext sc =
                com.sun.enterprise.server.ApplicationServer.getServerContext();

            mdbc = com.sun.enterprise.config.serverbeans.ServerBeansFactory.
                  getMdbContainerBean(sc.getConfigContext());

        } 
        catch (Exception e) {
            _mdblogger.log(Level.WARNING, "containers.mdb.config_exception", 
                        new Object[]{e.getMessage()});
            if (_mdblogger.isLoggable(Level.FINE)) {
                _mdblogger.log(Level.FINE, e.getClass().getName(), e);
            }
        }

        if (mdbc != null) {
            ElementProperty[] props = mdbc.getElementProperty();
            if (props != null) {
                for (int i = 0; i < props.length; i++) {
                    ElementProperty p = props[i];
                    if (p == null) continue;
                    String name = p.getName();
                    if (name == null) continue;
                    try {
                        if (name.equals(propName_reconnect_enabled)) {
                            if (p.getValue() == null) continue;
                            reconnectEnabled = 
                                Boolean.valueOf(p.getValue()).booleanValue();
                        }
                        else if (name.equals
                                 (propName_reconnect_delay_in_seconds)) {
                            try {
                                reconnectDelayInSeconds = 
                                    Integer.parseInt(p.getValue());
                            } catch (Exception e) {
                                _mdblogger.log(Level.WARNING, 
                                    "containers.mdb.config_exception",
                                    new Object[]{e.getMessage()});
                            }
                        }
                        else if (name.equals(propName_reconnect_max_retries)) {
                            try {
                                reconnectMaxRetries = 
                                    Integer.parseInt(p.getValue());
                            } catch (Exception e) {
                                _mdblogger.log(Level.WARNING, 
                                    "containers.mdb.config_exception",
                                    new Object[]{e.getMessage()});
                            }
                        }
                        else if (name.equals
                                 (propName_cmt_max_runtime_exceptions)) {
                            try {
                                cmtMaxRuntimeExceptions = 
                                    Integer.parseInt(p.getValue());
                            } catch (Exception e) {
                                _mdblogger.log(Level.WARNING,
                                    "containers.mdb.config_exception",
                                    new Object[]{e.getMessage()});
                            }
                        }
                    } catch (Exception e) {
                        _mdblogger.log(Level.WARNING, 
                                    "containers.mdb.config_exception", 
                                    new Object[]{e.getMessage()});
                        if (_mdblogger.isLoggable(Level.FINE)) {
                            _mdblogger.log(Level.FINE, e.getClass().getName(), e);
                        }
                    }
                }
            }
        }
        if (reconnectDelayInSeconds < 0) {
            reconnectDelayInSeconds = DEFAULT_RECONNECT_DELAY;
        }
        if (reconnectMaxRetries < 0) {
            reconnectMaxRetries = DEFAULT_RECONNECT_RETRIES;
        }
        if (_mdblogger.isLoggable(Level.FINE)) {
            _mdblogger.log(Level.FINE, 
                propName_reconnect_delay_in_seconds+"="+
                reconnectDelayInSeconds +", "+
                propName_reconnect_max_retries+ "="+reconnectMaxRetries + ", "+
                propName_reconnect_enabled+"="+reconnectEnabled);
        }

        //Now set all these properties in the active resource adapter
        MdbContainerProps.setReconnectDelay(reconnectDelayInSeconds);
        MdbContainerProps.setReconnectMaxRetries(reconnectMaxRetries);
        MdbContainerProps.setReconnectEnabled(reconnectEnabled);
        MdbContainerProps.setMaxRuntimeExceptions(cmtMaxRuntimeExceptions);

    }

    public void configureDescriptor(ConnectorDescriptor cd) {

        Object[] envProps = cd.getConfigProperties().toArray();
	
        for (int i = 0; i < envProps.length; i++) {
            EnvironmentProperty envProp = (EnvironmentProperty) envProps[i];
            String name = envProp.getName();
	    if (!name.equals("ConnectionURL")) {
	        continue;
	    }
            String userValue = getUrl();
            if (userValue != null) {
                cd.removeConfigProperty(envProp);
                cd.addConfigProperty(new EnvironmentProperty(
                              name, userValue, userValue, envProp.getType()));
            }

        }

    }

    /**
     * Obtains the Implementation-Version from the MQ Client libraries
     * that are deployed in the application server and in MQ installation
     * directory.
     */
    public void upgradeIfNecessary() {

        String installedMqVersion = null;
        String deployedMqVersion = null;

        try {
           installedMqVersion = getInstalledMqVersion();
           _rarlogger.log(Level.FINE,"installedMQVersion :: " + installedMqVersion);
           deployedMqVersion =  getDeployedMqVersion();
           _rarlogger.log(Level.FINE,"deployedMQVersion :: " + deployedMqVersion);
        }catch (Exception e) {
	    return;
        }

        String deployed_dir = 
           java.lang. System.getProperty(Constants.INSTALL_ROOT) 
           + File.separator + SYSTEM_APP_DIR + File.separator 
           + ConnectorConstants.DEFAULT_JMS_ADAPTER;

        // If the Manifest entry has different versions, then attempt to 
        // explode the MQ resource adapter.
        if (!installedMqVersion.equals(deployedMqVersion)) {
           try {
               _rarlogger.log(Level.INFO, "jmsra.upgrade_started" );
	       ZipFile rarFile = new ZipFile(java.lang.System.getProperty
                                 (Constants.INSTALL_IMQ_LIB) + 
                                 File.separator + MQ_RAR, deployed_dir);
               rarFile.explode();
               _rarlogger.log(Level.INFO, "jmsra.upgrade_completed");
	   } catch(ZipFileException ze) {
               _rarlogger.log(Level.SEVERE,"jmsra.upgrade_failed",ze.getMessage());
           }
        }

    }

    private String getInstalledMqVersion() throws Exception {
       String ver = null;
       // Full path of installed Mq Client library
       String installed_dir = 
           java.lang.System.getProperty(Constants.INSTALL_IMQ_LIB);
       String jarFile = installed_dir + File.separator + MQ_RAR;
       _rarlogger.log(Level.FINE,"Installed MQ JAR " + jarFile);
	JarFile jFile = null;	
       try {
	   if ((new File(jarFile)).exists()) {
		/* This is for a file based install
		 * RAR has to be present in this location 
		 * ASHOME/imq/lib
		 */
		jFile = new JarFile(jarFile);
	   } else {
		/* This is for a package based install
		 * RAR has to be present in this location 
		 * /usr/lib
		 */
		jFile = new JarFile(installed_dir + File.separator + ".." + File.separator + MQ_RAR);
	   }
           Manifest mf = jFile.getManifest();
           ver = mf.getMainAttributes().getValue(MANIFEST_TAG);
           return ver;
       } catch (Exception e) {
           _rarlogger.log(Level.WARNING, "jmsra.upgrade_check_failed", 
                       e.getMessage() + ":" + jarFile );
           throw e;
       }
    }

    private String getDeployedMqVersion() throws Exception {
       String ver = null;
        // Full path of Mq client library that is deployed in appserver.
       String deployed_dir = 
           java.lang.System.getProperty(Constants.INSTALL_ROOT) 
           + File.separator + SYSTEM_APP_DIR; 
       String manifestFile = deployed_dir + File.separator +
                             MQ_RAR_MANIFEST; 
       _rarlogger.log(Level.FINE,"Deployed MQ version Manifest file" + manifestFile);
       try {
           Manifest mf = new Manifest(new FileInputStream(manifestFile));
           ver = mf.getMainAttributes().getValue(MANIFEST_TAG);
           return ver;
       } catch (Exception e) {
           _rarlogger.log(Level.WARNING, "jmsra.upgrade_check_failed", 
                       e.getMessage() + ":" + manifestFile );
           throw e;
       }
   }

   private static ConnectorRuntimeException handleException(Exception e) {
        ConnectorRuntimeException cre =
             new ConnectorRuntimeException(e.getMessage());
        cre.initCause(e);
        return cre;
    }
}