From: markt Date: Thu, 13 Jul 2006 02:36:06 +0000 (+0000) Subject: Delete unused classes deprecated in TC5. X-Git-Url: https://git.internetallee.de/?a=commitdiff_plain;h=74f605d7448e724619e60859526858c138dc1178;p=tomcat7.0 Delete unused classes deprecated in TC5. git-svn-id: https://svn.apache.org/repos/asf/tomcat/tc6.0.x/trunk@421482 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/java/org/apache/catalina/util/CGIProcessEnvironment.java b/java/org/apache/catalina/util/CGIProcessEnvironment.java deleted file mode 100644 index b9e0f46fe..000000000 --- a/java/org/apache/catalina/util/CGIProcessEnvironment.java +++ /dev/null @@ -1,448 +0,0 @@ -/* - * Copyright 1999,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package org.apache.catalina.util; - -import java.io.File; -import java.net.URLEncoder; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.StringTokenizer; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - - -/** - * Encapsulates the CGI Process' environment and rules to derive - * that environment from the servlet container and request information. - * @author Martin Dengler [root@martindengler.com] - * @version $Revision: 303237 $, $Date: 2004-09-17 01:23:37 +0200 (ven., 17 sept. 2004) $ - * @since Tomcat 4.0 - */ - -public class CGIProcessEnvironment extends ProcessEnvironment { - - - private static org.apache.commons.logging.Log log= - org.apache.commons.logging.LogFactory.getLog( CGIProcessEnvironment.class ); - - /** cgi command's query parameters */ - private Hashtable queryParameters = null; - - /** - * The CGI search path will start at - * webAppRootDir + File.separator + cgiPathPrefix - * (or webAppRootDir alone if cgiPathPrefix is - * null) - */ - private String cgiPathPrefix = null; - - - /** - * Creates a ProcessEnvironment and derives the necessary environment, - * working directory, command, etc. The cgi path prefix is initialized - * to "" (the empty string). - * - * @param req HttpServletRequest for information provided by - * the Servlet API - * @param context ServletContext for information provided by - * the Servlet API - */ - public CGIProcessEnvironment(HttpServletRequest req, - ServletContext context) { - this(req, context, ""); - } - - - - /** - * Creates a ProcessEnvironment and derives the necessary environment, - * working directory, command, etc. - * @param req HttpServletRequest for information provided by - * the Servlet API - * @param context ServletContext for information provided by - * the Servlet API - * @param cgiPathPrefix subdirectory of webAppRootDir below which the - * web app's CGIs may be stored; can be null or "". - */ - public CGIProcessEnvironment(HttpServletRequest req, - ServletContext context, String cgiPathPrefix) { - this(req, context, cgiPathPrefix, 0); - } - - - - /** - * Creates a ProcessEnvironment and derives the necessary environment, - * working directory, command, etc. - * @param req HttpServletRequest for information provided by - * the Servlet API - * @param context ServletContext for information provided by - * the Servlet API - * @param debug int debug level (0 == none, 6 == lots) - */ - public CGIProcessEnvironment(HttpServletRequest req, - ServletContext context, int debug) { - this(req, context, "", 0); - } - - - - - /** - * Creates a ProcessEnvironment and derives the necessary environment, - * working directory, command, etc. - * @param req HttpServletRequest for information provided by - * the Servlet API - * @param context ServletContext for information provided by - * the Servlet API - * @param cgiPathPrefix subdirectory of webAppRootDir below which the - * web app's CGIs may be stored; can be null or "". - * @param debug int debug level (0 == none, 6 == lots) - */ - public CGIProcessEnvironment(HttpServletRequest req, - ServletContext context, String cgiPathPrefix, int debug) { - super(req, context, debug); - this.cgiPathPrefix = cgiPathPrefix; - queryParameters = new Hashtable(); - Enumeration paramNames = req.getParameterNames(); - while (paramNames != null && paramNames.hasMoreElements()) { - String param = paramNames.nextElement().toString(); - if (param != null) { - queryParameters.put(param, - URLEncoder.encode(req.getParameter(param))); - } - } - this.valid = deriveProcessEnvironment(req); - } - - - - /** - * Constructs the CGI environment to be supplied to the invoked CGI - * script; relies heavliy on Servlet API methods and findCGI - * @param req request associated with the CGI invokation - * @return true if environment was set OK, false if there was a problem - * and no environment was set - */ - protected boolean deriveProcessEnvironment(HttpServletRequest req) { - /* - * This method is slightly ugly; c'est la vie. - * "You cannot stop [ugliness], you can only hope to contain [it]" - * (apologies to Marv Albert regarding MJ) - */ - - Hashtable envp; - super.deriveProcessEnvironment(req); - envp = getEnvironment(); - - String sPathInfoOrig = null; - String sPathTranslatedOrig = null; - String sPathInfoCGI = null; - String sPathTranslatedCGI = null; - String sCGIFullPath = null; - String sCGIScriptName = null; - String sCGIFullName = null; - String sCGIName = null; - String[] sCGINames; - sPathInfoOrig = this.pathInfo; - sPathInfoOrig = sPathInfoOrig == null ? "" : sPathInfoOrig; - sPathTranslatedOrig = req.getPathTranslated(); - sPathTranslatedOrig = sPathTranslatedOrig == null ? "" : - sPathTranslatedOrig; - sCGINames = - findCGI(sPathInfoOrig, getWebAppRootDir(), getContextPath(), - getServletPath(), cgiPathPrefix); - sCGIFullPath = sCGINames[0]; - sCGIScriptName = sCGINames[1]; - sCGIFullName = sCGINames[2]; - sCGIName = sCGINames[3]; - if (sCGIFullPath == null || sCGIScriptName == null - || sCGIFullName == null || sCGIName == null) { - return false; - } - envp.put("SERVER_SOFTWARE", "TOMCAT"); - envp.put("SERVER_NAME", nullsToBlanks(req.getServerName())); - envp.put("GATEWAY_INTERFACE", "CGI/1.1"); - envp.put("SERVER_PROTOCOL", nullsToBlanks(req.getProtocol())); - int port = req.getServerPort(); - Integer iPort = (port == 0 ? new Integer(-1) : new Integer(port)); - envp.put("SERVER_PORT", iPort.toString()); - envp.put("REQUEST_METHOD", nullsToBlanks(req.getMethod())); - - /*- - * PATH_INFO should be determined by using sCGIFullName: - * 1) Let sCGIFullName not end in a "/" (see method findCGI) - * 2) Let sCGIFullName equal the pathInfo fragment which - * corresponds to the actual cgi script. - * 3) Thus, PATH_INFO = request.getPathInfo().substring( - * sCGIFullName.length()) - * - * (see method findCGI, where the real work is done) - * - */ - - if (pathInfo == null || - (pathInfo.substring(sCGIFullName.length()).length() <= 0)) { - sPathInfoCGI = ""; - } else { - sPathInfoCGI = pathInfo.substring(sCGIFullName.length()); - } - envp.put("PATH_INFO", sPathInfoCGI); - - /*- - * PATH_TRANSLATED must be determined after PATH_INFO (and the - * implied real cgi-script) has been taken into account. - * - * The following example demonstrates: - * - * servlet info = /servlet/cgigw/dir1/dir2/cgi1/trans1/trans2 - * cgifullpath = /servlet/cgigw/dir1/dir2/cgi1 - * path_info = /trans1/trans2 - * webAppRootDir = servletContext.getRealPath("/") - * - * path_translated = servletContext.getRealPath("/trans1/trans2") - * - * That is, PATH_TRANSLATED = webAppRootDir + sPathInfoCGI - * (unless sPathInfoCGI is null or blank, then the CGI - * specification dictates that the PATH_TRANSLATED metavariable - * SHOULD NOT be defined. - * - */ - - if (sPathInfoCGI != null && !("".equals(sPathInfoCGI))) { - sPathTranslatedCGI = getContext().getRealPath(sPathInfoCGI); - } else { - sPathTranslatedCGI = null; - } - if (sPathTranslatedCGI == null || "".equals(sPathTranslatedCGI)) { - //NOOP - } else { - envp.put("PATH_TRANSLATED", nullsToBlanks(sPathTranslatedCGI)); - } - envp.put("SCRIPT_NAME", nullsToBlanks(sCGIScriptName)); - envp.put("QUERY_STRING", nullsToBlanks(req.getQueryString())); - envp.put("REMOTE_HOST", nullsToBlanks(req.getRemoteHost())); - envp.put("REMOTE_ADDR", nullsToBlanks(req.getRemoteAddr())); - envp.put("AUTH_TYPE", nullsToBlanks(req.getAuthType())); - envp.put("REMOTE_USER", nullsToBlanks(req.getRemoteUser())); - envp.put("REMOTE_IDENT", ""); //not necessary for full compliance - envp.put("CONTENT_TYPE", nullsToBlanks(req.getContentType())); - - /* Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined - * if there is no content, so we cannot put 0 or -1 in as per the - * Servlet API spec. - */ - - int contentLength = req.getContentLength(); - String sContentLength = (contentLength <= 0 ? "" : ( - new Integer(contentLength)).toString()); - envp.put("CONTENT_LENGTH", sContentLength); - Enumeration headers = req.getHeaderNames(); - String header = null; - while (headers.hasMoreElements()) { - header = null; - header = ((String)headers.nextElement()).toUpperCase(); - //REMIND: rewrite multiple headers as if received as single - //REMIND: change character set - //REMIND: I forgot what the previous REMIND means - if ("AUTHORIZATION".equalsIgnoreCase(header) - || "PROXY_AUTHORIZATION".equalsIgnoreCase(header)) { - //NOOP per CGI specification section 11.2 - } else if ("HOST".equalsIgnoreCase(header)) { - String host = req.getHeader(header); - envp.put("HTTP_" + header.replace('-', '_'), - host.substring(0, host.indexOf(":"))); - } else { - envp.put("HTTP_" + header.replace('-', '_'), - req.getHeader(header)); - } - } - command = sCGIFullPath; - workingDirectory = new File(command.substring(0, - command.lastIndexOf(File.separator))); - envp.put("X_TOMCAT_COMMAND_PATH", command); //for kicks - this.setEnvironment(envp); - return true; - } - - - /** - * Resolves core information about the cgi script.

