alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.tomcat5;

import java.io.File;
import java.io.InputStream;
import java.util.Locale;
import org.openide.filesystems.*;
import java.util.Enumeration;

import javax.enterprise.deploy.model.DeployableObject;
import javax.enterprise.deploy.shared.DConfigBeanVersionType;
import javax.enterprise.deploy.shared.ModuleType;
import javax.enterprise.deploy.spi.DeploymentConfiguration;
import javax.enterprise.deploy.spi.DeploymentManager;
import javax.enterprise.deploy.spi.Target;
import javax.enterprise.deploy.spi.TargetModuleID;
import javax.enterprise.deploy.spi.exceptions.DConfigBeanVersionUnsupportedException;
import javax.enterprise.deploy.spi.exceptions.InvalidModuleException;
import javax.enterprise.deploy.spi.exceptions.TargetException;
import javax.enterprise.deploy.spi.status.ProgressObject;
import org.openide.ErrorManager;
import org.openide.modules.InstalledFileLocator;

import org.netbeans.modules.j2ee.deployment.plugins.api.*;

import org.w3c.dom.Document;
import org.xml.sax.*;

import java.io.*;

import org.openide.xml.XMLUtil;

import org.netbeans.modules.tomcat5.config.*;
import org.netbeans.modules.tomcat5.ide.StartTomcat;
import org.netbeans.modules.tomcat5.util.TomcatInstallUtil;
import org.netbeans.modules.tomcat5.nodes.DebuggingTypeEditor;
import org.netbeans.modules.tomcat5.nodes.TomcatWebModule;

import org.openide.util.NbBundle;

import org.netbeans.api.debugger.*;
import org.netbeans.api.debugger.jpda.*;

import org.openide.util.Lookup;

import org.netbeans.modules.tomcat5.util.*;
import org.openide.NotifyDescriptor;
import org.openide.DialogDisplayer;

/** DeploymentManager that can deploy to 
 * Tomcat 5 using manager application.
 *
 * @author  Radim Kubacki
 */
public class TomcatManager implements DeploymentManager {

    /** Enum value for get*Modules methods. */
    static final int ENUM_AVAILABLE = 0;
    
    /** Enum value for get*Modules methods. */
    static final int ENUM_RUNNING = 1;
    
    /** Enum value for get*Modules methods. */
    static final int ENUM_NONRUNNING = 2;
    
    /** server.xml check timestamp */
    public static final String TIMESTAMP = "timestamp";

    /** admin port property */
    public static final String ADMIN_PORT = "admin_port";

    /** debugger port property */
    public static final String DEBUG_PORT = "debugger_port";
    
    /** http server port property */
    public static final String SERVER_PORT = "server_port";

    public static final String HOST = "host";
    
    /** http server port property */
    public static final String CLASSIC = "classic";

    /** http server port property */
    public static final String DEBUG_TYPE = "debug_type";

    /** shared memory property */
    public static final String SHARED_MEMORY = "shared_memory";

    /** default value for property classic */
    public static final Boolean DEFAULT_CLASSIC = Boolean.FALSE;

    /** default value for property debugger port */
    public static final Integer DEFAULT_DEBUG_PORT = new Integer(11555);
    
    /** default value for property server port */
    public static final Integer DEFAULT_SERVER_PORT = new Integer(8080);

    /** default value for property admin port */
    public static final Integer DEFAULT_ADMIN_PORT = new Integer(8005);

    /** default value for property debugging type*/
    public static final String DEFAULT_DEBUG_TYPE_UNIX = 
        NbBundle.getMessage (DebuggingTypeEditor.class, "SEL_debuggingType_socket");

    /** default value for property debugging type*/
    public static final String DEFAULT_DEBUG_TYPE_WINDOWS = 
        NbBundle.getMessage (DebuggingTypeEditor.class, "SEL_debuggingType_shared");

    /** default value for property shared memory*/
    public static final String DEFAULT_SHARED_MEMORY = NbBundle.getMessage (TomcatManager.class, "LBL_Tomcat_shared_memory_id");

