You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by hu...@apache.org on 2002/08/14 19:50:28 UTC
cvs commit: jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/http SocketUtil.java ResourceServlet.java HttpClient.java ConnectionServlet.java
husted 2002/08/14 10:50:28
Added: scaffold/src/java/org/apache/commons/scaffold/http
SocketUtil.java ResourceServlet.java
HttpClient.java ConnectionServlet.java
Log:
[SCAFFOLD] New sandbox component
Revision Changes Path
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/http/SocketUtil.java
Index: SocketUtil.java
===================================================================
package org.apache.commons.scaffold.http;
import java.net.*;
import java.io.*;
/** A shorthand way to create BufferedReaders and
* PrintWriters associated with a Socket.
* <P>
* Taken from Core Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.coreservlets.com/.
* © 2000 Marty Hall; may be freely used or adapted.
*/
public class SocketUtil {
/**
* Make a BufferedReader to get incoming data.
*/
public static BufferedReader getReader(Socket s)
throws IOException {
return(new BufferedReader(
new InputStreamReader(s.getInputStream())));
}
/**
* Make a PrintWriter to send outgoing data.
* This PrintWriter will automatically flush stream
* when println is called.
*/
public static PrintWriter getWriter(Socket s)
throws IOException {
// 2nd argument of true means autoflush
return(new PrintWriter(s.getOutputStream(), true));
}
} // end SocketUtil
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/http/ResourceServlet.java
Index: ResourceServlet.java
===================================================================
package org.apache.commons.scaffold.http;
import java.util.Properties;
import java.util.Map;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.scaffold.lang.Log;
/**
* Base servlet for loading application resources.
*/
public class ResourceServlet extends HttpServlet {
// -------------------------------------------------- Parameter Utilities
/**
* Check for a parameter and returns a default value if not found.
*
* @param parameter The attribute name to look for
* @param defaultValue The default to return if the parameter is not found
* @return The customized value or the default value
*/
public String getInitString(
String parameter,
String defaultValue) {
String stringValue =
getServletConfig().getInitParameter(parameter);
if (null==stringValue) return defaultValue;
return stringValue;
}
/**
* Check for a parameter and returns a default value if not found,
* or if the value does not convert to an <code>int</code>.
*
* @param parameter The attribute name to look for
* @defaultValue The default to return if the parameter is not found
* @return The customized value or the default value
*/
public int getInitInt(
String parameter,
int defaultValue) {
String stringValue = null;
int intValue = defaultValue;
try {
stringValue =
getServletConfig().getInitParameter(parameter);
intValue = Integer.parseInt(stringValue);
} catch (Throwable t) {
intValue = defaultValue;
}
return intValue;
}
/**
* Return a map of this servlet's initialization parameters.
*
* @return A map of this servlet's initialization parameters.
* @fixme Not tested yet
*/
public Map getInitParameters() {
// :FIXME: Not tested yet.
java.util.Enumeration names =
getServletConfig().getInitParameterNames();
java.util.HashMap map = new java.util.HashMap();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = getServletConfig().getInitParameter(name);
map.put(name,value);
}
return map;
}
// -------------------------------------------------------------- Logging
/**
* The logging level for this servlet.
*/
private int logLevel = Log.ERROR;
/**
* Return the logging level for this servlet.
*
* @return The logging level for this servlet.
*/
public int getLogLevel() {
return this.logLevel;
}
/**
* Set the logging detail level for this servlet.
*
* @param logLevel The new logging level for this servlet.
*/
public void setLogLevel(int logLevel) {
this.logLevel = logLevel;
}
/**
* Is logging set this level or higher?
*
* @param level The debug level to test
*/
protected boolean isLogLevel(int level) {
return (getLogLevel()>=level);
}
/**
* Is logging set to debugging?
*/
protected boolean isDebug() {
return (getLogLevel()>=Log.DEBUG);
}
/**
* Is logging set to verbose?
*/
protected boolean isVerbose() {
return (getLogLevel()>=Log.VERBOSE);
}
/**
* Log the specified message if the current debugging detail level for
* this servlet has been set to an equal or higher value.
* Otherwise, ignore this message.
*
* @param message Message to be logged
* @param level Debugging detail level of this message
*/
public void log(
String message,
int level) {
if (isLogLevel(level)) log(message);
}
/**
* Initialize the debugging detail level for this application servlet..
*
* @fixme Add digester, commons logging features.
* @exception ServletException if we cannot initialize these resources
*/
protected void initLogging() throws ServletException {
String logLevel = getServletConfig().getInitParameter(Log.LOG_LEVEL_PARAMETER);
// :FIXME: Add digester, commons logging features
// String digesterLevel = getServletConfig().getInitParameter(Log.DIGESTER_LEVEL_PARAMETER);
try {
setLogLevel(Integer.parseInt(logLevel));
}
catch (Throwable t) {
setLogLevel(Log.ERROR);
}
}
protected void destroyLogging() {
// override to provide funcationality if needed
}
// ---------------------------------------------------- Internal Messages
// :TODO: Add a message resource bundle for internal messages
/*
protected MessageResources internal = null;
protected String internalName = "org.apache.struts.action.ActionResources";
...
try {
internal = MessageResources.getMessageResources(internalName);
} catch (MissingResourceException e) {
log.error("Cannot load internal resources from '" + internalName + "'",
e);
throw new UnavailableException
("Cannot load internal resources from '" + internalName + "'");
}
...
log.error(internal.getMessage("dataSource.init", dscs[i].getKey()), t);
*/
// -------------------------------------------------- Internal Properties
/**
* The parameter to check for a new path to the default properties
* ["default"].
*/
private static final String DEFAULT_PARAMETER =
"default";
/**
* The default path to use if parameter is not set
*["resources/default.properties"].
*/
private static final String DEFAULT_PATH =
"resources/default.properties";
/**
* The default attribute for the application properties.
* The properties are exposed in the servlet context
* under this attribute name
* [lang.Tokens.PROPERTIES_KEY].
*/
private static final String DEFAULT_ATTRIBUTE =
org.apache.commons.scaffold.lang.Tokens.PROPERTIES_KEY;
/**
* Message for verbose logging.
*/
private static final String RESOURCE_LOADING =
"Loading resources from path: ";
/**
* Message to log if resource is not found.
*/
private static final String RESOURCE_NOT_FOUND =
"Resources not found";
/**
* Our default properties object.
* <p>
* The default properties can be used to store applications
* settings that do not need to be localized and may
* not even be displayed to the user.
*/
Properties properties = null;
/**
* Set the default properties object.
*/
public void setProperties(Properties properties) {
this.properties = properties;
}
/**
* Return the default properties object.
*
* @return The default properties object
*/
public Properties getProperties() {
return this.properties;
}
/**
* A utility method for loading a Properties file
* specified by an initialization parameter.
*
* The initialization parameter should specify the
* package and folder for the Properties in system
* path format (resources/custom.properties).
*
* @param parameter The name of the initialization
* parameter
* @param defaultPath The path to use if the
* parameter is not found
* @param attribute If not null, store in
* application scope under this attribute name
*/
public Properties loadProperties(
String parameter,
String defaultPath,
String attribute) throws ServletException {
String path = getInitString(parameter,defaultPath);
if (isVerbose()) {
log(RESOURCE_LOADING);
log(path);
}
InputStream is = null;
is = this.getClass().getClassLoader().getResourceAsStream(path);
if (null==is)
throw new UnavailableException(RESOURCE_NOT_FOUND);
Properties p = null;
BufferedInputStream bis = new BufferedInputStream(is);
try {
p = new Properties();
p.load(bis);
bis.close();
is.close();
}
catch (IOException e) {
p = null;
}
finally {
is = null;
bis = null;
}
if ((null!=p) && (null!=attribute)) {
this.getServletContext().setAttribute(attribute,p);
}
return p;
}
/**
* Initialize the default properties for this application.
* <p>
* Use the <code>default</code> initialization parameter to specify
* another path. Otherwise ["resources/default.properties"] is used.
* <p>
* If the default properties will not be used or specified,
* override this method with one that does not try to load the
* default properties.
*
* @exception IOException if an input/output error is encountered
* @exception ServletException if we cannot initialize these resources
* @todo The PROPERTIES_KEY could be made configurable,
* but the BaseAction would need to be notified.
*/
protected void initDefault() throws IOException, ServletException {
// :TODO: The PROPERTIES_KEY could be made configurable
// :TODO: but the BaseAction would need to be notified.
setProperties(loadProperties(DEFAULT_PARAMETER, DEFAULT_PATH,
DEFAULT_ATTRIBUTE));
}
/**
* Release any default resources created at initialization
*/
protected void destroyDefault() {
setProperties(null);
}
// -------------------------------------------------- HttpServlet Methods
private static final String INIT_FAILED_EVENT =
"ResourceServlet: init() failed.";
/**
* Initialize this servlet by caling three extension points:
* <ul>
* <li><code>initLogging</code></li>
* <li><code>initDefault</code></li>
* <li><code>initCustom</code></li>
* </ul>
* The main extension point is <code><b>initCustom</b></code>
* The default implementation does nothing.
* The other two methods have reasonable default behaviors that most
* subclasses could use as-is.
* This may be called again from <code>reload</code> and should be
* "re-enterant".
*
* @exception ServletException if we cannot configure ourselves
* correctly
*/
public void init() throws ServletException {
try {
initLogging();
initDefault();
// initMessages();
initCustom();
}
catch (IOException e) {
throw new UnavailableException(INIT_FAILED_EVENT);
}
}
/**
* Message for verbose logging.
*/
public static final String DESTROY_EVENT = "Destroying ResourceServlet";
/**
* Gracefully shut down this controller servlet, releasing any resources
* that were allocated at initialization.
*/
public void destroy() {
if (isVerbose()) log(DESTROY_EVENT);
destroyCustom();
// destroyMessages();
destroyDefault();
destroyLogging();
}
// ------------------------------------------------------ Extension Points
/**
* Initialize the custom properties or objects for this application.
*
* @exception IOException if an input/output error is encountered
* @exception ServletException if we cannot initialize these resources
*/
protected void initCustom() throws IOException, ServletException {
// Override with custom initializations
}
/**
* Release any custom resources created at initialization
*/
protected void destroyCustom() {
// override to provide functionality if needed
}
// ------------------------------------------------------- Public Methods
/**
* Message for verbose logging.
*/
public static final String RELOAD_EVENT =
"Reloading ResourceServlet";
/**
* Reload the configuration of this controller servlet from our
* underlying configuration files.
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void reload() throws IOException, ServletException {
if (logLevel >= Log.VERBOSE) log(RELOAD_EVENT);
// Re-initialize
init();
}
} // end ResourceServlet
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/http/HttpClient.java
Index: HttpClient.java
===================================================================
package org.apache.commons.scaffold.http;
import java.net.*;
import java.io.*;
/**
* A network client that reads from a HTTP URL.
* <P>
* Taken from Core Servlets and JavaServer Pages
* from Prentice Hall and Sun Microsystems Press,
* http://www.coreservlets.com/.
* © 2000 Marty Hall; may be freely used or adapted.
* <P>
* Adapted for general use by a servlet to read a page
* into a StringBuffer by Ted Husted, August 2001.
*
* @author Marty Hall
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:50:28 $
*/
public class HttpClient {
/**
* Retrieve indicated page, returning headers and
* page content.
*
* @params host
* @params port
* @params requestLine
* @params requestHeaders
* @params content
* @exception Catches IOException and UnknownHostException,
* and returns messages in content.
* @author Marty Hall
* @author Ted Husted
* @version $Revision: 1.1 $ $Date: 2002/08/14 17:50:28 $
*/
public HttpClient(
String host, int port,
String requestLine, String[] requestHeaders,
StringBuffer responseHeaders, StringBuffer responseContent)
throws UnknownHostException,IOException {
// check host and connect - Will succeed or throw UHE
InetAddress.getByName(host);
Socket uriSocket = new Socket(host,port);
// handleConnection - May throw IOE
PrintWriter out = SocketUtil.getWriter(uriSocket);
BufferedReader in = SocketUtil.getReader(uriSocket);
// say howdy
out.println(requestLine);
// send any headers, and then blank
for(int i=0; i<requestHeaders.length; i++) {
if (requestHeaders[i] == null)
break;
else
out.println(requestHeaders[i]);
}
out.println();
// capture response
String line;
// - headers
while ((line = in.readLine()) != null) {
responseHeaders.append(line + "\n");
if ("".equals(line)) break;
}
// - content
while ((line = in.readLine()) != null)
responseContent.append(line + "\n");
}
}
1.1 jakarta-commons-sandbox/scaffold/src/java/org/apache/commons/scaffold/http/ConnectionServlet.java
Index: ConnectionServlet.java
===================================================================
package org.apache.commons.scaffold.http;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletException;
import org.apache.commons.scaffold.http.ResourceServlet;
import org.apache.commons.scaffold.sql.ConnectionAdaptor;
import org.apache.commons.scaffold.sql.ServletAdaptor;
/**
* Initialize a <code>ConnectionAdaptor</code> for this application.
* <p>
* The servlet itself is <b>not</b> involved in managing the connection.
* The ConnectionAdaptor is a standalone object.
* This servlet simply provides a means to initialize and load a
* ConnectionAdaptor for use by your application.
* <p>
* This servlet can be configured to use an alternate adaptor or
* adaptor key using initialization parameters:
* <p>
* <b>adaptor</b> The default adaptor is
* <code>org.apache.scaffold.sql.ConnectionAdaptor</code>.
* Any sublcass of ConnectionAdaptor can be specified instead.
* <p>
* <b>adaptor.key</b> The default adaptor key is <code>DATA_SOURCE</code>.
* Another key can be specified instead. This is the attribute to use
* when looking up the datasource in JNDI, the servlet context, or
* whatever.
* <p>
* To use the Struts generic connection pool, specify the adaptor as
* <code>org.apache.scaffold.sql.ServletAdaptor</code> and the
* adaptor.key as <code>org.apache.struts.action.DATA_SOURCE</code>
* <p>
* To use the Resin connection pool, specify the <b>res-ref-name</b>
* in the Resin conf as the <b>adaptor.key</b>.
* <p>
* To use Poolman without JNDI, use the Poolman adaptor in the
* sql package, and specify the dbName from the poolman.xml as the
* <b>adaptor.key</b>
*
* @see org.apache.scaffold.sql.ConnectionAdaptor
* @see org.apache.scaffold.sql.Servletdaptor
* @see org.apache.scaffold.sql.PoolmanAdaptor
*/
public class ConnectionServlet extends ResourceServlet {
/**
* Message for verbose logging.
*/
private static String ADAPTOR_LOADING_EVENT = "Loading ConnectionAdaptor";
/**
* Message to log if connector initialization fails.
*/
private static String ADAPTOR_FAILED_EVENT =
"*** ConnectionAdaptor failed to load: ";
/**
* Default parameter for setting a custom adaptor type
* in the servlet configuration.
*/
private static String ADAPTOR_PARAMETER = "adaptor";
/**
* Default type to use if parameter not set
* ["org.apache.scaffold.sql.ConnectionAdaptor"].
*/
private static String ADAPTOR_DEFAULT =
"org.apache.commons.scaffold.sql.ConnectionAdaptor";
/**
* Default parameter for setting the default attribute
* name, or key, used to retrieve the datasource.
* <p>
* For the Struts generic connection pool, you would set
* this to "org.apache.struts.action.DATA_SOURCE"
* [Action.DATA_SOURCE_KEY].
*/
private static String ADAPTOR_KEY = "adaptor.key";
/**
* Field to hold our instance of the connection adaptor.
* Can be initialized to another ConnectionAdaptor at startup.
*/
private static ConnectionAdaptor adaptor;
/**
* Initialize the ConnectionAdaptor for this application.
* <p>
* An alternate ConnectionAdaptor can be specified in the servlet config
* by specifying the class type as the <b>adaptor</b> initialization
* parameter.
*
* @exception IOException if an input/output error is encountered
* @exception ServletException if we cannot initialize these resources
*/
protected void initDefault() throws IOException, ServletException {
super.initDefault();
if (isVerbose()) log(ADAPTOR_LOADING_EVENT);
// Check for an adaptor parameter
String adaptorClass =
getInitString(ADAPTOR_PARAMETER,ADAPTOR_DEFAULT);
// Create the default or custom adaptor
try {
adaptor = (ConnectionAdaptor)
Class.forName(adaptorClass).newInstance();
}
catch (Throwable t) {
log(ADAPTOR_FAILED_EVENT,t);
t.printStackTrace();
throw new ServletException(t);
}
// Check for an adaptor key
String key = getInitString(ADAPTOR_KEY,null);
if (null!=key) adaptor.setKey(key);
// ** kludge alert **
// If its a servlet adaptor, give it a servlet reference
if (adaptor instanceof ServletAdaptor) {
// Give adaptor access to servlet context.
ServletAdaptor s = (ServletAdaptor) adaptor;
s.setServlet(this);
}
}
} // end ConnectionServlet
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>