Example URI: - *

 /servlet/cgigateway/dir1/realCGIscript/pathinfo1 
- *

- *

- * CGI search algorithm: search the real path below - * <my-webapp-root> and find the first non-directory in - * the getPathTranslated("/"), reading/searching from left-to-right. - *

- *

- * The CGI search path will start at - * webAppRootDir + File.separator + cgiPathPrefix (or webAppRootDir - * alone if cgiPathPrefix is null). - *

- *

- * cgiPathPrefix is usually set by the calling servlet to the servlet's - * cgiPathPrefix init parameter - *

- * - * @param pathInfo String from HttpServletRequest.getPathInfo() - * @param webAppRootDir String from context.getRealPath("/") - * @param contextPath String as from HttpServletRequest.getContextPath() - * @param servletPath String as from HttpServletRequest.getServletPath() - * @param cgiPathPrefix subdirectory of webAppRootDir below which the - * web app's CGIs may be stored; can be null. - * @return - * - * @since Tomcat 4.0 - */ - protected String[] findCGI(String pathInfo, String webAppRootDir, - String contextPath, String servletPath, String cgiPathPrefix) { - String path = null; - String name = null; - String scriptname = null; - String cginame = null; - if ((webAppRootDir != null) - && (webAppRootDir.lastIndexOf("/") - == (webAppRootDir.length() - 1))) { - //strip the trailing "/" from the webAppRootDir - webAppRootDir = - webAppRootDir.substring(0, - (webAppRootDir.length() - 1)); - } - if (cgiPathPrefix != null) { - webAppRootDir = webAppRootDir + File.separator - + cgiPathPrefix; - } - - if (log.isDebugEnabled()) { - log.debug("findCGI: start = [" + webAppRootDir - + "], pathInfo = [" + pathInfo + "] "); - } - File currentLocation = new File(webAppRootDir); - StringTokenizer dirWalker = new StringTokenizer(pathInfo, "/"); - while (!currentLocation.isFile() && dirWalker.hasMoreElements()) { - currentLocation = new - File(currentLocation, (String) dirWalker.nextElement()); - if (log.isDebugEnabled()) { - log.debug("findCGI: traversing to [" + currentLocation + "]"); - } - } - if (!currentLocation.isFile()) { - return new String[] { null, null, null, null }; - } else { - if (log.isDebugEnabled()) { - log.debug("findCGI: FOUND cgi at [" + currentLocation + "]"); - } - path = currentLocation.getAbsolutePath(); - name = currentLocation.getName(); - cginame = currentLocation.getParent() - .substring(webAppRootDir.length()) - + File.separator + name; - if (".".equals(contextPath)) { - scriptname = servletPath + cginame; - } else { - scriptname = contextPath + servletPath + cginame; - } - } - if (log.isDebugEnabled()) { - log.debug("findCGI calc: name=" + name + ", path=" + path - + ", scriptname=" + scriptname + ", cginame=" + cginame); - } - return new String[] { path, scriptname, cginame, name }; - } - - - /** - * Print important CGI environment information in an - * easy-to-read HTML table - * @return HTML string containing CGI environment info - */ - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - if (isValid()) { - Enumeration envk = env.keys(); - while (envk.hasMoreElements()) { - String s = (String)envk.nextElement(); - sb.append(""); - } - } - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - Enumeration paramk = queryParameters.keys(); - while (paramk.hasMoreElements()) { - String s = paramk.nextElement().toString(); - sb.append(""); - } - - sb.append("
"); - sb.append("ProcessEnvironment Info
Debug Level"); - sb.append(debug); - sb.append("
Validity:"); - sb.append(isValid()); - sb.append("
"); - sb.append(s); - sb.append(""); - sb.append(blanksToString((String)env.get(s), - "[will be set to blank]")); - sb.append("