    /** path to server xml */
    public static final String SERVERXML_PATH = File.separator + "conf" + File.separator + "server.xml";  // NOI18N
    
    /** path to default web.xml */
    public static final String WEBXML_PATH = File.separator + "conf" + File.separator + "web.xml";  // NOI18N
    
    /** some bundled tomcat settings are stored here */
    private static final String BUNDLED_TOMCAT_SETTING = "J2EE/BundledTomcat/Setting"; // NOI18N
    
    /** Tomcat specific Instance property - if this property exists and is set 
       to true web module's context log will be opened on run. */
    private static final String OPEN_CONTEXT_LOG_ON_RUN = "openContextLogOnRun";    

    /** Manager state. */
    private boolean connected;
    
    /** uri of this DeploymentManager. */
    private String uri;
    
    /** Username used for connecting. */
    private String username;
    /** Password used for connecting. */
    private String password;
    
    /** CATALINA_HOME of disconnected TomcatManager. */
    private String catalinaHome;
    /** CATALINA_BASE of disconnected TomcatManager. */
    private String catalinaBase;
    
    private FileObject catalinaBaseDir;
    
    private StartTomcat sTomcat;
    
    private Server root = null;
    
    /** Easier access to some server.xml settings. */
    private TomcatManagerConfig tomcatManagerConfig;
    
    /** LogManager manages all context and shared context logs for this TomcatManager. */
    private LogManager logManager = new LogManager(this);

    /** Creates an instance of connected TomcatManager
     * @param conn true to create connected manager
     * @param uri URI for DeploymentManager
     * @param uname username
     * @param passwd password
     */
    public TomcatManager (boolean conn, String uri, String uname, String passwd) {
        if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
            TomcatFactory.getEM ().log ("Creating connected TomcatManager uri="+uri+", uname="+uname); //NOI18N
        }
        this.connected = conn;
        sTomcat = null;
        
        // parse home and base attrs
        final String home = "home=";
        final String base = ":base=";
        final String uriString = "http://";  // NOI18N
        int uriOffset = uri.indexOf (uriString);
        int homeOffset = uri.indexOf (home) + home.length ();
        int baseOffset = uri.indexOf (base, homeOffset);
        if (homeOffset >= home.length ()) {
            int homeEnd = baseOffset > 0 ? baseOffset : (uriOffset > 0 ? uriOffset - 1 : uri.length ());
            int baseEnd = uriOffset > 0 ? uriOffset - 1 : uri.length ();
            catalinaHome= uri.substring (homeOffset, homeEnd);
            if (baseOffset > 0) {
                catalinaBase = uri.substring (baseOffset + base.length (), baseEnd);
            }
            // Bundled Tomcat home and base dirs can be specified as attributes
            // specified in BUNDLED_TOMCAT_SETTING file. Tomcat manager URL can 
            // then look like "tomcat:home=$bundled_home:base=$bundled_base" and
            // therefore remains valid even if Tomcat version changes. (issue# 40659)
            if (catalinaHome.length() > 0 && catalinaHome.charAt(0) == '$') {
                FileSystem fs = Repository.getDefault().getDefaultFileSystem();
                FileObject fo = fs.findResource(BUNDLED_TOMCAT_SETTING);
                if (fo != null) {
                    catalinaHome = fo.getAttribute(catalinaHome.substring(1)).toString();
                    if (catalinaBase != null && catalinaBase.length() > 0 
                        && catalinaBase.charAt(0) == '$') {
                        catalinaBase = fo.getAttribute(catalinaBase.substring(1)).toString();
                    }
                }
            }
        }
        