Derived Command"); - sb.append(nullsToBlanks(command)); - sb.append("
Working Directory"); - if (workingDirectory != null) { - sb.append(workingDirectory.toString()); - } - sb.append("
Query Params
"); - sb.append(s); - sb.append(""); - sb.append(queryParameters.get(s).toString()); - sb.append("

end."); - return sb.toString(); - } - - - /** - * Gets process' derived query parameters - * @return process' query parameters - */ - public Hashtable getParameters() { - return queryParameters; - } - -} diff --git a/java/org/apache/catalina/util/ProcessEnvironment.java b/java/org/apache/catalina/util/ProcessEnvironment.java deleted file mode 100644 index d97f775e0..000000000 --- a/java/org/apache/catalina/util/ProcessEnvironment.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright 1999,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.catalina.util; - -import java.io.File; -import java.util.Enumeration; -import java.util.Hashtable; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - - - -/** - * Encapsulates the Process environment and rules to derive - * that environment from the servlet container and request information. - * @author Martin Dengler [root@martindengler.com] - * @version $Revision: 303236 $, $Date: 2004-09-17 01:19:54 +0200 (ven., 17 sept. 2004) $ - * @since Tomcat 4.0 - */ -public class ProcessEnvironment { - - private static org.apache.commons.logging.Log log= - org.apache.commons.logging.LogFactory.getLog( ProcessEnvironment.class ); - - /** context of the enclosing servlet */ - private ServletContext context = null; - - /** real file system directory of the enclosing servlet's web app */ - private String webAppRootDir = null; - - /** context path of enclosing servlet */ - private String contextPath = null; - - /** pathInfo for the current request */ - protected String pathInfo = null; - - /** servlet URI of the enclosing servlet */ - private String servletPath = null; - - /** derived process environment */ - protected Hashtable env = null; - - /** command to be invoked */ - protected String command = null; - - /** whether or not this object is valid or not */ - protected boolean valid = false; - - /** the debugging detail level for this instance. */ - protected int debug = 0; - - /** process' desired working directory */ - protected File workingDirectory = null; - - - /** - * Creates a ProcessEnvironment and derives the necessary environment, - * working directory, command, etc. - * @param req HttpServletRequest for information provided by - * the Servlet API - * @param context ServletContext for information provided by - * the Servlet API - */ - public ProcessEnvironment(HttpServletRequest req, - ServletContext context) { - this(req, context, 0); - } - - - /** - * Creates a ProcessEnvironment and derives the necessary environment, - * working directory, command, etc. - * @param req HttpServletRequest for information provided by - * the Servlet API - * @param context ServletContext for information provided by - * the Servlet API - * @param debug int debug level (0 == none, 4 == medium, 6 == lots) - */ - public ProcessEnvironment(HttpServletRequest req, - ServletContext context, int debug) { - this.debug = debug; - setupFromContext(context); - setupFromRequest(req); - this.valid = deriveProcessEnvironment(req); - if (log.isDebugEnabled()) - log.debug(this.getClass().getName() + "() ctor, debug level " + - debug); - } - - - /** - * Uses the ServletContext to set some process variables - * @param context ServletContext for information provided by - * the Servlet API - */ - protected void setupFromContext(ServletContext context) { - this.context = context; - this.webAppRootDir = context.getRealPath("/"); - } - - - /** - * Uses the HttpServletRequest to set most process variables - * @param req HttpServletRequest for information provided by - * the Servlet API - */ - protected void setupFromRequest(HttpServletRequest req) { - this.contextPath = req.getContextPath(); - this.pathInfo = req.getPathInfo(); - this.servletPath = req.getServletPath(); - } - - - /** - * Print important process environment information in an - * easy-to-read HTML table - * @return HTML string containing process environment info - */ - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - if (isValid()) { - Enumeration envk = env.keys(); - while (envk.hasMoreElements()) { - String s = (String)envk.nextElement(); - sb.append(""); - } - } - sb.append(""); - sb.append(""); - sb.append(""); - sb.append("
"); - sb.append("ProcessEnvironment Info
Debug Level"); - sb.append(debug); - sb.append("
Validity:"); - sb.append(isValid()); - sb.append("
"); - sb.append(s); - sb.append(""); - sb.append(blanksToString((String)env.get(s), - "[will be set to blank]")); - sb.append("

Derived Command"); - sb.append(nullsToBlanks(command)); - sb.append("
Working Directory"); - if (workingDirectory != null) { - sb.append(workingDirectory.toString()); - } - sb.append("

end."); - return sb.toString(); - } - - - /** - * Gets derived command string - * @return command string - */ - public String getCommand() { - return command; - } - - - /** - * Sets the desired command string - * @param command String command as desired - * @return command string - */ - protected String setCommand(String command) { - return command; - } - - - /** - * Gets this process' derived working directory - * @return working directory - */ - public File getWorkingDirectory() { - return workingDirectory; - } - - - /** - * Gets process' environment - * @return process' environment - */ - public Hashtable getEnvironment() { - return env; - } - - - /** - * Sets process' environment - * @param env process' environment - * @return Hashtable to which the process' environment was set - */ - public Hashtable setEnvironment(Hashtable env) { - this.env = env; - return this.env; - } - - - /** - * Gets validity status - * @return true if this environment is valid, false otherwise - */ - public boolean isValid() { - return valid; - } - - - /** - * Converts null strings to blank strings ("") - * @param s string to be converted if necessary - * @return a non-null string, either the original or the empty string - * ("") if the original was null - */ - protected String nullsToBlanks(String s) { - return nullsToString(s, ""); - } - - - /** - * Converts null strings to another string - * @param couldBeNull string to be converted if necessary - * @param subForNulls string to return instead of a null string - * @return a non-null string, either the original or the substitute - * string if the original was null - */ - protected String nullsToString(String couldBeNull, String subForNulls) { - return (couldBeNull == null ? subForNulls : couldBeNull); - } - - - /** - * Converts blank strings to another string - * @param couldBeBlank string to be converted if necessary - * @param subForBlanks string to return instead of a blank string - * @return a non-null string, either the original or the substitute - * string if the original was null or empty ("") - */ - protected String blanksToString(String couldBeBlank, - String subForBlanks) { - return (("".equals(couldBeBlank) || couldBeBlank == null) ? - subForBlanks : couldBeBlank); - } - - - /** - * Constructs the Process environment to be supplied to the invoked - * process. Defines an environment no environment variables. - *