        //parse the old format for backward compatibility
        if (uriOffset > 0) {
            String theUri = uri.substring (uriOffset + uriString.length ());
            int portIndex = theUri.indexOf (':');
            String host = theUri.substring (0, portIndex - 1);
            setHost (host);
            //System.out.println("host:"+host);
            int portEnd = theUri.indexOf ('/');
            portEnd = portEnd > 0 ? portEnd : theUri.length ();
            String port = theUri.substring (portIndex, portEnd - 1);
            //System.out.println("port:"+port);
            try {
                setServerPort (Integer.valueOf (port));
            } catch (NumberFormatException nef) {
                org.openide.ErrorManager.getDefault ().log (nef.getLocalizedMessage ());
            }
        }
        this.uri = uri;
        username = uname;
        password = passwd;
        tomcatManagerConfig = new TomcatManagerConfig(getCatalinaDir() + SERVERXML_PATH);
    }

    public InstanceProperties getInstanceProperties() {
        return InstanceProperties.getInstanceProperties(TomcatFactory.tomcatUriPrefix + getUri());
    }
    
    /** Creates an instance of disconnected TomcatManager * /
    public TomcatManager (String catHome, String catBase) {
        if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
            TomcatFactory.getEM ().log ("Creating discconnected TomcatManager home="+catHome+", base="+catBase);
        }
        this.connected = false;
        this.catalinaHome = catHome;
        this.catalinaBase = catBase;
    }
     */
    
    /**
     * Returns true if this admin server is running.
     */
    public boolean isRunning() {
        return URLWait.waitForStartup (this, 1000);
    }
    
    /** Returns identifier of TomcatManager. This is not a real URI!
     * @return URI including home and base specification
     */
    public String getUri () {
        return uri;
    }
    
    /** Returns URI of TomcatManager (manager application).
     * @return URI without home and base specification
     */
    public String getPlainUri () {
        return "http://" + getHost () + ":" + getServerPort () + "/manager/"; //NOI18N
    }
    
    /** Returns URI of TomcatManager.
     * @return URI without home and base specification
     */
    public String getServerUri () {
        return "http://" + getHost () + ":" + getServerPort (); //NOI18N
    }
    
    /** Returns catalinaHome.
     * @return catalinaHome or null when not specified.
     */
    public String getCatalinaHome () {
        return catalinaHome;
    }
    
    /** Returns catalinaBase.
     * @return catalinaBase or null when not specified.
     */
    public String getCatalinaBase () {
        return catalinaBase;
    }
    
    /** Returns catalinaHome directory.
     * @return catalinaHome or null when not specified.
     */
    public File getCatalinaHomeDir () {
        if (catalinaHome == null) {
            return null;
        }
        File homeDir = new File (catalinaHome);
        if (!homeDir.isAbsolute ()) {
            InstalledFileLocator ifl = InstalledFileLocator.getDefault ();
            homeDir = ifl.locate (catalinaHome, null, false);
        }
        return homeDir;
    }
    
    /** Returns catalinaBase directory.
     * @return catalinaBase or null when not specified.
     */
    public File getCatalinaBaseDir () {
        if (catalinaBase == null) {
            return null;
        }
        File baseDir = new File (catalinaBase);
        if (!baseDir.isAbsolute ()) {
            InstalledFileLocator ifl = InstalledFileLocator.getDefault ();
            baseDir = ifl.locate (catalinaBase, null, false);
            if (baseDir == null) {
                baseDir = new File(System.getProperty("netbeans.user")+System.getProperty("file.separator")+catalinaBase);   // NOI18N
            }
        }
        return baseDir;
    }
    
    /**
     * Returns catalina directory.
     * @return catalinaBase directory, if it does not exist return catalinaHome directory,
     * null otherwise.
     */
    public File getCatalinaDir() {
        File catalinaDir = getCatalinaBaseDir();
        if (catalinaDir == null) catalinaDir = getCatalinaHomeDir();
        return catalinaDir;        
    }

    /**
     * Return path to catalina work directory, which is used to store generated 
     * sources and classes from JSPs.
     *
     * @return path to catalina work directory.
     */
    public String getCatalinaWork() {
        String engineName = tomcatManagerConfig.getEngineElement().getAttributeValue("name"); //NOI18N
        String hostName = tomcatManagerConfig.getHostElement().getAttributeValue("name"); //NOI18N
        StringBuffer catWork = new StringBuffer(getCatalinaDir().getAbsolutePath());
        catWork.append("/work/").append(engineName).append("/").append(hostName); //NOI18N
        return catWork.toString(); 
    }
    
    public FileObject getCatalinaBaseFileObject() {
        if (catalinaBaseDir!=null) return catalinaBaseDir;
        File baseDir = getCatalinaBaseDir();
        if (baseDir==null) baseDir = getCatalinaHomeDir();
        if (!baseDir.exists()) createBaseDir(baseDir,getCatalinaHomeDir());
        if (baseDir==null) return null;
        catalinaBaseDir = FileUtil.toFileObject(baseDir);
        if (catalinaBaseDir==null) {
            // try to refresh parent FileObject
            File parentDir = baseDir.getParentFile();
            if (parentDir != null) {
                FileObject parentFileObject = FileUtil.toFileObject(parentDir);
                if (parentFileObject != null) {
                    parentFileObject.refresh();
                    catalinaBaseDir = FileUtil.toFileObject(baseDir);
                }
            }
        }
        return catalinaBaseDir;
    }
    
    public StartTomcat getStartTomcat(){
        return sTomcat;
    }
    
    public void setStartTomcat (StartTomcat st){
        sTomcat = st;
    }
    
    /**
     * Returns true if this server is started in debug mode AND debugger is attached to it.
     * Doesn't matter whether the thread are suspended or not.
     */
    public boolean isDebugged() {
        
        ServerDebugInfo sdi = null;

        Session[] sessions = DebuggerManager.getDebuggerManager().getSessions();

        try {
            sdi = getStartTomcat().getDebugInfo(null);
        } catch (Exception e) {
            // don't care - just a try
        }

        if (sdi == null) {
            ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DebuggerInfo cannot be found for: " + this.toString());
        }

        for (int i=0; i < sessions.length; i++) {
            Session s = sessions[i];
            if (s != null) {
                Object o = s.lookupFirst(null, AttachingDICookie.class);
                if (o != null) {
                    AttachingDICookie attCookie = (AttachingDICookie)o;
                    if (sdi.getTransport().equals(ServerDebugInfo.TRANSPORT_SHMEM)) {
                        if (attCookie.getSharedMemoryName().equalsIgnoreCase(sdi.getShmemName())) {
                            return true;
                        }
                    } else {
                        if (attCookie.getHostName().equalsIgnoreCase(sdi.getHost())) {
                            if (attCookie.getPortNumber() == sdi.getPort()) {
                                return true;
                            }
                        }
                    }
                }
            }
        }

        return false;
    }
        
    /**
     * Returns true if this server is started in debug mode AND debugger is attached to it 
     * AND threads are suspended (e.g. debugger stopped on breakpoint)
     */
    public boolean isSuspended() {

        ServerDebugInfo sdi = null;
        Session[] sessions = DebuggerManager.getDebuggerManager().getSessions();

        try {
            sdi = getStartTomcat().getDebugInfo(null);
        } catch (Exception e) {
            // don't care - just a try
        }

        if (sdi == null) {
            ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DebuggerInfo cannot be found for: " + this.toString());
        }

        for (int i=0; i < sessions.length; i++) {
            Session s = sessions[i];
            if (s != null) {
                Object o = s.lookupFirst(null, AttachingDICookie.class);
                if (o != null) {
                    AttachingDICookie attCookie = (AttachingDICookie)o;
                    if (sdi.getTransport().equals(ServerDebugInfo.TRANSPORT_SHMEM)) {
                        if (attCookie.getSharedMemoryName().equalsIgnoreCase(sdi.getShmemName())) {
                            Object d = s.lookupFirst(null, JPDADebugger.class);
                            if (d != null) {
                                JPDADebugger jpda = (JPDADebugger)d;
                                if (jpda.getState() == JPDADebugger.STATE_STOPPED) {
                                    return true;
                                }
                            }
                        }
                    } else {
                        if (attCookie.getHostName().equalsIgnoreCase(sdi.getHost())) {
                            if (attCookie.getPortNumber() == sdi.getPort()) {
                                Object d = s.lookupFirst(null, JPDADebugger.class);
                                if (d != null) {
                                    JPDADebugger jpda = (JPDADebugger)d;
                                    if (jpda.getState() == JPDADebugger.STATE_STOPPED) {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return false;
    }

    /** Returns username.
     * @return username or null when not connected.
     */
    public String getUsername () {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            return ip.getProperty(InstanceProperties.USERNAME_ATTR);
        }
        return username;
    }
    
    public void setUsername (String username){
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(InstanceProperties.USERNAME_ATTR, username);
            this.username = username;
        }
    }
    
    /** Returns password.
     * @return password or null when not connected.
     */
    public String getPassword () {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            return ip.getProperty(InstanceProperties.PASSWORD_ATTR);
        }
        return password;
    }
    
    public void setPassword (String password){
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(InstanceProperties.PASSWORD_ATTR, password);
            this.password = password;
        }
    }
    
    /** 
     * Return display name which represents this tomcat manager's server instance 
     * in IDE.
     *
     * @return display name which represents this tomcat manager's server instance 
     * in IDE, null if display name is not defined, which should not
     * occur.
     */
    public String getDisplayName() {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            return ip.getProperty(InstanceProperties.DISPLAY_NAME_ATTR);
        }
        return null;
    }
    
    public void setOpenContextLogOnRun(boolean val) {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(OPEN_CONTEXT_LOG_ON_RUN, Boolean.valueOf(val).toString());
        }
    }
    
    public boolean getOpenContextLogOnRun() {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            Object val = ip.getProperty(OPEN_CONTEXT_LOG_ON_RUN);
            if (val != null) return Boolean.valueOf(val.toString()).booleanValue();
        }
        return true;
    }    
    
// --- DeploymentManager interface implementation ----------------------
    
    public DeploymentConfiguration createConfiguration (DeployableObject deplObj) 
    throws InvalidModuleException {
        if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
            TomcatFactory.getEM ().log ("TomcatManager.createConfiguration "+deplObj);
        }
        if (!ModuleType.WAR.equals (deplObj.getType ())) {
            throw new InvalidModuleException ("Only WAR modules are supported for TomcatManager"); // NOI18N
        }
        
        return new WebappConfiguration (deplObj);
    }
    
    public Locale getCurrentLocale () {
        return Locale.getDefault ();
    }
    
    public Locale getDefaultLocale () {
        return Locale.getDefault ();
    }
    
    public Locale[] getSupportedLocales () {
        return Locale.getAvailableLocales ();
    }
    
    public boolean isLocaleSupported (Locale locale) {
        if (locale == null) {
            return false;
        }
        
        Locale [] supLocales = getSupportedLocales ();
        for (int i =0; itrue when connected.
     */
    public boolean isConnected () {
        return connected;
    }
    
    public String toString () {
        return "Tomcat manager ["+uri+", home "+catalinaHome+", base "+catalinaBase+(connected?"conneceted":"disconnected")+"]";    // NOI18N
    }

    /**
     * Getter for property debugPort.
     * @return Value of property debugPort.
     */
    public java.lang.Integer getDebugPort() {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            String prop = ip.getProperty(DEBUG_PORT);
            if (prop != null) {
                return Integer.valueOf(prop);
            }
        }
        return DEFAULT_DEBUG_PORT;
    }
    
    /**
     * Getter for property debugPort.
     * @return Value of property debugPort.
     */
    public String getDebugType() {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            String prop = ip.getProperty(DEBUG_TYPE);
            if (prop != null) {
                return prop;
            }
        }
        if (org.openide.util.Utilities.isWindows()) {
            return DEFAULT_DEBUG_TYPE_WINDOWS;
        }
        return DEFAULT_DEBUG_TYPE_UNIX;
    }

    public String getSharedMemory() {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            String prop = ip.getProperty(SHARED_MEMORY);
            if (prop != null) {
                return prop;
            }
        }
        return DEFAULT_SHARED_MEMORY;
    }

    /**
     * Getter for property debugPort.
     * @return Value of property debugPort.
     */
    public Boolean getClassic() {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            String prop = ip.getProperty(CLASSIC);
            if (prop != null) {
                return Boolean.valueOf(prop);
            }
        }
        return DEFAULT_CLASSIC;
    }

    public void setClassic(Boolean classic) {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(CLASSIC, classic.toString());
        }
    }

    public void setDebugType(String str) {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(DEBUG_TYPE, str);
        }
    }

    public void setSharedMemory(String str) {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(SHARED_MEMORY, str);
        }
    }
    
    /**
     * Setter for property debugPort.
     * @param port New value of property debugPort.
     */
    public void setDebugPort(java.lang.Integer port) {
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            ip.setProperty(DEBUG_PORT, port.toString());
        }
    }    
    
    public Integer getServerPort() {
        
        boolean upToDate = true;
        InstanceProperties ip = getInstanceProperties();
        if (ip == null) {
            return null;   
        }
                
        String time;
        try {
            time = ip.getProperty(TIMESTAMP);
        } catch (IllegalStateException ise) {
            // TODO - Workaround - should be fixed on j2eeserver side
            return null;
        }
        if (time != null) {
            Long t = Long.valueOf(time);
            upToDate = isPortUpToDate(t);
        }
        if (upToDate) {
            String o;
            try {
                o = ip.getProperty(SERVER_PORT);
            } catch (IllegalStateException ise) {
                // TODO - Workaround - should be fixed on j2eeserver side
                return null;
            }
            if (o != null) {
                Integer i = null;
                try {
                    i = Integer.valueOf(o); 
                } catch (Exception e){
                    ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Cannot convert port number: " + o + " to Integer."); //NOI18N
                }
                return i;
            } 
        } else {
            if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
                TomcatFactory.getEM ().log ("server port not uptodate, gonna read from file"); // NOI18N 
            }
            Integer p = readPortFromFile();
            return p;
        }
        return null;
    }
    
    public Integer getAdminPort() {
        boolean upToDate = true;
        InstanceProperties ip = getInstanceProperties();
        if (ip == null) {
            return null;
        }
        String time = ip.getProperty(TIMESTAMP);
        if (time != null) {
            Long t = Long.valueOf(time);
            upToDate = isPortUpToDate(t);
        }
        if (upToDate) {
            String o = ip.getProperty(ADMIN_PORT);
            if (o != null) {
                return Integer.valueOf(o);
            }
        } else {
            if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
                TomcatFactory.getEM ().log ("admin port not uptodate, gonna read from file"); // NOI18N
            }
            Integer p = readAdminPortFromFile();
            return p;
        }
        return null;
    }
    
    private synchronized void updatePortsFromFile() {
        try {
            InstanceProperties ip = getInstanceProperties();
            FileInputStream inputStream;
            File f;
            if (catalinaBase != null) {
                f = new File(catalinaBase + SERVERXML_PATH);
            } else {
                f = new File(catalinaHome + SERVERXML_PATH);
            }
            if (!f.isAbsolute ()) {
                InstalledFileLocator ifl = InstalledFileLocator.getDefault ();
                f = ifl.locate (f.getPath(), null, false);
                if (f == null) {
                    if (ip != null) {
                        ip.setProperty(ADMIN_PORT, DEFAULT_ADMIN_PORT.toString());
                        ip.setProperty(SERVER_PORT, DEFAULT_SERVER_PORT.toString());
                    }
                    return;
                }
            }
            
            inputStream = new FileInputStream(f);
            Long t = null;
            
            if (f.exists()) {
                t = new Long(f.lastModified());
            } else {
                return;
            }

            if (ip != null) {
                String stamp = ip.getProperty(TomcatManager.TIMESTAMP);
                if (stamp != null) {
                    if (isPortUpToDate(Long.valueOf(stamp))) {
                        return;
                    }
                }                
            }
                        
            Document doc = XMLUtil.parse(new InputSource(inputStream), false, false, null,org.openide.xml.EntityCatalog.getDefault());
            Server server = Server.createGraph(doc);
            Integer adminPort = new Integer(TomcatInstallUtil.getAdminPort(server));
            Integer serverPort = new Integer(TomcatInstallUtil.getPort(server));
            inputStream.close();
            
            if (ip != null) {
                ip.setProperty(TIMESTAMP, t.toString());
                ip.setProperty(ADMIN_PORT, adminPort.toString());
                ip.setProperty(SERVER_PORT, serverPort.toString());
            }
        } catch (Exception e) {
            if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
                TomcatFactory.getEM ().log (e.getMessage());
            }
        }
    }
    
    private Integer readAdminPortFromFile() {
        updatePortsFromFile();
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            Integer adminPort = null;
            try {
                adminPort = Integer.valueOf(ip.getProperty(ADMIN_PORT));
            } catch (Exception e) {
                ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, e.toString());
            }
            return adminPort;
        }
        return null;
    }

    private Integer readPortFromFile() {
        updatePortsFromFile();
        InstanceProperties ip = getInstanceProperties();
        if (ip != null) {
            Integer serverPort = null;
            try {
                serverPort = Integer.valueOf(ip.getProperty(SERVER_PORT));
            } catch (Exception e) {
                ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, e.toString());
            }
            return serverPort;
        }
        return null;
    }
    
    private synchronized boolean isPortUpToDate(Long timestamp) {
        String serverXml;
        if (catalinaBase == null) {
            serverXml = catalinaHome + SERVERXML_PATH;
        } else {
            serverXml = catalinaBase + SERVERXML_PATH;
        }
        File serverXmlFile = new File(serverXml);
        if (serverXmlFile.exists()) {
            long l = serverXmlFile.lastModified();
            if (l <= timestamp.longValue()) {
                return true;
            }
        }
        return true;
    }
    
    public void setServerPort(Integer port) {
        InstanceProperties ip = getInstanceProperties();
        if (ip == null) {
            return;
        }
        ip.setProperty(SERVER_PORT, port.toString());
    }
    
    //PENDING: does not set in server.xml
    private void setHost (String host) {
        InstanceProperties ip = getInstanceProperties();
        if (ip == null) {
            return;
        }
        ip.setProperty(HOST, host);
    }
    
    public String getHost () {
        InstanceProperties ip = getInstanceProperties();
        if (ip == null) {
            return null;
        }
        return ip.getProperty(HOST);
    }
    
    public void setAdminPort(Integer port) {
        InstanceProperties ip = getInstanceProperties();
        if (ip == null) {
            return;
        }
        ip.setProperty(ADMIN_PORT, port.toString());
    }

    public Server getRoot() {
        // do we really need to cache this? shouldn't we at least return a
        // defensive copy, otherwise we may get easily out of sync with server.xml
        // if (this.root != null) {
        //    return root;
        // }        
        try {
            File f = new File(getCatalinaDir().getAbsolutePath() + SERVERXML_PATH);
            InputStream in = new BufferedInputStream(new FileInputStream(f));            
            Document doc = XMLUtil.parse(new InputSource(in), false, false, null,org.openide.xml.EntityCatalog.getDefault());
            root = Server.createGraph(doc);
            return root;
        } catch (Exception e) {
            if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
                TomcatFactory.getEM ().log (e.toString());
            }
            return null;
        }
    }
    
    /** Initializes base dir for use with Tomcat 5.0.x. 
     *  @param baseDir directory for base dir.
     *  @param homeDir directory to copy config files from.
     *  @return File with absolute path for created dir or null when ther is an error.
     */    
    public File createBaseDir(File baseDir, File homeDir) {
        File targetFolder;
        if (!baseDir.isAbsolute ()) {
            baseDir = new File(System.getProperty("netbeans.user")+System.getProperty("file.separator")+baseDir);
            targetFolder = new File(System.getProperty("netbeans.user"));

        } else {
            targetFolder = baseDir.getParentFile ();
        }
        
        try {
            
            if (targetFolder == null) {
                TomcatFactory.getEM ().log (ErrorManager.INFORMATIONAL, "Cannot find parent folder for base dir "+baseDir.getPath ());
                return null;
            }
            File baseDirFO = new File (targetFolder, baseDir.getName ());
            baseDirFO.mkdir ();
                        
            // create directories
            String [] subdirs = new String [] { 
                "conf",   // NOI18N
                "conf/Catalina",   // NOI18N
                "conf/Catalina/localhost",   // NOI18N
                "logs",   // NOI18N
                "work",   // NOI18N
                "temp",   // NOI18N
                "webapps" // NOI18N
            };
            for (int i = 0; i",   // NOI18N
                "",   // NOI18N
                null, 
                "docBase=\"../server/webapps/admin\"", 
                "docBase=\"../server/webapps/manager\"",
                "docBase=\"balancer\""
            };
            String passwd = readPassword();
            if (passwd == null) {
                passwd = TomcatInstallUtil.generatePassword(8);
            }
            this.setPassword(passwd);
            String [] patternTo = new String [] { 
                null, 
                null, 
                "\n"+
                // jsp/servlet examples can be created as sample projects now, so this doesn't need to be here anymore
                //"\n"+
                //"\n"+
                "",   // NOI18N
                "\n",   // NOI18N
                null, 
                "docBase=\""+new File (homeDir, "server/webapps/admin").getAbsolutePath ()+"\"",   // NOI18N
                "docBase=\""+new File (homeDir, "server/webapps/manager").getAbsolutePath ()+"\"",   // NOI18N
                "docBase=\""+new File (homeDir, "webapps/balancer").getAbsolutePath ()+"\""   // NOI18N
            };
            for (int i = 0; i= 0) {
                sb.replace (idx, idx+from.length (), to);  // NOI18N
            }
            else {
                // Something unexpected
                TomcatFactory.getEM ().log (ErrorManager.WARNING, "Pattern "+from+" not found in "+src.getPath ());
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream (dst), "utf-8")); // NOI18N
            out.write (sb.toString ());
            
        } catch (java.io.IOException ioe) {
            ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, ioe);
            return false;
        } finally {
            try { if (out != null) out.close (); } catch (java.io.IOException ioe) { // ignore this
            }
            try { if (r != null) r.close (); } catch (java.io.IOException ioe) { // ignore this 
            }
        }
        return true;
    }
    
    /**
     * Open a context log for the specified module, if specified module does not
     * have its own logger defined, open shared context log instead.
     *
     * @param module module its context log should be opened
     */
    public void openLog(TargetModuleID module) {
        TomcatModule tomcatModule = null;
        if (module instanceof TomcatModule) {
            tomcatModule = (TomcatModule)module;
        } else {
            try {
                TargetModuleID[] tomMod = getRunningModules(ModuleType.WAR, new Target[]{module.getTarget()});
                for (int i = 0; i < tomMod.length; i++) {
                    if (module.getModuleID().equals(tomMod[i].getModuleID())) {
                        tomcatModule = (TomcatModule)tomMod[i];
                        break;
                    }
                }
            } catch (TargetException te) {
                ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, te);
            }
        }
        if (tomcatModule != null && logManager.hasContextLogger(tomcatModule)) {
            logManager.openContextLog(tomcatModule);
        } else {
            logManager.openSharedContextLog();
        }
    }
    
    /**
     * Return TomcatManagerConfig for easier access to some server.xml
     * settings.
     *
     * @return TomcatManagerConfig for easier access to some server.xml
     *         settings.
     */
    public TomcatManagerConfig tomcatManagerConfig() {
        return tomcatManagerConfig;
    }
    
    /**
     * Return LogManager which manages all context and shared context
     * logs for this TomcatManager.
     *
     * @return LogManager which manages all context and shared context
     *         logs for this TomcatManager.
     */
    public LogManager logManager() {
        return logManager;
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.