- * Should be overriden by subclasses to perform useful setup. - *

- * - * @param req request associated with the - * Process' invocation - * @return true if environment was set OK, false if there was a problem - * and no environment was set - */ - protected boolean deriveProcessEnvironment(HttpServletRequest req) { - - Hashtable envp = new Hashtable(); - command = getCommand(); - if (command != null) { - workingDirectory = new - File(command.substring(0, - command.lastIndexOf(File.separator))); - envp.put("X_TOMCAT_COMMAND_PATH", command); //for kicks - } - this.env = envp; - return true; - } - - - /** - * Gets the root directory of the web application to which this process\ - * belongs - * @return root directory - */ - public String getWebAppRootDir() { - return webAppRootDir; - } - - - public String getContextPath(){ - return contextPath; - } - - - public ServletContext getContext(){ - return context; - } - - - public String getServletPath(){ - return servletPath; - } -} diff --git a/java/org/apache/catalina/util/ProcessHelper.java b/java/org/apache/catalina/util/ProcessHelper.java deleted file mode 100644 index b2aed9a04..000000000 --- a/java/org/apache/catalina/util/ProcessHelper.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * Copyright 1999,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.catalina.util; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; - -import javax.servlet.http.HttpServletResponse; - -/** - * Encapsulates the knowledge of how to run a CGI script, given the - * script's desired environment and (optionally) input/output streams - * - *

- * - * Exposes a run method used to actually invoke the - * CGI. - * - *

- *

- * - * The CGI environment and settings are derived from the information - * passed to the constuctor. - * - *

- *

- * - * The input and output streams can be set by the setInput - * and setResponse methods, respectively. - *

- * - * @author Martin Dengler [root@martindengler.com] - * @version $Revision: 303236 $, $Date: 2004-09-17 01:19:54 +0200 (ven., 17 sept. 2004) $ - */ -public class ProcessHelper { - - private static org.apache.commons.logging.Log log= - org.apache.commons.logging.LogFactory.getLog( ProcessHelper.class ); - - /** script/command to be executed */ - private String command = null; - - /** environment used when invoking the cgi script */ - private Hashtable env = null; - - /** working directory used when invoking the cgi script */ - private File wd = null; - - /** query parameters to be passed to the invoked script */ - private Hashtable params = null; - - /** stdin to be passed to cgi script */ - private InputStream stdin = null; - - /** response object used to set headers & get output stream */ - private HttpServletResponse response = null; - - /** boolean tracking whether this object has enough info to run() */ - private boolean readyToRun = false; - - /** the debugging detail level for this instance. */ - private int debug = 0; - - /** the time in ms to wait for the client to send us CGI input data */ - private int iClientInputTimeout; - - /** - * Creates a ProcessHelper and initializes its environment, working - * directory, and query parameters. - *
- * Input/output streams (optional) are set using the - * setInput and setResponse methods, - * respectively. - * - * @param command string full path to command to be executed - * @param env Hashtable with the desired script environment - * @param wd File with the script's desired working directory - * @param params Hashtable with the script's query parameters - */ - public ProcessHelper( - String command, - Hashtable env, - File wd, - Hashtable params) { - this.command = command; - this.env = env; - this.wd = wd; - this.params = params; - updateReadyStatus(); - } - - /** - * Checks & sets ready status - */ - protected void updateReadyStatus() { - if (command != null - && env != null - && wd != null - && params != null - && response != null) { - readyToRun = true; - } else { - readyToRun = false; - } - } - - /** - * Gets ready status - * - * @return false if not ready (run will throw - * an exception), true if ready - */ - public boolean isReady() { - return readyToRun; - } - - /** - * Sets HttpServletResponse object used to set headers and send - * output to - * - * @param response HttpServletResponse to be used - * - */ - public void setResponse(HttpServletResponse response) { - this.response = response; - updateReadyStatus(); - } - - /** - * Sets standard input to be passed on to the invoked cgi script - * - * @param stdin InputStream to be used - * - */ - public void setInput(InputStream stdin) { - this.stdin = stdin; - updateReadyStatus(); - } - - /** - * Converts a Hashtable to a String array by converting each - * key/value pair in the Hashtable to a String in the form - * "key=value" (hashkey + "=" + hash.get(hashkey).toString()) - * - * @param h Hashtable to convert - * - * @return converted string array - * - * @exception NullPointerException if a hash key has a null value - * - */ - private String[] hashToStringArray(Hashtable h) - throws NullPointerException { - Vector v = new Vector(); - Enumeration e = h.keys(); - while (e.hasMoreElements()) { - String k = e.nextElement().toString(); - v.add(k + "=" + h.get(k)); - } - String[] strArr = new String[v.size()]; - v.copyInto(strArr); - return strArr; - } - - /** - * Executes a process script with the desired environment, current working - * directory, and input/output streams - * - *

- * This implements the following CGI specification recommedations: - *

- *

- * - * For more information, see java.lang.Runtime#exec(String command, - * String[] envp, File dir) - * - * @exception IOException if problems during reading/writing occur - * - */ - public void run() throws IOException { - - /* - * REMIND: this method feels too big; should it be re-written? - */ - - if (!isReady()) { - throw new IOException( - this.getClass().getName() + ": not ready to run."); - } - - if (log.isDebugEnabled()) { - log.debug("runCGI(envp=[" + env + "], command=" + command + ")"); - } - - if ((command.indexOf(File.separator + "." + File.separator) >= 0) - || (command.indexOf(File.separator + "..") >= 0) - || (command.indexOf(".." + File.separator) >= 0)) { - throw new IOException( - this.getClass().getName() - + "Illegal Character in CGI command " - + "path ('.' or '..') detected. Not " - + "running CGI [" - + command - + "]."); - } - - /* original content/structure of this section taken from - * http://developer.java.sun.com/developer/ - * bugParade/bugs/4216884.html - * with major modifications by Martin Dengler - */ - Runtime rt = null; - BufferedReader commandsStdOut = null; - BufferedReader commandsStdErr = null; - BufferedOutputStream commandsStdIn = null; - Process proc = null; - byte[] bBuf = new byte[1024]; - char[] cBuf = new char[1024]; - int bufRead = -1; - - //create query arguments - Enumeration paramNames = params.keys(); - StringBuffer cmdAndArgs = new StringBuffer(command); - if (paramNames != null && paramNames.hasMoreElements()) { - cmdAndArgs.append(" "); - while (paramNames.hasMoreElements()) { - String k = (String) paramNames.nextElement(); - String v = params.get(k).toString(); - if ((k.indexOf("=") < 0) && (v.indexOf("=") < 0)) { - cmdAndArgs.append(k); - cmdAndArgs.append("="); - v = java.net.URLEncoder.encode(v); - cmdAndArgs.append(v); - cmdAndArgs.append(" "); - } - } - } - - String postIn = getPostInput(params); - int contentLength = - (postIn.length() + System.getProperty("line.separator").length()); - if ("POST".equals(env.get("REQUEST_METHOD"))) { - env.put("CONTENT_LENGTH", new Integer(contentLength)); - } - - rt = Runtime.getRuntime(); - proc = rt.exec(cmdAndArgs.toString(), hashToStringArray(env), wd); - - /* - * provide input to cgi - * First -- parameters - * Second -- any remaining input - */ - commandsStdIn = new BufferedOutputStream(proc.getOutputStream()); - if (log.isDebugEnabled()) { - log.debug("runCGI stdin=[" + stdin + "], qs=" + env.get("QUERY_STRING")); - } - if ("POST".equals(env.get("REQUEST_METHOD"))) { - if (log.isDebugEnabled()) { - log.debug("runCGI: writing ---------------\n"); - log.debug(postIn); - log.debug( - "runCGI: new content_length=" - + contentLength - + "---------------\n"); - } - commandsStdIn.write(postIn.getBytes()); - } - if (stdin != null) { - //REMIND: document this - /* assume if nothing is available after a time, that nothing is - * coming... - */ - if (stdin.available() <= 0) { - if (log.isDebugEnabled()) { - log.debug( - "runCGI stdin is NOT available [" - + stdin.available() - + "]"); - } - try { - Thread.sleep(iClientInputTimeout); - } catch (InterruptedException ignored) { - } - } - if (stdin.available() > 0) { - if (log.isDebugEnabled()) { - log.debug( - "runCGI stdin IS available [" - + stdin.available() - + "]"); - } - bBuf = new byte[1024]; - bufRead = -1; - try { - while ((bufRead = stdin.read(bBuf)) != -1) { - if (log.isDebugEnabled()) { - log.debug( - "runCGI: read [" - + bufRead - + "] bytes from stdin"); - } - commandsStdIn.write(bBuf, 0, bufRead); - } - if (log.isDebugEnabled()) { - log.debug("runCGI: DONE READING from stdin"); - } - } catch (IOException ioe) { - log.error("runCGI: couldn't write all bytes.", ioe); - } - } - } - commandsStdIn.flush(); - commandsStdIn.close(); - - /* we want to wait for the process to exit, Process.waitFor() - * is useless in our situation; see - * http://developer.java.sun.com/developer/ - * bugParade/bugs/4223650.html - */ - - boolean isRunning = true; - commandsStdOut = - new BufferedReader(new InputStreamReader(proc.getInputStream())); - commandsStdErr = - new BufferedReader(new InputStreamReader(proc.getErrorStream())); - BufferedWriter servletContainerStdout = null; - - try { - if (response.getOutputStream() != null) { - servletContainerStdout = - new BufferedWriter( - new OutputStreamWriter(response.getOutputStream())); - } - } catch (IOException ignored) { - //NOOP: no output will be written - } - - while (isRunning) { - - try { - //read stderr first - cBuf = new char[1024]; - while ((bufRead = commandsStdErr.read(cBuf)) != -1) { - if (servletContainerStdout != null) { - servletContainerStdout.write(cBuf, 0, bufRead); - } - } - - //set headers - String line = null; - while (((line = commandsStdOut.readLine()) != null) - && !("".equals(line))) { - if (log.isDebugEnabled()) { - log.debug("runCGI: addHeader(\"" + line + "\")"); - } - if (line.startsWith("HTTP")) { - //TODO: should set status codes (NPH support) - /* - * response.setStatus(getStatusCode(line)); - */ - } else { - response.addHeader( - line.substring(0, line.indexOf(":")).trim(), - line.substring(line.indexOf(":") + 1).trim()); - } - } - - //write output - cBuf = new char[1024]; - while ((bufRead = commandsStdOut.read(cBuf)) != -1) { - if (servletContainerStdout != null) { - if (log.isDebugEnabled()) { - log.debug("runCGI: write(\"" + new String(cBuf) + "\")"); - } - servletContainerStdout.write(cBuf, 0, bufRead); - } - } - - if (servletContainerStdout != null) { - servletContainerStdout.flush(); - } - - proc.exitValue(); // Throws exception if alive - - isRunning = false; - - } catch (IllegalThreadStateException e) { - try { - Thread.sleep(500); - } catch (InterruptedException ignored) { - } - } - } //replacement for Process.waitFor() - - } - - /** - * Gets a string for input to a POST cgi script - * - * @param params Hashtable of query parameters to be passed to - * the CGI script - * @return for use as input to the CGI script - */ - - protected String getPostInput(Hashtable params) { - String lineSeparator = System.getProperty("line.separator"); - Enumeration paramNames = params.keys(); - StringBuffer postInput = new StringBuffer(""); - StringBuffer qs = new StringBuffer(""); - if (paramNames != null && paramNames.hasMoreElements()) { - while (paramNames.hasMoreElements()) { - String k = (String) paramNames.nextElement(); - String v = params.get(k).toString(); - if ((k.indexOf("=") < 0) && (v.indexOf("=") < 0)) { - postInput.append(k); - qs.append(k); - postInput.append("="); - qs.append("="); - postInput.append(v); - qs.append(v); - postInput.append(lineSeparator); - qs.append("&"); - } - } - } - qs.append(lineSeparator); - return qs.append(postInput).toString(); - } - - public int getIClientInputTimeout() { - return iClientInputTimeout; - } - - public void setIClientInputTimeout(int iClientInputTimeout) { - this.iClientInputTimeout = iClientInputTimeout; - } -}