JBossWeb SVN: r1417 - trunk/java/org/apache/tomcat/util/http/mapper.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-24 12:45:25 -0400 (Wed, 24 Mar 2010)
New Revision: 1417
Modified:
trunk/java/org/apache/tomcat/util/http/mapper/Mapper.java
Log:
- Throw ISE when there's an error when adding a bad context or wrapper.
Modified: trunk/java/org/apache/tomcat/util/http/mapper/Mapper.java
===================================================================
--- trunk/java/org/apache/tomcat/util/http/mapper/Mapper.java 2010-03-20 17:05:33 UTC (rev 1416)
+++ trunk/java/org/apache/tomcat/util/http/mapper/Mapper.java 2010-03-24 16:45:25 UTC (rev 1417)
@@ -17,14 +17,15 @@
package org.apache.tomcat.util.http.mapper;
+import java.util.ArrayList;
+import java.util.List;
+
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
+import org.apache.tomcat.util.buf.Ascii;
import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.MessageBytes;
-import org.apache.tomcat.util.buf.Ascii;
-import java.util.List;
-import java.util.ArrayList;
/**
* Mapper, which implements the servlet API mapping rules (which are derived
@@ -35,8 +36,6 @@
public final class Mapper {
- private static org.jboss.logging.Logger logger =
- org.jboss.logging.Logger.getLogger(Mapper.class);
// ----------------------------------------------------- Instance Variables
@@ -224,7 +223,7 @@
pos = find(hosts, hostName);
}
if (pos < 0) {
- logger.error("No host found: " + hostName);
+ throw new IllegalStateException("No host found: " + hostName);
}
Host host = hosts[pos];
if (host.name.equals(hostName)) {
@@ -268,7 +267,7 @@
pos = find(hosts, hostName);
}
if (pos < 0) {
- logger.error("No host found: " + hostName);
+ throw new IllegalStateException("No host found: " + hostName);
}
Host host = hosts[pos];
if (host.name.equals(hostName)) {
@@ -341,19 +340,17 @@
* @return The context names
*/
public String[] getContextNames() {
- List list=new ArrayList();
- for( int i=0; i<hosts.length; i++ ) {
- for( int j=0; j<hosts[i].contextList.contexts.length; j++ ) {
- String cname=hosts[i].contextList.contexts[j].name;
- list.add("//" + hosts[i].name +
- (cname.startsWith("/") ? cname : "/"));
+ List<String> list = new ArrayList<String>();
+ for (int i = 0; i < hosts.length; i++) {
+ for (int j = 0; j < hosts[i].contextList.contexts.length; j++) {
+ String cname = hosts[i].contextList.contexts[j].name;
+ list.add("//" + hosts[i].name
+ + (cname.startsWith("/") ? cname : "/"));
}
}
- String res[] = new String[list.size()];
- return (String[])list.toArray(res);
+ return list.toArray(new String[list.size()]);
}
-
/**
* Add a new Wrapper to an existing Context.
*
@@ -380,8 +377,7 @@
Context[] contexts = host.contextList.contexts;
int pos2 = find(contexts, contextPath);
if( pos2<0 ) {
- logger.error("No context found: " + contextPath );
- return;
+ throw new IllegalStateException("No context found: " + contextPath );
}
Context context = contexts[pos2];
if (context.name.equals(contextPath)) {
@@ -565,36 +561,36 @@
return sb.toString();
}
- public String[] getWrapperNames( String host, String context ) {
- List list=new ArrayList();
- if( host==null ) host="";
- if( context==null ) context="";
- for( int i=0; i<hosts.length; i++ ) {
- if( ! host.equals( hosts[i].name ))
+ public String[] getWrapperNames(String host, String context) {
+ List<String> list = new ArrayList<String>();
+ if (host == null)
+ host = "";
+ if (context == null)
+ context = "";
+ for (int i = 0; i < hosts.length; i++) {
+ if (!host.equals(hosts[i].name))
continue;
- for( int j=0; j<hosts[i].contextList.contexts.length; j++ ) {
- if( ! context.equals( hosts[i].contextList.contexts[j].name))
+ for (int j = 0; j < hosts[i].contextList.contexts.length; j++) {
+ if (!context.equals(hosts[i].contextList.contexts[j].name))
continue;
// found the context
- Context ctx=hosts[i].contextList.contexts[j];
- list.add( ctx.defaultWrapper.name);
- for( int k=0; k<ctx.exactWrappers.length; k++ ) {
- list.add( ctx.exactWrappers[k].name);
+ Context ctx = hosts[i].contextList.contexts[j];
+ list.add(ctx.defaultWrapper.name);
+ for (int k = 0; k < ctx.exactWrappers.length; k++) {
+ list.add(ctx.exactWrappers[k].name);
}
- for( int k=0; k<ctx.wildcardWrappers.length; k++ ) {
- list.add( ctx.wildcardWrappers[k].name + "*");
+ for (int k = 0; k < ctx.wildcardWrappers.length; k++) {
+ list.add(ctx.wildcardWrappers[k].name + "*");
}
- for( int k=0; k<ctx.extensionWrappers.length; k++ ) {
- list.add( "*." + ctx.extensionWrappers[k].name);
+ for (int k = 0; k < ctx.extensionWrappers.length; k++) {
+ list.add("*." + ctx.extensionWrappers[k].name);
}
}
}
- String res[]=new String[list.size()];
- return (String[])list.toArray(res);
+ return list.toArray(new String[list.size()]);
}
-
/**
* Map the specified host name and URI, mutating the given mapping data.
*
14 years, 9 months
JBossWeb SVN: r1416 - trunk/java/org/apache/naming/resources.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-20 13:05:33 -0400 (Sat, 20 Mar 2010)
New Revision: 1416
Modified:
trunk/java/org/apache/naming/resources/DirContextURLConnection.java
Log:
- connect() may not be using the same path as the other methods.
Modified: trunk/java/org/apache/naming/resources/DirContextURLConnection.java
===================================================================
--- trunk/java/org/apache/naming/resources/DirContextURLConnection.java 2010-03-18 15:36:46 UTC (rev 1415)
+++ trunk/java/org/apache/naming/resources/DirContextURLConnection.java 2010-03-20 17:05:33 UTC (rev 1416)
@@ -115,6 +115,12 @@
*/
protected Permission permission;
+
+ /**
+ * Local path.
+ */
+ protected String localPath;
+
// ------------------------------------------------------------- Properties
@@ -152,6 +158,7 @@
}
}
}
+ localPath = path;
object = context.lookup(path);
attributes = context.getAttributes(path);
if (object instanceof Resource)
@@ -363,7 +370,7 @@
} else {
// Reopen resource
try {
- resource = (Resource) context.lookup(getURL().getFile());
+ resource = (Resource) context.lookup(localPath);
} catch (NamingException e) {
}
}
@@ -404,7 +411,7 @@
if (collection != null) {
try {
- NamingEnumeration enumeration = context.list(getURL().getFile());
+ NamingEnumeration enumeration = context.list(localPath);
while (enumeration.hasMoreElements()) {
NameClassPair ncp = (NameClassPair) enumeration.nextElement();
result.addElement(ncp.getName());
14 years, 9 months
JBossWeb SVN: r1415 - tags.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-18 11:36:46 -0400 (Thu, 18 Mar 2010)
New Revision: 1415
Added:
tags/JBOSSWEB_3_0_0_BETA3/
Log:
- JBoss Web 3 beta 3.
Copied: tags/JBOSSWEB_3_0_0_BETA3 (from rev 1414, trunk)
14 years, 9 months
JBossWeb SVN: r1414 - trunk/java/org/apache/jasper/compiler.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-18 08:51:25 -0400 (Thu, 18 Mar 2010)
New Revision: 1414
Modified:
trunk/java/org/apache/jasper/compiler/JspUtil.java
trunk/java/org/apache/jasper/compiler/PageInfo.java
Log:
- Use ExpressionFactory.newInstance().
Modified: trunk/java/org/apache/jasper/compiler/JspUtil.java
===================================================================
--- trunk/java/org/apache/jasper/compiler/JspUtil.java 2010-03-17 13:30:11 UTC (rev 1413)
+++ trunk/java/org/apache/jasper/compiler/JspUtil.java 2010-03-18 12:51:25 UTC (rev 1414)
@@ -27,12 +27,9 @@
import java.util.zip.ZipEntry;
import javax.el.FunctionMapper;
-import javax.servlet.jsp.el.ExpressionEvaluator;
-import org.apache.el.ExpressionFactoryImpl;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
-import org.apache.jasper.el.ExpressionEvaluatorImpl;
import org.xml.sax.Attributes;
/**
@@ -61,8 +58,8 @@
//= new ExpressionEvaluatorImpl();
//tc6
- private final static ExpressionEvaluator expressionEvaluator =
- new ExpressionEvaluatorImpl(new ExpressionFactoryImpl());
+ //private final static ExpressionEvaluator expressionEvaluator =
+ // new ExpressionEvaluatorImpl(ExpressionFactory.newInstance());
private static final String javaKeywords[] = {
"abstract", "assert", "boolean", "break", "byte", "case",
Modified: trunk/java/org/apache/jasper/compiler/PageInfo.java
===================================================================
--- trunk/java/org/apache/jasper/compiler/PageInfo.java 2010-03-17 13:30:11 UTC (rev 1413)
+++ trunk/java/org/apache/jasper/compiler/PageInfo.java 2010-03-18 12:51:25 UTC (rev 1414)
@@ -28,7 +28,6 @@
import javax.el.ExpressionFactory;
import javax.servlet.jsp.tagext.TagLibraryInfo;
-import org.apache.el.ExpressionFactoryImpl;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
@@ -77,7 +76,7 @@
// JSP 2.1
private String deferredSyntaxAllowedAsLiteralValue;
private boolean deferredSyntaxAllowedAsLiteral = false;
- private ExpressionFactory expressionFactory = new ExpressionFactoryImpl();
+ private ExpressionFactory expressionFactory = ExpressionFactory.newInstance();
private String trimDirectiveWhitespacesValue;
private boolean trimDirectiveWhitespaces = false;
14 years, 9 months
JBossWeb SVN: r1413 - branches/2.1.x/java/org/apache/tomcat/util/buf.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-17 09:30:11 -0400 (Wed, 17 Mar 2010)
New Revision: 1413
Modified:
branches/2.1.x/java/org/apache/tomcat/util/buf/B2CConverter.java
branches/2.1.x/java/org/apache/tomcat/util/buf/C2BConverter.java
Log:
- JBAS-7817: unsafe use of position(). This API is very strict here.
Modified: branches/2.1.x/java/org/apache/tomcat/util/buf/B2CConverter.java
===================================================================
--- branches/2.1.x/java/org/apache/tomcat/util/buf/B2CConverter.java 2010-03-17 12:21:39 UTC (rev 1412)
+++ branches/2.1.x/java/org/apache/tomcat/util/buf/B2CConverter.java 2010-03-17 13:30:11 UTC (rev 1413)
@@ -81,8 +81,8 @@
bb = ByteBuffer.wrap(bc.getBuffer(), bc.getStart(), bc.getLength());
} else {
// Initialize the byte buffer
+ bb.limit(bc.getEnd());
bb.position(bc.getStart());
- bb.limit(bc.getEnd());
}
if ((cb == null) || (cb.array() != cc.getBuffer())) {
// Create a new char buffer if anything changed
@@ -90,8 +90,8 @@
cc.getBuffer().length - cc.getEnd());
} else {
// Initialize the char buffer
+ cb.limit(cc.getBuffer().length);
cb.position(cc.getEnd());
- cb.limit(cc.getBuffer().length);
}
CoderResult result = null;
// Parse leftover if any are present
@@ -126,8 +126,8 @@
cc.setEnd(cb.position());
// Put leftovers in the leftovers byte buffer
if (bc.getLength() > 0) {
+ leftovers.limit(leftovers.array().length);
leftovers.position(bc.getLength());
- leftovers.limit(leftovers.array().length);
bc.substract(leftovers.array(), 0, bc.getLength());
}
}
Modified: branches/2.1.x/java/org/apache/tomcat/util/buf/C2BConverter.java
===================================================================
--- branches/2.1.x/java/org/apache/tomcat/util/buf/C2BConverter.java 2010-03-17 12:21:39 UTC (rev 1412)
+++ branches/2.1.x/java/org/apache/tomcat/util/buf/C2BConverter.java 2010-03-17 13:30:11 UTC (rev 1413)
@@ -75,8 +75,8 @@
bc.getBuffer().length - bc.getEnd());
} else {
// Initialize the byte buffer
+ bb.limit(bc.getBuffer().length);
bb.position(bc.getEnd());
- bb.limit(bc.getBuffer().length);
}
if ((cb == null) || (cb.array() != cc.getBuffer())) {
// Create a new char buffer if anything changed
@@ -84,8 +84,8 @@
cc.getLength());
} else {
// Initialize the char buffer
+ cb.limit(cc.getEnd());
cb.position(cc.getStart());
- cb.limit(cc.getEnd());
}
// Do the decoding and get the results into the byte chunk and the char chunk
CoderResult result = encoder.encode(cb, bb, false);
14 years, 9 months
JBossWeb SVN: r1412 - in trunk: webapps/docs and 1 other directory.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-17 08:21:39 -0400 (Wed, 17 Mar 2010)
New Revision: 1412
Modified:
trunk/java/org/apache/tomcat/util/buf/B2CConverter.java
trunk/java/org/apache/tomcat/util/buf/C2BConverter.java
trunk/webapps/docs/changelog.xml
Log:
- JBAS-7817: unsafe use of position(). This API is very strict here.
Modified: trunk/java/org/apache/tomcat/util/buf/B2CConverter.java
===================================================================
--- trunk/java/org/apache/tomcat/util/buf/B2CConverter.java 2010-03-16 14:48:04 UTC (rev 1411)
+++ trunk/java/org/apache/tomcat/util/buf/B2CConverter.java 2010-03-17 12:21:39 UTC (rev 1412)
@@ -81,8 +81,8 @@
bb = ByteBuffer.wrap(bc.getBuffer(), bc.getStart(), bc.getLength());
} else {
// Initialize the byte buffer
+ bb.limit(bc.getEnd());
bb.position(bc.getStart());
- bb.limit(bc.getEnd());
}
if ((cb == null) || (cb.array() != cc.getBuffer())) {
// Create a new char buffer if anything changed
@@ -90,8 +90,8 @@
cc.getBuffer().length - cc.getEnd());
} else {
// Initialize the char buffer
+ cb.limit(cc.getBuffer().length);
cb.position(cc.getEnd());
- cb.limit(cc.getBuffer().length);
}
CoderResult result = null;
// Parse leftover if any are present
@@ -126,8 +126,8 @@
cc.setEnd(cb.position());
// Put leftovers in the leftovers byte buffer
if (bc.getLength() > 0) {
+ leftovers.limit(leftovers.array().length);
leftovers.position(bc.getLength());
- leftovers.limit(leftovers.array().length);
bc.substract(leftovers.array(), 0, bc.getLength());
}
}
Modified: trunk/java/org/apache/tomcat/util/buf/C2BConverter.java
===================================================================
--- trunk/java/org/apache/tomcat/util/buf/C2BConverter.java 2010-03-16 14:48:04 UTC (rev 1411)
+++ trunk/java/org/apache/tomcat/util/buf/C2BConverter.java 2010-03-17 12:21:39 UTC (rev 1412)
@@ -75,8 +75,8 @@
bc.getBuffer().length - bc.getEnd());
} else {
// Initialize the byte buffer
+ bb.limit(bc.getBuffer().length);
bb.position(bc.getEnd());
- bb.limit(bc.getBuffer().length);
}
if ((cb == null) || (cb.array() != cc.getBuffer())) {
// Create a new char buffer if anything changed
@@ -84,8 +84,8 @@
cc.getLength());
} else {
// Initialize the char buffer
+ cb.limit(cc.getEnd());
cb.position(cc.getStart());
- cb.limit(cc.getEnd());
}
// Do the decoding and get the results into the byte chunk and the char chunk
CoderResult result = encoder.encode(cb, bb, false);
Modified: trunk/webapps/docs/changelog.xml
===================================================================
--- trunk/webapps/docs/changelog.xml 2010-03-16 14:48:04 UTC (rev 1411)
+++ trunk/webapps/docs/changelog.xml 2010-03-17 12:21:39 UTC (rev 1412)
@@ -53,6 +53,10 @@
<fix>
<bug>48545</bug>: Optional password on truststores. (markt)
</fix>
+ <fix>
+ <jboss-jira>JBAS-7817</jboss-jira>: Use of position before setting the limit of a NIO buffer
+ is unsafe. (remm)
+ </fix>
</changelog>
</subsection>
<subsection name="Jasper">
14 years, 9 months
JBossWeb SVN: r1411 - trunk.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-16 10:48:04 -0400 (Tue, 16 Mar 2010)
New Revision: 1411
Removed:
trunk/RUNNING.txt
trunk/dist.xml
Modified:
trunk/NOTICE
trunk/build.properties.default
trunk/build.xml
Log:
- Remove some additional standalone elements.
Modified: trunk/NOTICE
===================================================================
--- trunk/NOTICE 2010-03-12 18:44:44 UTC (rev 1410)
+++ trunk/NOTICE 2010-03-16 14:48:04 UTC (rev 1411)
@@ -1,8 +1,8 @@
JBoss Web
-Copyright 2006-2009 Red Hat Middleware, LLC. All rights reserved.
+Copyright 2006-2010 Red Hat Middleware, LLC. All rights reserved.
Apache Tomcat
-Copyright 1999-2009 The Apache Software Foundation
+Copyright 1999-2010 The Apache Software Foundation
Servlet API 3.0
Copyright 1997-2009 Sun Microsystems, Inc
Deleted: trunk/RUNNING.txt
===================================================================
--- trunk/RUNNING.txt 2010-03-12 18:44:44 UTC (rev 1410)
+++ trunk/RUNNING.txt 2010-03-16 14:48:04 UTC (rev 1411)
@@ -1,148 +0,0 @@
-
- ===========================================
- Running The JBoss Web Servlet/JSP Container
- ===========================================
-
-JBoss Web requires the Java 2 Standard Edition Runtime
-Environment (JRE) version 5.0 or later.
-
-=============================
-Running With JRE 5.0 Or Later
-=============================
-
-(1) Download and Install the J2SE Runtime Environment (JRE)
-
-(1.1) Download the Java 2 Standard Edition Runtime Environment (JRE),
- release version 5.0 or later, from http://java.sun.com/j2se.
-
-(1.2) Install the JRE according to the instructions included with the
- release.
-(1.3) Set an environment variable named JRE_HOME to the pathname of
- the directory into which you installed the JRE, e.g. c:\jre5.0
- or /usr/local/java/jre5.0.
-
-NOTE: You may also use the full JDK rather than just the JRE. In this
- case set your JAVA_HOME environment variable to the pathname of
- the directory into which you installed the JDK, e.g. c:\j2sdk5.0
- or /usr/local/java/j2sdk5.0.
-
-
-(2) Download and Install the JBoss Web Binary Distribution
-
-NOTE: As an alternative to downloading a binary distribution, you can create
-your own from the JBoss Web source repository, as described in "BUILDING.txt".
-If you do this, the value to use for "${catalina.home}" will be the "dist"
-subdirectory of your source distribution.
-
-(2.1) Download a binary distribution of JBoss Web from:
-
- http://labs.jboss.com/jbossweb/
-
-(2.2) Unpack the binary distribution into a convenient location so that the
- distribution resides in its own directory (conventionally named
- "jboss-web-[version]"). For the purposes of the remainder of this document,
- the symbolic name "$CATALINA_HOME" is used to refer to the full
- pathname of the release directory.
-
-
-(3) Start Up JBoss Web
-
-(3.1) JBoss Web can be started by executing the following commands:
-
- $CATALINA_HOME\bin\startup.bat (Windows)
-
- $CATALINA_HOME/bin/startup.sh (Unix)
-
-(3.2) After startup, the default web applications included with JBoss Web will be
- available by visiting:
-
- http://localhost:8080/
-
-(3.3) Further information about configuring and running JBoss Web can be found in
- the documentation included here, as well as on the JBoss Web web site:
-
- http://labs.jboss.com/jbossweb/
-
-
-(4) Shut Down JBoss Web
-
-(4.1) JBoss Web can be shut down by executing the following command:
-
- $CATALINA_HOME\bin\shutdown (Windows)
-
- $CATALINA_HOME/bin/shutdown.sh (Unix)
-
-
-=====================================================
-Advanced Configuration - Multiple JBoss Web Instances
-=====================================================
-
-In many circumstances, it is desirable to have a single copy of a JBoss Web
-binary distribution shared among multiple users on the same server. To make
-this possible, you can pass a "-Dcatalina.base=$CATALINA_BASE" argument when
-executing the startup command (see (2)). In this
-"-Dcatalina.base=$CATALINA_BASE" argument, replace $CATALINA_BASE with the
-directory that contains the files for your 'personal' JBoss Web instance.
-
-When you use this "-Dcatalina.base=$CATALINA_BASE" argument, JBoss Web will
-calculate all relative references for files in the following directories based
-on the value of $CATALINA_BASE instead of $CATALINA_HOME:
-
-* bin - Only setenv.sh (*nix) and setenv.bat (windows)
-
-* conf - Server configuration files (including server.xml)
-
-* logs - Log and output files
-
-* lib - For classes and resources that must be shared across all web
- applications
-
-* webapps - Automatically loaded web applications
-
-* work - Temporary working directories for web applications
-
-* temp - Directory used by the JVM for temporary files (java.io.tmpdir)
-
-If you do not pass the "-Dcatalina.base=$CATALINA_BASE" argument to the
-startup command, $CATALINA_BASE will default to the same value as $CATALINA_HOME,
- which means that the same directory is used for all relative path resolutions.
-
-
-================
-Troubleshooting
-================
-
-There are only really 3 things likely to go wrong during the stand-alone
-JBoss Web install:
-
-(1) The most common hiccup is when another web server (or any process for that
- matter) has laid claim to port 8080. This is the default HTTP port that
- JBoss Web attempts to bind to at startup. To change this, open the file:
-
- $CATALINA_HOME/conf/server.xml
-
- and search for '8080'. Change it to a port that isn't in use, and is
- greater than 1024, as ports less than or equal to 1024 require superuser
- access to bind under UNIX.
-
- Restart JBoss Web and you're in business. Be sure that you replace the "8080"
- in the URL you're using to access JBoss Web. For example, if you change the
- port to 1977, you would request the URL http://localhost:1977/ in your browser.
-
-(2) An "out of environment space" error when running the batch files in
- Windows 95, 98, or ME operating systems.
-
- Right-click on the STARTUP.BAT and SHUTDOWN.BAT files. Click on
- "Properties", then on the "Memory" tab. For the "Initial environment" field,
- enter in something like 4096.
-
- After you click apply, Windows will create shortcuts which you can use
- to start and stop the container.
-
-(3) The 'localhost' machine isn't found. This could happen if you're behind a
- proxy. If that's the case, make sure the proxy configuration for your
- browser knows that you shouldn't be going through the proxy to access the
- "localhost".
-
- In Netscape, this is under Edit/Preferences -> Advanced/Proxies, and in
- Internet Explorer, Tools -> Internet Options -> Connections -> LAN Settings.
Modified: trunk/build.properties.default
===================================================================
--- trunk/build.properties.default 2010-03-12 18:44:44 UTC (rev 1410)
+++ trunk/build.properties.default 2010-03-16 14:48:04 UTC (rev 1411)
@@ -32,46 +32,12 @@
base-tomcat.loc=http://archive.apache.org/dist/tomcat
base-sf.loc=http://downloads.sourceforge.net
-# ----- Webservices -----
-jaxrpc-src.loc=http://repo1.maven.org/maven2/geronimo-spec/geronimo-spec-jaxrpc/1.1-rc4/geronimo-spec-jaxrpc-1.1-rc4.jar
-wsdl4j-src.loc=http://repo1.maven.org/maven2/wsdl4j/wsdl4j/1.6.1/wsdl4j-1.6.1.jar
-
# ----- Eclipse JDT, version 3.2 or later -----
jdt.home=${base.path}/eclipse/plugins
jdt.lib=${jdt.home}
jdt.jar=${jdt.lib}/org.eclipse.jdt.core_3.4.2.v_883_R34x.jar
jdt.loc=http://download.eclipse.org/eclipse/downloads/drops/R-3.4.1-20080...
-# ----- Commons DBCP, version 1.1 or later -----
-commons-dbcp.version=1.2.2
-commons-dbcp.home=${base.path}/commons-dbcp-1.2.2-src
-commons-dbcp-src.loc=${base-commons.loc}/dbcp/source/commons-dbcp-1.2.2-src.tar.gz
-
-# ----- Commons Pool, version 1.1 or later -----
-commons-pool.home=${base.path}/commons-pool-1.5.2-src
-commons-pool-src.loc=${base-commons.loc}/pool/source/commons-pool-1.5.2-src.tar.gz
-
-# ----- NSIS, version 2.0 or later -----
-nsis.home=${base.path}/nsis-2.44
-nsis.exe=${nsis.home}/makensis.exe
-nsis.installoptions.dll=${nsis.home}/Plugins/InstallOptions.dll
-nsis.nsexec.dll=${nsis.home}/Plugins/nsExec.dll
-nsis.nsisdl.dll=${nsis.home}/Plugins/NSISdl.dll
-nsis.loc=${base-sf.loc}/nsis/nsis-2.44.zip
-
-# ----- JBoss Native, version 2.0 or later -----
-jbossnative.home=${base.path}/jboss-native-2.0.6
-jbossnative.openssl=${jbossnative.home}/bin/META-INF/bin/windows/x86/openssl.exe
-jbossnative.dlls=${jbossnative.home}/bin/META-INF/lib/windows/x86
-jbossnative.loc=http://www.jboss.org/downloading/?projectId=jbossweb&url=http://labs.jboss.com/file-access/default/members/jbossweb/freezone/dist/2.0.6.GA/jboss-native-2.0.6-windows-x86-ssl.zip
-
-# ----- Commons Daemon, version 1.0-Alpha or later -----
-commons-daemon.home=${base.path}/commons-daemon-1.0.1
-commons-daemon.lib=${commons-daemon.home}
-commons-daemon.jar=${commons-daemon.lib}/commons-daemon.jar
-commons-daemon.loc=${base-commons.loc}/daemon/binaries/commons-daemon-1.0.1.tar.gz
-commons-daemon.jsvc.tar.gz=${commons-daemon.lib}/bin/jsvc.tar.gz
-
# ----- Dojo Toolkit (for test webapp) -----
dojo-js.home=${base.path}/dojo-release-1.1.1
dojo-js.loc=http://download.dojotoolkit.org/release-1.1.1/dojo-release-1....
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2010-03-12 18:44:44 UTC (rev 1410)
+++ trunk/build.xml 2010-03-16 14:48:04 UTC (rev 1411)
@@ -1,862 +1,528 @@
<?xml version="1.0"?>
<project name="JBoss Web" default="deploy" basedir=".">
+ <!-- ===================== Initialize Property Values =================== -->
- <!-- ===================== Initialize Property Values =================== -->
+ <!-- See "build.properties.sample" in the top level directory for all -->
+ <!-- property values you must customize for successful building!!! -->
+ <property file="${user.home}/build.properties"/>
+ <property file="build.properties"/>
- <!-- See "build.properties.sample" in the top level directory for all -->
- <!-- property values you must customize for successful building!!! -->
- <property file="${user.home}/build.properties"/>
- <property file="build.properties"/>
+ <property file="build.properties.default"/>
- <property file="build.properties.default"/>
+ <!-- Project Properties -->
+ <property name="name" value="JBoss Web" />
+ <property name="year" value="2010" />
+ <property name="version.major" value="3" />
+ <property name="version.minor" value="0" />
+ <property name="version.build" value="0" />
+ <property name="version.patch" value="0" />
+ <property name="version.tag" value="SNAPSHOT" />
+ <property name="version" value="${version.major}.${version.minor}.${version.build}-${version.tag}" />
+ <property name="version.number" value="${version.major}.${version.minor}.${version.build}.${version.patch}" />
- <!-- Project Properties -->
- <property name="name" value="JBoss Web" />
- <property name="year" value="2009" />
- <property name="version.major" value="3" />
- <property name="version.minor" value="0" />
- <property name="version.build" value="0" />
- <property name="version.patch" value="0" />
- <property name="version.tag" value="SNAPSHOT" />
- <property name="version" value="${version.major}.${version.minor}.${version.build}-${version.tag}" />
- <property name="version.number" value="${version.major}.${version.minor}.${version.build}.${version.patch}" />
+ <property name="project" value="jboss-web" />
+ <property name="final.name" value="${project}-${version}" />
+ <property name="final-src.name" value="${project}-${version}-src" />
- <property name="project" value="jboss-web" />
- <property name="final.name" value="${project}-${version}" />
- <property name="final-src.name" value="${project}-${version}-src" />
+ <!-- Build Defaults -->
+ <property name="tomcat.build" value="${basedir}/output/build"/>
+ <property name="tomcat.classes" value="${basedir}/output/classes"/>
+ <property name="tomcat.dist" value="${basedir}/output/dist"/>
+ <property name="tomcat.jars" value="${basedir}/output/jars"/>
+ <property name="jbossweb.site" value="${basedir}/output/site"/>
+ <property name="test.failonerror" value="true"/>
+ <property name="test.runner" value="junit.textui.TestRunner"/>
- <!-- Build Defaults -->
- <property name="tomcat.build" value="${basedir}/output/build"/>
- <property name="tomcat.classes" value="${basedir}/output/classes"/>
- <property name="tomcat.dist" value="${basedir}/output/dist"/>
- <property name="tomcat.jars" value="${basedir}/output/jars"/>
- <property name="jbossweb.site" value="${basedir}/output/site"/>
- <property name="test.failonerror" value="true"/>
- <property name="test.runner" value="junit.textui.TestRunner"/>
+ <!-- Can't be lower - jsp uses templates -->
+ <property name="compile.source" value="1.6"/>
- <!-- Can't be lower - jsp uses templates -->
- <property name="compile.source" value="1.6"/>
+ <property name="jasper-jdt.home" value="${base.path}/jbossweb-deps/jdt" />
+ <property name="jasper-jdt.jar" value="${jasper-jdt.home}/jasper-jdt.jar"/>
- <!-- JAR artifacts -->
- <property name="bootstrap.jar" value="${tomcat.build}/bin/bootstrap.jar"/>
- <property name="tomcat-juli.jar" value="${tomcat.build}/bin/tomcat-juli.jar"/>
+ <!-- Classpath -->
+ <path id="tomcat.classpath">
+ <fileset dir="${basedir}/lib">
+ <include name="*.jar"/>
+ </fileset>
+ <pathelement path="${jasper-jdt.jar}"/>
+ </path>
- <property name="annotations-api.jar" value="${tomcat.build}/lib/annotations-api.jar"/>
- <property name="servlet-api.jar" value="${tomcat.build}/lib/servlet-api.jar"/>
- <property name="jsp-api.jar" value="${tomcat.build}/lib/jsp-api.jar"/>
- <property name="el-api.jar" value="${tomcat.build}/lib/el-api.jar"/>
- <property name="catalina.jar" value="${tomcat.build}/lib/catalina.jar"/>
- <property name="catalina-ant.jar" value="${tomcat.build}/lib/catalina-ant.jar"/>
- <property name="catalina-optional.jar" value="${tomcat.build}/lib/catalina-optional.jar"/>
- <property name="tomcat-coyote.jar" value="${tomcat.build}/lib/tomcat-coyote.jar"/>
- <property name="tomcat-bayeux.jar" value="${tomcat.build}/lib/tomcat-bayeux.jar"/>
+ <!-- Just build Tomcat -->
+ <target name="build-prepare">
- <property name="jasper.jar" value="${tomcat.build}/lib/jasper.jar"/>
- <property name="jasper-el.jar" value="${tomcat.build}/lib/jasper-el.jar"/>
+ <available classname="junit.framework.TestCase" property="junit.present" />
- <property name="tomcat-dbcp.home" value="${base.path}/jbossweb-deps/dbcp" />
- <property name="jasper-jdt.home" value="${base.path}/jbossweb-deps/jdt" />
- <property name="tomcat-dbcp.jar" value="${tomcat-dbcp.home}/tomcat-dbcp.jar"/>
- <property name="jasper-jdt.jar" value="${jasper-jdt.home}/jasper-jdt.jar"/>
+ <mkdir dir="${tomcat.classes}"/>
- <!-- Classpath -->
- <path id="tomcat.classpath">
- <fileset dir="${basedir}/lib">
- <include name="*.jar"/>
- </fileset>
- <pathelement path="${jasper-jdt.jar}"/>
- </path>
+ <mkdir dir="${tomcat.build}"/>
+ <mkdir dir="${tomcat.build}/webapps"/>
- <!-- Just build Tomcat -->
- <target name="build-prepare">
+ <mkdir dir="${tomcat.jars}"/>
- <available classname="junit.framework.TestCase" property="junit.present" />
+ </target>
- <mkdir dir="${tomcat.classes}"/>
+ <target name="compile">
- <delete dir="${tomcat.build}/temp" />
- <delete dir="${tomcat.build}/work" />
-
- <mkdir dir="${tomcat.build}"/>
- <mkdir dir="${tomcat.build}/bin"/>
- <mkdir dir="${tomcat.build}/conf"/>
- <mkdir dir="${tomcat.build}/lib"/>
- <mkdir dir="${tomcat.build}/logs"/>
- <mkdir dir="${tomcat.build}/temp"/>
- <mkdir dir="${tomcat.build}/webapps"/>
-
- <mkdir dir="${tomcat.jars}"/>
-
- </target>
-
- <target name="compile">
-
- <!-- Compile internal server components -->
- <javac srcdir="java" destdir="${tomcat.classes}"
+ <!-- Compile internal server components -->
+ <javac srcdir="java" destdir="${tomcat.classes}"
debug="${compile.debug}"
optimize="${compile.optimize}"
deprecation="${compile.deprecation}"
source="${compile.source}"
target="${compile.target}"
excludes="**/CVS/**,**/.svn/**">
-<!-- Comment this in to show unchecked warnings: <compilerarg value="-Xlint:unchecked"/> -->
- <classpath refid="tomcat.classpath" />
- </javac>
- <tstamp>
- <format property="TODAY" pattern="MMM d yyyy" locale="en"/>
- <format property="TSTAMP" pattern="hh:mm:ss"/>
- </tstamp>
- <!-- Copy static resource files -->
- <filter token="VERSION" value="${version}"/>
- <filter token="VERSION_NUMBER" value="${version.number}"/>
- <filter token="VERSION_BUILT" value="${TODAY} ${TSTAMP}"/>
- <copy todir="${tomcat.classes}" filtering="true" encoding="ISO-8859-1">
- <fileset dir="java">
- <include name="**/*.properties"/>
- <include name="**/*.dtd"/>
- <include name="**/*.tasks"/>
- <include name="**/*.xsd"/>
- <include name="**/*.xml"/>
- </fileset>
- </copy>
+ <!-- Comment this in to show unchecked warnings: <compilerarg value="-Xlint:unchecked"/> -->
+ <classpath refid="tomcat.classpath" />
+ </javac>
+ <tstamp>
+ <format property="TODAY" pattern="MMM d yyyy" locale="en"/>
+ <format property="TSTAMP" pattern="hh:mm:ss"/>
+ </tstamp>
+ <!-- Copy static resource files -->
+ <filter token="VERSION" value="${version}"/>
+ <filter token="VERSION_NUMBER" value="${version.number}"/>
+ <filter token="VERSION_BUILT" value="${TODAY} ${TSTAMP}"/>
+ <copy todir="${tomcat.classes}" filtering="true" encoding="ISO-8859-1">
+ <fileset dir="java">
+ <include name="**/*.properties"/>
+ <include name="**/*.dtd"/>
+ <include name="**/*.tasks"/>
+ <include name="**/*.xsd"/>
+ <include name="**/*.xml"/>
+ </fileset>
+ </copy>
- </target>
+ </target>
- <target name="build-only" depends="build-prepare,compile,package" />
+ <target name="build-only" depends="build-prepare,compile" />
- <target name="package" >
+ <target name="build-docs">
- <!-- Common Annotations 1.1 JAR File -->
- <jar jarfile="${annotations-api.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="javax/annotation/**" />
- <include name="javax/ejb/*" />
- <include name="javax/persistence/*" />
- <include name="javax/xml/ws/*" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Servlet 3.0 Implementation JAR File -->
- <jar jarfile="${servlet-api.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="javax/servlet/*" />
- <include name="javax/servlet/annotation/*" />
- <include name="javax/servlet/descriptor/*" />
- <include name="javax/servlet/http/*" />
- <include name="javax/servlet/resources/*" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- JSP 2.2 Implementation JAR File -->
- <jar jarfile="${jsp-api.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="javax/servlet/jsp/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- JSP 2.2 EL Implementation JAR File -->
- <jar jarfile="${el-api.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="javax/el/*" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Bootstrap JAR File -->
- <jar jarfile="${bootstrap.jar}"
- manifest="res/bootstrap.jar.manifest">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/catalina/startup/Bootstrap.class" />
- <include name="org/apache/catalina/startup/catalina.properties" />
- <include name="org/apache/catalina/startup/CatalinaProperties.class" />
- <include name="org/apache/catalina/startup/ClassLoaderFactory.class" />
- <include name="org/apache/catalina/startup/Tool.class" />
- <include name="org/apache/catalina/loader/StandardClassLoader*.class" />
- <include name="org/apache/catalina/loader/Extension.class" />
- <include name="org/apache/catalina/loader/Reloader.class" />
- <include name="org/apache/catalina/security/SecurityClassLoad.class" />
- <include name="org/apache/naming/JndiPermission.class" />
- <include name="org/apache/tomcat/util/compat/*" />
- <include name="org/jboss/logging/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Tomcat-juli JAR File -->
- <jar jarfile="${tomcat-juli.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/juli/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Catalina Main JAR File -->
- <jar jarfile="${catalina.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/catalina/**" />
- <include name="org/apache/naming/**" />
- <include name="org/jboss/servlet/http/**" />
- <include name="org/jboss/web/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="org/jboss/web/php/**" />
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- <!-- Modules -->
- <exclude name="org/apache/catalina/ant/**" />
- <exclude name="org/apache/catalina/cluster/**" />
- <exclude name="org/apache/catalina/tribes/**" />
- <exclude name="org/apache/catalina/launcher/**" />
- <exclude name="org/apache/catalina/storeconfig/**" />
- </fileset>
- </jar>
-
- <!-- Catalina Ant Tasks JAR File -->
- <jar jarfile="${catalina-ant.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/catalina/ant/*" />
- <include name="org/apache/catalina/ant/jmx/*" />
- <include name="org/apache/catalina/util/Base64.class" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Protocol handlers - Coyote -->
- <jar jarfile="${tomcat-coyote.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/coyote/**" />
- <include name="org/apache/tomcat/*" />
- <include name="org/apache/tomcat/jni/**" />
- <include name="org/apache/tomcat/util/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Bayeux -->
- <jar jarfile="${tomcat-bayeux.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/cometd/**" />
- <include name="org/apache/tomcat/bayeux/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Jasper Implementation JAR File -->
- <jar jarfile="${jasper.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/jasper/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Jasper EL Implementation JAR File -->
- <jar jarfile="${jasper-el.jar}">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/el/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- i18n JARs -->
- <jar jarfile="${tomcat.build}/lib/tomcat-i18n-es.jar">
- <fileset dir="${tomcat.classes}">
- <include name="**/LocalStrings_es.properties" />
- </fileset>
- </jar>
- <jar jarfile="${tomcat.build}/lib/tomcat-i18n-fr.jar">
- <fileset dir="${tomcat.classes}">
- <include name="**/LocalStrings_fr.properties" />
- </fileset>
- </jar>
- <jar jarfile="${tomcat.build}/lib/tomcat-i18n-ja.jar">
- <fileset dir="${tomcat.classes}">
- <include name="**/LocalStrings_ja.properties" />
- </fileset>
- </jar>
-
- <!-- JBoss Web - PHP Servlet -->
- <jar jarfile="${tomcat.build}/lib/servlets-php.jar" index="true">
- <fileset dir="${tomcat.classes}">
- <include name="org/jboss/web/php/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- </target>
-
- <target name="build-docs">
-
- <copy todir="${tomcat.build}/webapps">
- <fileset dir="webapps">
- <include name="docs/images/**"/>
- <include name="docs/**/*.css"/>
- <include name="docs/**/*.html"/>
- <include name="docs/WEB-INF/**"/>
- <include name="docs/appdev/*.txt"/>
- <include name="docs/appdev/sample/**"/>
- </fileset>
- <fileset dir="webapps">
- <include name="docs/architecture/**"/>
- <exclude name="docs/architecture/*.xml"/>
- </fileset>
- </copy>
- <copy todir="${tomcat.build}/webapps/docs">
- <fileset dir=".">
- <include name="BUILDING.txt"/>
- <include name="NOTICE"/>
- <include name="RUNNING.txt"/>
- </fileset>
- </copy>
- <filter token="VERSION" value="${version}"/>
- <copy tofile="${tomcat.build}/webapps/docs/RELEASE-NOTES.txt" file="RELEASE-NOTES"
+ <copy todir="${tomcat.build}/webapps">
+ <fileset dir="webapps">
+ <include name="docs/images/**"/>
+ <include name="docs/**/*.css"/>
+ <include name="docs/**/*.html"/>
+ <include name="docs/WEB-INF/**"/>
+ <include name="docs/appdev/*.txt"/>
+ <include name="docs/appdev/sample/**"/>
+ </fileset>
+ <fileset dir="webapps">
+ <include name="docs/architecture/**"/>
+ <exclude name="docs/architecture/*.xml"/>
+ </fileset>
+ </copy>
+ <copy todir="${tomcat.build}/webapps/docs">
+ <fileset dir=".">
+ <include name="BUILDING.txt"/>
+ <include name="NOTICE"/>
+ <include name="RUNNING.txt"/>
+ </fileset>
+ </copy>
+ <filter token="VERSION" value="${version}"/>
+ <copy tofile="${tomcat.build}/webapps/docs/RELEASE-NOTES.txt" file="RELEASE-NOTES"
filtering="true" encoding="ISO-8859-1" />
- <copy tofile="${tomcat.build}/webapps/docs/appdev/sample/build.xml"
+ <copy tofile="${tomcat.build}/webapps/docs/appdev/sample/build.xml"
file="webapps/docs/appdev/build.xml.txt"/>
-
- <mkdir dir="${tomcat.build}/webapps/docs/funcspec" />
-
- <!-- XSL processing -->
- <xslt basedir="webapps/docs"
+
+ <mkdir dir="${tomcat.build}/webapps/docs/funcspec" />
+
+ <!-- XSL processing -->
+ <xslt basedir="webapps/docs"
destdir="${tomcat.build}/webapps/docs"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="build.xml project.xml"
includes="*.xml">
- <param name="relative-path" expression="."/>
- </xslt>
- <xslt basedir="webapps/docs/appdev"
+ <param name="relative-path" expression="."/>
+ </xslt>
+ <xslt basedir="webapps/docs/appdev"
destdir="${tomcat.build}/webapps/docs/appdev"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- </xslt>
- <xslt basedir="webapps/docs/funcspecs"
+ <param name="relative-path" expression=".."/>
+ </xslt>
+ <xslt basedir="webapps/docs/funcspecs"
destdir="${tomcat.build}/webapps/docs/funcspecs"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- </xslt>
- <xslt basedir="webapps/docs/config"
+ <param name="relative-path" expression=".."/>
+ </xslt>
+ <xslt basedir="webapps/docs/config"
destdir="${tomcat.build}/webapps/docs/config"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- </xslt>
- <xslt basedir="webapps/docs/architecture"
+ <param name="relative-path" expression=".."/>
+ </xslt>
+ <xslt basedir="webapps/docs/architecture"
destdir="${tomcat.build}/webapps/docs/architecture"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- </xslt>
-
- <!-- Print friendly version -->
- <mkdir dir="${tomcat.build}/webapps/docs/printer" />
- <copy todir="${tomcat.build}/webapps/docs/printer">
- <fileset dir=".">
- <include name="BUILDING.txt"/>
- <include name="NOTICE"/>
- <include name="RUNNING.txt"/>
- </fileset>
- </copy>
- <mkdir dir="${tomcat.build}/webapps/docs/appdev/printer" />
- <copy todir="${tomcat.build}/webapps/docs/appdev/printer">
- <fileset dir="webapps">
- <include name="docs/appdev/*.txt"/>
- </fileset>
- </copy>
- <mkdir dir="${tomcat.build}/webapps/docs/funcspecs/printer" />
- <mkdir dir="${tomcat.build}/webapps/docs/architecture/printer"/>
- <mkdir dir="${tomcat.build}/webapps/docs/config/printer"/>
+ <param name="relative-path" expression=".."/>
+ </xslt>
- <xslt basedir="webapps/docs"
+ <!-- Print friendly version -->
+ <mkdir dir="${tomcat.build}/webapps/docs/printer" />
+ <copy todir="${tomcat.build}/webapps/docs/printer">
+ <fileset dir=".">
+ <include name="BUILDING.txt"/>
+ <include name="NOTICE"/>
+ <include name="RUNNING.txt"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${tomcat.build}/webapps/docs/appdev/printer" />
+ <copy todir="${tomcat.build}/webapps/docs/appdev/printer">
+ <fileset dir="webapps">
+ <include name="docs/appdev/*.txt"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${tomcat.build}/webapps/docs/funcspecs/printer" />
+ <mkdir dir="${tomcat.build}/webapps/docs/architecture/printer"/>
+ <mkdir dir="${tomcat.build}/webapps/docs/config/printer"/>
+
+ <xslt basedir="webapps/docs"
destdir="${tomcat.build}/webapps/docs/printer"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="build.xml project.xml"
includes="*.xml">
- <param name="relative-path" expression="./.."/>
- <param name="project-menu" expression="nomenu"/>
- </xslt>
- <xslt basedir="webapps/docs/appdev"
+ <param name="relative-path" expression="./.."/>
+ <param name="project-menu" expression="nomenu"/>
+ </xslt>
+ <xslt basedir="webapps/docs/appdev"
destdir="${tomcat.build}/webapps/docs/appdev/printer"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression="../.."/>
- <param name="project-menu" expression="nomenu"/>
- </xslt>
- <xslt basedir="webapps/docs/funcspecs"
+ <param name="relative-path" expression="../.."/>
+ <param name="project-menu" expression="nomenu"/>
+ </xslt>
+ <xslt basedir="webapps/docs/funcspecs"
destdir="${tomcat.build}/webapps/docs/funcspecs/printer"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression="../.."/>
- <param name="project-menu" expression="nomenu"/>
- </xslt>
- <xslt basedir="webapps/docs/config"
+ <param name="relative-path" expression="../.."/>
+ <param name="project-menu" expression="nomenu"/>
+ </xslt>
+ <xslt basedir="webapps/docs/config"
destdir="${tomcat.build}/webapps/docs/config/printer"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression="../.."/>
- <param name="project-menu" expression="nomenu"/>
- </xslt>
- <xslt basedir="webapps/docs/architecture"
+ <param name="relative-path" expression="../.."/>
+ <param name="project-menu" expression="nomenu"/>
+ </xslt>
+ <xslt basedir="webapps/docs/architecture"
destdir="${tomcat.build}/webapps/docs/architecture/printer"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression="../.."/>
- <param name="project-menu" expression="nomenu"/>
- </xslt>
+ <param name="relative-path" expression="../.."/>
+ <param name="project-menu" expression="nomenu"/>
+ </xslt>
- <!-- Website version -->
- <mkdir dir="${jbossweb.site}" />
- <copy todir="${jbossweb.site}">
- <fileset dir="webapps/docs">
- <include name="images/**"/>
- <include name="**/*.html"/>
- <include name="appdev/*.txt"/>
- <include name="appdev/sample/**"/>
- </fileset>
- <fileset dir="webapps/docs">
- <include name="architecture/**"/>
- <exclude name="architecture/*.xml"/>
- </fileset>
- </copy>
- <copy todir="${jbossweb.site}">
- <fileset dir=".">
- <include name="BUILDING.txt"/>
- <include name="NOTICE"/>
- <include name="RUNNING.txt"/>
- </fileset>
- </copy>
- <mkdir dir="${jbossweb.site}/appdev" />
- <copy todir="${jbossweb.site}/appdev">
- <fileset dir="webapps">
- <include name="docs/appdev/*.txt"/>
- </fileset>
- </copy>
- <mkdir dir="${jbossweb.site}/funcspecs" />
- <mkdir dir="${jbossweb.site}/architecture"/>
- <mkdir dir="${jbossweb.site}/config"/>
+ <!-- Website version -->
+ <mkdir dir="${jbossweb.site}" />
+ <copy todir="${jbossweb.site}">
+ <fileset dir="webapps/docs">
+ <include name="images/**"/>
+ <include name="**/*.html"/>
+ <include name="appdev/*.txt"/>
+ <include name="appdev/sample/**"/>
+ </fileset>
+ <fileset dir="webapps/docs">
+ <include name="architecture/**"/>
+ <exclude name="architecture/*.xml"/>
+ </fileset>
+ </copy>
+ <copy todir="${jbossweb.site}">
+ <fileset dir=".">
+ <include name="BUILDING.txt"/>
+ <include name="NOTICE"/>
+ <include name="RUNNING.txt"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${jbossweb.site}/appdev" />
+ <copy todir="${jbossweb.site}/appdev">
+ <fileset dir="webapps">
+ <include name="docs/appdev/*.txt"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${jbossweb.site}/funcspecs" />
+ <mkdir dir="${jbossweb.site}/architecture"/>
+ <mkdir dir="${jbossweb.site}/config"/>
- <xslt basedir="webapps/docs"
+ <xslt basedir="webapps/docs"
destdir="${jbossweb.site}"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="build.xml project.xml"
includes="*.xml">
- <param name="relative-path" expression="."/>
- <param name="project-menu" expression="nomenu"/>
- <param name="bodyonly" expression="true"/>
- <param name="usehead" expression="true"/>
- </xslt>
- <xslt basedir="webapps/docs/appdev"
+ <param name="relative-path" expression="."/>
+ <param name="project-menu" expression="nomenu"/>
+ <param name="bodyonly" expression="true"/>
+ <param name="usehead" expression="true"/>
+ </xslt>
+ <xslt basedir="webapps/docs/appdev"
destdir="${jbossweb.site}/appdev"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- <param name="project-menu" expression="nomenu"/>
- <param name="bodyonly" expression="true"/>
- <param name="usehead" expression="true"/>
- </xslt>
- <xslt basedir="webapps/docs/funcspecs"
+ <param name="relative-path" expression=".."/>
+ <param name="project-menu" expression="nomenu"/>
+ <param name="bodyonly" expression="true"/>
+ <param name="usehead" expression="true"/>
+ </xslt>
+ <xslt basedir="webapps/docs/funcspecs"
destdir="${jbossweb.site}/funcspecs"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression="../.."/>
- <param name="project-menu" expression="nomenu"/>
- <param name="bodyonly" expression="true"/>
- <param name="usehead" expression="true"/>
- </xslt>
- <xslt basedir="webapps/docs/config"
+ <param name="relative-path" expression="../.."/>
+ <param name="project-menu" expression="nomenu"/>
+ <param name="bodyonly" expression="true"/>
+ <param name="usehead" expression="true"/>
+ </xslt>
+ <xslt basedir="webapps/docs/config"
destdir="${jbossweb.site}/config"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- <param name="project-menu" expression="nomenu"/>
- <param name="bodyonly" expression="true"/>
- <param name="usehead" expression="true"/>
- </xslt>
- <xslt basedir="webapps/docs/architecture"
+ <param name="relative-path" expression=".."/>
+ <param name="project-menu" expression="nomenu"/>
+ <param name="bodyonly" expression="true"/>
+ <param name="usehead" expression="true"/>
+ </xslt>
+ <xslt basedir="webapps/docs/architecture"
destdir="${jbossweb.site}/architecture"
extension=".html"
style="webapps/docs/tomcat-docs.xsl"
excludes="project.xml"
includes="*.xml">
- <param name="relative-path" expression=".."/>
- <param name="project-menu" expression="nomenu"/>
- <param name="bodyonly" expression="true"/>
- <param name="usehead" expression="true"/>
- </xslt>
+ <param name="relative-path" expression=".."/>
+ <param name="project-menu" expression="nomenu"/>
+ <param name="bodyonly" expression="true"/>
+ <param name="usehead" expression="true"/>
+ </xslt>
- </target>
+ </target>
- <target name="deploy" depends="build-only,build-docs">
+ <target name="deploy" depends="build-only,build-docs">
- <copy todir="${tomcat.build}/bin" file="${commons-daemon.jar}" />
- <copy todir="${tomcat.build}/bin" file="${commons-daemon.jsvc.tar.gz}" />
+ <!-- JBoss Web Main JAR File -->
+ <jar jarfile="${tomcat.jars}/jbossweb.jar" index="true">
+ <fileset dir="${tomcat.classes}">
+ <!-- Temp EE class -->
+ <include name="org/apache/catalina/**" />
+ <include name="org/apache/catalina/ha/backend/**" />
+ <include name="org/apache/naming/**" />
+ <include name="org/apache/comet/**" />
+ <include name="org/apache/coyote/**" />
+ <include name="org/apache/tomcat/**" />
+ <include name="org/apache/jasper/**" />
+ <include name="org/apache/cometd/bayeux/**" />
+ <include name="org/apache/el/**" />
+ <include name="org/jboss/servlet/**" />
+ <include name="org/jboss/web/**" />
+ <!-- Javadoc and i18n exclusions -->
+ <exclude name="**/package.html" />
+ </fileset>
+ </jar>
- <!-- Copy scripts -->
- <copy todir="${tomcat.build}/bin">
- <fileset dir="bin">
- <exclude name="**/*.launch"/>
- </fileset>
- </copy>
- <chmod perm="ug+x" dir="${tomcat.build}/bin" includes="*.sh"/>
+ <copy file="${jasper-jdt.jar}" todir="${tomcat.jars}" />
- <!-- Copy static resource files -->
- <copy todir="${tomcat.build}/conf">
- <fileset dir="conf">
- <include name="**/*.policy"/>
- <include name="**/*.xml"/>
- <include name="**/*.properties"/>
- </fileset>
- </copy>
+ <!-- Create a source jar of the jbossweb/servlet classes -->
+ <zip destfile="${tomcat.jars}/jbossweb-src.zip">
+ <fileset dir="${basedir}/java">
+ <include name="org/**" />
+ <exclude name="org/jboss/logging/**" />
+ <exclude name="javax/servlet/**" />
+ <exclude name="javax/el/**" />
+ </fileset>
+ </zip>
- <!-- Copy other regular webapps -->
- <copy todir="${tomcat.build}/webapps">
- <fileset dir="webapps">
- <include name="ROOT/**"/>
- <include name="manager/**"/>
- <include name="host-manager/**"/>
- </fileset>
- </copy>
+ </target>
- <filter token="VERSION" value="${version}"/>
- <copy tofile="${tomcat.build}/webapps/ROOT/RELEASE-NOTES.txt" file="RELEASE-NOTES"
- filtering="true" encoding="ISO-8859-1" />
-
- <copy file="${tomcat-dbcp.jar}" todir="${tomcat.build}/lib" />
- <copy file="${jasper-jdt.jar}" todir="${tomcat.build}/lib" />
-
- <!-- JBoss Web Main JAR File -->
- <jar jarfile="${tomcat.jars}/jbossweb.jar" index="true">
- <fileset dir="${tomcat.classes}">
- <!-- Temp EE class -->
- <include name="org/apache/catalina/**" />
- <include name="org/apache/catalina/ha/backend/**" />
- <include name="org/apache/naming/**" />
- <include name="org/apache/comet/**" />
- <include name="org/apache/coyote/**" />
- <include name="org/apache/tomcat/**" />
- <include name="org/apache/jasper/**" />
- <include name="org/apache/cometd/bayeux/**" />
- <include name="org/apache/el/**" />
- <include name="org/jboss/servlet/**" />
- <include name="org/jboss/web/**" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- </fileset>
- </jar>
-
- <!-- Servlet 3.0 Implementation JAR File -->
- <jar jarfile="${tomcat.jars}/servlet-api.jar">
- <fileset dir="${tomcat.classes}">
- <include name="javax/servlet/*" />
- <include name="javax/servlet/annotation/*" />
- <include name="javax/servlet/descriptor/*" />
- <include name="javax/servlet/http/*" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- JSP 2.2 Implementation JAR File -->
- <jar jarfile="${tomcat.jars}/jsp-api.jar">
- <fileset dir="${tomcat.classes}">
- <include name="javax/servlet/jsp/*" />
- <include name="javax/servlet/jsp/el/*" />
- <include name="javax/servlet/jsp/tagext/*" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- EL Implementation JAR File -->
- <jar jarfile="${tomcat.jars}/el-api.jar">
- <fileset dir="${tomcat.classes}">
- <include name="javax/el/*" />
- <!-- Javadoc and i18n exclusions -->
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <copy file="${jasper-jdt.jar}" todir="${tomcat.jars}" />
-
- <!-- Create a source jar of the jbossweb/servlet classes -->
- <zip destfile="${tomcat.jars}/jbossweb-src.zip">
- <fileset dir="${basedir}/java">
- <include name="org/**" />
- <exclude name="org/jboss/logging/**" />
- <include name="javax/servlet/**" />
- <include name="javax/el/**" />
- </fileset>
- </zip>
-
- </target>
-
- <target name="clean-depend"
+ <target name="clean-depend"
description="Clean depend src components">
- <delete dir="${tomcat-dbcp.home}"/>
- <delete dir="${jasper-jdt.home}"/>
- </target>
-
- <target name="clean">
- <delete dir="${tomcat.classes}" />
- <delete dir="${tomcat.build}" />
- <delete dir="${tomcat.jars}" />
- <delete dir="${jbossweb.site}" />
- </target>
+ <delete dir="${jasper-jdt.home}"/>
+ </target>
- <!-- Download and dependency building -->
- <target name="proxyflags">
- <!-- check proxy parameters. -->
- <condition property="useproxy">
- <equals arg1="${proxy.use}" arg2="on" />
- </condition>
- </target>
+ <target name="clean">
+ <delete dir="${tomcat.classes}" />
+ <delete dir="${tomcat.build}" />
+ <delete dir="${tomcat.jars}" />
+ <delete dir="${jbossweb.site}" />
+ </target>
- <target name="setproxy" depends="proxyflags" if="useproxy">
- <taskdef name="setproxy"
+ <!-- Download and dependency building -->
+ <target name="proxyflags">
+ <!-- check proxy parameters. -->
+ <condition property="useproxy">
+ <equals arg1="${proxy.use}" arg2="on" />
+ </condition>
+ </target>
+
+ <target name="setproxy" depends="proxyflags" if="useproxy">
+ <taskdef name="setproxy"
classname="org.apache.tools.ant.taskdefs.optional.net.SetProxy" />
- <setproxy proxyhost="${proxy.host}" proxyport="${proxy.port}"
+ <setproxy proxyhost="${proxy.host}" proxyport="${proxy.port}"
proxyuser="${proxy.user}" proxypassword="${proxy.password}" />
- <echo message="Using ${proxy.host}:${proxy.port} to download ${sourcefile}"/>
- </target>
+ <echo message="Using ${proxy.host}:${proxy.port} to download ${sourcefile}"/>
+ </target>
- <target name="testexist">
- <echo message="Testing for ${destfile}"/>
- <available file="${destfile}" property="exist"/>
- </target>
+ <target name="testexist">
+ <echo message="Testing for ${destfile}"/>
+ <available file="${destfile}" property="exist"/>
+ </target>
- <target name="downloadgz" unless="exist" depends="setproxy,testexist">
- <!-- Download and extract the package -->
- <get src="${sourcefile}" dest="${base.path}/file.tar.gz" />
- <gunzip src="${base.path}/file.tar.gz" dest="${base.path}/file.tar"/>
- <untar src="${base.path}/file.tar" dest="${base.path}"/>
- <delete file="${base.path}/file.tar"/>
- <delete file="${base.path}/file.tar.gz"/>
- </target>
+ <target name="downloadgz" unless="exist" depends="setproxy,testexist">
+ <!-- Download and extract the package -->
+ <get src="${sourcefile}" dest="${base.path}/file.tar.gz" />
+ <gunzip src="${base.path}/file.tar.gz" dest="${base.path}/file.tar"/>
+ <untar src="${base.path}/file.tar" dest="${base.path}"/>
+ <delete file="${base.path}/file.tar"/>
+ <delete file="${base.path}/file.tar.gz"/>
+ </target>
- <target name="downloadzip" unless="exist" depends="setproxy,testexist">
- <!-- Download and extract the package -->
- <get src="${sourcefile}" dest="${base.path}/file.zip" />
- <mkdir dir="${destdir}" />
- <unzip src="${base.path}/file.zip" dest="${destdir}"/>
- <delete file="${base.path}/file.zip"/>
- </target>
+ <target name="downloadzip" unless="exist" depends="setproxy,testexist">
+ <!-- Download and extract the package -->
+ <get src="${sourcefile}" dest="${base.path}/file.zip" />
+ <mkdir dir="${destdir}" />
+ <unzip src="${base.path}/file.zip" dest="${destdir}"/>
+ <delete file="${base.path}/file.zip"/>
+ </target>
- <target name="downloadfile" unless="exist" depends="setproxy,testexist">
- <!-- Download extract the file -->
- <mkdir dir="${destdir}" />
- <get src="${sourcefile}" dest="${destfile}" />
- </target>
+ <target name="downloadfile" unless="exist" depends="setproxy,testexist">
+ <!-- Download extract the file -->
+ <mkdir dir="${destdir}" />
+ <get src="${sourcefile}" dest="${destfile}" />
+ </target>
- <target name="download"
+ <target name="download"
description="Builds and download dependent components">
- <mkdir dir="${base.path}" />
+ <mkdir dir="${base.path}" />
- <antcall target="downloadgz">
- <param name="sourcefile" value="${commons-daemon.loc}"/>
- <param name="destfile" value="${commons-daemon.jar}"/>
- </antcall>
-
- <!-- Build Tomcat DBCP bundle -->
- <antcall target="downloadgz">
- <param name="sourcefile" value="${commons-pool-src.loc}"/>
- <param name="destfile" value="${tomcat-dbcp.jar}" />
- </antcall>
- <antcall target="downloadgz">
- <param name="sourcefile" value="${commons-dbcp-src.loc}"/>
- <param name="destfile" value="${tomcat-dbcp.jar}" />
- </antcall>
- <mkdir dir="${tomcat-dbcp.home}"/>
- <antcall target="build-tomcat-dbcp">
- <param name="basedir" value="${tomcat-dbcp.home}" />
- <param name="destfile" value="${tomcat-dbcp.jar}" />
- </antcall>
-
- <!-- Download json libraries
+ <!-- Download json libraries
<antcall target="downloadfile">
<param name="sourcefile" value="${json-lib.loc}"/>
<param name="destfile" value="${json-lib.jar}"/>
<param name="destdir" value="${json-lib.home}"/>
</antcall> -->
- <!-- Build Jasper JDT bundle -->
- <antcall target="downloadzip">
- <param name="sourcefile" value="${jdt.loc}"/>
- <param name="destfile" value="${jdt.jar}"/>
- <param name="destdir" value="${base.path}"/>
- </antcall>
- <mkdir dir="${jasper-jdt.home}"/>
- <antcall target="build-jasper-jdt">
- <param name="basedir" value="${jasper-jdt.home}" />
- </antcall>
+ <!-- Build Jasper JDT bundle -->
+ <antcall target="downloadzip">
+ <param name="sourcefile" value="${jdt.loc}"/>
+ <param name="destfile" value="${jdt.jar}"/>
+ <param name="destdir" value="${base.path}"/>
+ </antcall>
+ <mkdir dir="${jasper-jdt.home}"/>
+ <antcall target="build-jasper-jdt">
+ <param name="basedir" value="${jasper-jdt.home}" />
+ </antcall>
- <antcall target="downloadzip">
- <param name="sourcefile" value="${jbossnative.loc}"/>
- <param name="destfile" value="${jbossnative.openssl}"/>
- <param name="destdir" value="${jbossnative.home}"/>
- </antcall>
+ </target>
- <antcall target="downloadzip">
- <param name="sourcefile" value="${nsis.loc}"/>
- <param name="destfile" value="${nsis.exe}"/>
- <param name="destdir" value="${nsis.home}/.."/>
- </antcall>
+ <target name="build-jasper-jdt">
+ <unjar src="${jdt.jar}" dest="${jasper-jdt.home}" />
+ <jar destfile="${jasper-jdt.jar}" index="true">
+ <fileset dir="${jasper-jdt.home}">
+ <include name="org/eclipse/jdt/core/compiler/**"/>
+ <include name="org/eclipse/jdt/internal/compiler/**"/>
+ <include name="org/eclipse/jdt/internal/core/util/CommentRecorder*"/>
+ </fileset>
+ </jar>
+ </target>
- </target>
+ <target name="tests">
+ <antcall target="downloadgz">
+ <param name="sourcefile" value="${dojo-js.loc}"/>
+ <param name="destfile" value="${dojo-js.jar}"/>
+ </antcall>
- <target name="build-tomcat-dbcp" unless="exist" depends="testexist">
- <copy todir="${tomcat-dbcp.home}">
- <!--
- <fileset dir="${commons-collections.home}" >
- <include name="**/collections/CursorableLinkedList.java" />
- <include name="**/collections/KeyValue.java" />
- <include name="**/collections/LRUMap.java" />
- <include name="**/collections/SequencedHashMap.java" />
- </fileset>
- -->
- <fileset dir="${commons-pool.home}">
- <include name="**/*.java" />
- <exclude name="**/test/**" />
- </fileset>
- <fileset dir="${commons-dbcp.home}">
- <include name="**/*.java" />
- <exclude name="**/test/**" />
- </fileset>
- </copy>
- <!--
- <replace dir="${tomcat-dbcp.home}/src/java/org/apache/commons">
- <replacefilter token="return UnmodifiableList.decorate(l);"
- value="return l;" />
- <replacefilter token="import org.apache.commons.collections.list.UnmodifiableList;"
- value=" " />
- </replace>
- -->
- <replace dir="${tomcat-dbcp.home}/src/java/org/apache/commons" >
- <replacefilter token="org.apache.commons"
- value="org.apache.tomcat.dbcp" />
- </replace>
- <replace dir="${tomcat-dbcp.home}/src/java/org/apache/commons/pool/impl" >
- <replacefilter token="enum"
- value="enumeration" />
- </replace>
-
- <mkdir dir="${tomcat-dbcp.home}/src/java/org/apache/tomcat/dbcp" />
- <move todir="${tomcat-dbcp.home}/src/java/org/apache/tomcat/dbcp">
- <fileset dir="${tomcat-dbcp.home}/src/java/org/apache/commons" />
- </move>
- <mkdir dir="${tomcat-dbcp.home}/classes"/>
- <javac destdir="${tomcat-dbcp.home}/classes"
- sourcepath="${tomcat-dbcp.home}/src/java"
- srcdir="${tomcat-dbcp.home}/src/java"
- debug="${compile.debug}"
- optimize="${compile.optimize}"
- deprecation="${compile.deprecation}"
- source="1.5"
- target="1.5"
- excludes="**/CVS/**,**/.svn/**">
- <include name="**" />
- </javac>
- <jar jarfile="${tomcat-dbcp.jar}"
- index="true">
- <fileset dir="${tomcat-dbcp.home}/classes">
- <include name="**/*.class" />
- <include name="**/*.properties" />
- </fileset>
- </jar>
- </target>
-
- <target name="build-jasper-jdt">
- <unjar src="${jdt.jar}" dest="${jasper-jdt.home}" />
- <jar destfile="${jasper-jdt.jar}" index="true">
- <fileset dir="${jasper-jdt.home}">
- <include name="org/eclipse/jdt/core/compiler/**"/>
- <include name="org/eclipse/jdt/internal/compiler/**"/>
- <include name="org/eclipse/jdt/internal/core/util/CommentRecorder*"/>
- </fileset>
- </jar>
- </target>
-
- <target name="tests">
- <antcall target="downloadgz">
- <param name="sourcefile" value="${dojo-js.loc}"/>
- <param name="destfile" value="${dojo-js.jar}"/>
- </antcall>
-
- <mkdir dir="${tomcat.build}/webapps/cometd"/>
- <mkdir dir="${tomcat.build}/webapps/cometd/WEB-INF/classes"/>
- <copy todir="${tomcat.build}/webapps/cometd">
- <fileset dir="${basedir}/test/webapps/cometd">
- </fileset>
- <fileset dir="${dojo-js.home}">
- <include name="dojo/**"/>
- <include name="dojox/**"/>
- </fileset>
- </copy>
- <javac srcdir="${basedir}/test/java" destdir="${tomcat.build}/webapps/cometd/WEB-INF/classes"
+ <mkdir dir="${tomcat.build}/webapps/cometd"/>
+ <mkdir dir="${tomcat.build}/webapps/cometd/WEB-INF/classes"/>
+ <copy todir="${tomcat.build}/webapps/cometd">
+ <fileset dir="${basedir}/test/webapps/cometd">
+ </fileset>
+ <fileset dir="${dojo-js.home}">
+ <include name="dojo/**"/>
+ <include name="dojox/**"/>
+ </fileset>
+ </copy>
+ <javac srcdir="${basedir}/test/java" destdir="${tomcat.build}/webapps/cometd/WEB-INF/classes"
debug="${compile.debug}"
deprecation="${compile.deprecation}"
source="${compile.source}"
optimize="${compile.optimize}"
classpath="${tomcat.classes}">
- <include name="org/jboss/web/comet/**" />
- <include name="org/apache/cometd/**" />
- </javac>
- </target>
-
+ <include name="org/jboss/web/comet/**" />
+ <include name="org/apache/cometd/**" />
+ </javac>
+ </target>
+
+ <target name="maven" description="Upload to Maven repository; if this looks like a hack, it's because it's one">
+
+ <filter token="VERSION" value="${version}"/>
+ <copy todir="${tomcat.jars}" filtering="true">
+ <fileset dir="res">
+ <include name="*-pom.xml"/>
+ </fileset>
+ </copy>
+
+ <!-- Maven repository configuration -->
+ <property name="maven.repository.url" value="file:///somepath"/>
+ <property name="maven.repository.id" value="repository.jboss.org"/>
+ <!--<property name="maven.repository.url" value="dav:https://snapshots.jboss.org/maven2"/>
+ <property name="maven.repository.id" value="snapshots.jboss.org"/>-->
+
+ <!-- Linux/Unix execs -->
+ <exec dir="." executable="/bin/sh" os="Linux">
+ <arg value="-c" />
+ <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jasper-jdt.jar -DpomFile=${tomcat.jars}/jasper-jdt-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
+ </exec>
+ <exec dir="." executable="/bin/sh" os="Linux">
+ <arg value="-c" />
+ <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb.jar -DpomFile=${tomcat.jars}/jbossweb-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
+ </exec>
+ <exec dir="." executable="/bin/sh" os="Linux">
+ <arg value="-c" />
+ <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb-src.zip -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id} -DgroupId=jboss.web -DartifactId=jbossweb -Dversion=${version} -Dclassifier=sources"/>
+ </exec>
+
+ <!-- Windows exec -->
+ <exec dir="." executable="cmd" os="Windows NT">
+ <arg value="/c" />
+ <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jasper-jdt.jar -DpomFile=${tomcat.jars}/jasper-jdt-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
+ </exec>
+ <exec dir="." executable="cmd" os="Windows NT">
+ <arg value="/c" />
+ <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb.jar -DpomFile=${tomcat.jars}/jbossweb-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
+ </exec>
+ <exec dir="." executable="cmd" os="Windows NT">
+ <arg value="/c" />
+ <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb-src.zip -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id} -DgroupId=jboss.web -DartifactId=jbossweb -Dversion=${version} -Dclassifier=sources"/>
+ </exec>
+
+ </target>
+
</project>
Deleted: trunk/dist.xml
===================================================================
--- trunk/dist.xml 2010-03-12 18:44:44 UTC (rev 1410)
+++ trunk/dist.xml 2010-03-16 14:48:04 UTC (rev 1411)
@@ -1,556 +0,0 @@
-<?xml version="1.0"?>
-<project name="JBoss Web" default="release" basedir=".">
-
-
- <!-- ===================== Initialize Property Values =================== -->
-
- <!-- See "build.properties.sample" in the top level directory for all -->
- <!-- property values you must customize for successful building!!! -->
- <property file="${user.home}/build.properties"/>
- <property file="build.properties"/>
-
- <property file="build.properties.default"/>
-
- <!-- Project Properties -->
- <property name="name" value="JBoss Web" />
- <property name="year" value="2009" />
- <property name="version.major" value="3" />
- <property name="version.minor" value="0" />
- <property name="version.build" value="0" />
- <property name="version.patch" value="0" />
- <property name="version.tag" value="SNAPSHOT" />
- <property name="version" value="${version.major}.${version.minor}.${version.build}-${version.tag}" />
- <property name="version.number" value="${version.major}.${version.minor}.${version.build}.${version.patch}" />
-
- <property name="project" value="jboss-web" />
- <property name="final.name" value="${project}-${version}" />
- <property name="final-src.name" value="${project}-${version}-src" />
-
- <!-- Build Defaults -->
- <property name="tomcat.build" value="${basedir}/output/build"/>
- <property name="tomcat.classes" value="${basedir}/output/classes"/>
- <property name="tomcat.dist" value="${basedir}/output/dist"/>
- <property name="tomcat.deployer" value="${basedir}/output/deployer"/>
- <property name="tomcat.extras" value="${basedir}/output/extras"/>
- <property name="tomcat.release" value="${basedir}/output/release"/>
- <property name="tomcat.jars" value="${basedir}/output/jars"/>
- <property name="test.failonerror" value="true"/>
- <property name="test.runner" value="junit.textui.TestRunner"/>
-
- <!-- constant to declare a file binary for md5sum -->
- <property name="md5sum.binary-prefix" value=" *" />
-
- <!-- Can't be lower - jsp uses templates -->
- <property name="compile.source" value="1.5"/>
-
- <!-- JAR artifacts -->
- <property name="bootstrap.jar" value="${tomcat.build}/bin/bootstrap.jar"/>
-
- <property name="annotations-api.jar" value="${tomcat.build}/lib/annotations-api.jar"/>
- <property name="servlet-api.jar" value="${tomcat.build}/lib/servlet-api.jar"/>
- <property name="jsp-api.jar" value="${tomcat.build}/lib/jsp-api.jar"/>
- <property name="el-api.jar" value="${tomcat.build}/lib/el-api.jar"/>
- <property name="catalina.jar" value="${tomcat.build}/lib/catalina.jar"/>
- <property name="catalina-ant.jar" value="${tomcat.build}/lib/catalina-ant.jar"/>
- <property name="catalina-ant-jmx.jar" value="${tomcat.build}/lib/catalina-ant-jmx.jar"/>
- <property name="tomcat-coyote.jar" value="${tomcat.build}/lib/tomcat-coyote.jar"/>
-
- <property name="jasper.jar" value="${tomcat.build}/lib/jasper.jar"/>
- <property name="jasper-el.jar" value="${tomcat.build}/lib/jasper-el.jar"/>
-
- <property name="tomcat-dbcp.home" value="${base.path}/tomcat6-deps/dbcp" />
- <property name="jasper-jdt.home" value="${base.path}/tomcat6-deps/jdt" />
- <property name="tomcat-dbcp.jar" value="${tomcat-dbcp.home}/tomcat-dbcp.jar"/>
- <property name="jasper-jdt.jar" value="${jasper-jdt.home}/jasper-jdt.jar"/>
-
- <!-- ====================== COMBO: Clean All Directories ================ -->
- <target name="clean"
- description="Clean all components">
-
- <delete dir="${tomcat.deployer}"/>
- <delete dir="${tomcat.dist}" failonerror="false"/>
-
- </target>
-
-
- <!-- ====================== DIST: Create Directories ==================== -->
- <target name="dist-prepare">
- <mkdir dir="${tomcat.dist}"/>
- <mkdir dir="${tomcat.dist}/bin"/>
- <mkdir dir="${tomcat.dist}/conf"/>
- <mkdir dir="${tomcat.dist}/lib"/>
- <mkdir dir="${tomcat.dist}/logs"/>
- <mkdir dir="${tomcat.dist}/temp"/>
- <mkdir dir="${tomcat.dist}/webapps"/>
- <mkdir dir="${tomcat.dist}/work"/>
- <mkdir dir="${tomcat.release}/v${version}/bin" />
- <mkdir dir="${tomcat.release}/v${version}/src" />
- <mkdir dir="${tomcat.jars}" />
- </target>
-
-
- <!-- ====================== DIST: Copy Static Files ===================== -->
- <target name="dist-static" depends="dist-prepare">
-
- <!-- Copy the top-level documentation files -->
- <filter token="VERSION" value="${version}"/>
- <copy todir="${tomcat.dist}" filtering="true">
- <fileset dir=".">
- <include name="INSTALLING.txt"/>
- <include name="LICENSE"/>
- <include name="NOTICE"/>
- <include name="RELEASE-NOTES"/>
- <include name="RUNNING.txt"/>
- </fileset>
- </copy>
-
- <!-- Copy the contents of each "build" directory -->
- <copy todir="${tomcat.dist}/bin">
- <fileset dir="${tomcat.build}/bin">
- </fileset>
- </copy>
- <copy todir="${tomcat.dist}/lib">
- <fileset dir="${tomcat.build}/lib" />
- </copy>
- <copy todir="${tomcat.dist}/conf">
- <fileset dir="${tomcat.build}/conf">
- </fileset>
- </copy>
-
- <copy todir="${tomcat.dist}/webapps">
- <fileset dir="${tomcat.build}/webapps">
- <exclude name="**/balancer/WEB-INF/classes/**" />
- <exclude name="**/ROOT/WEB-INF/classes/**" />
- <exclude name="**/WEB-INF/src/**" />
- </fileset>
- </copy>
-
- <touch file="${tomcat.dist}/temp/safeToDelete.tmp" />
-
- <!-- Correct permissions and line endings on "bin" scripts -->
- <fixcrlf srcdir="${tomcat.dist}/bin" includes="*.sh" eol="lf" encoding="ISO-8859-1" fixlast="false"/>
- <fixcrlf srcdir="${tomcat.dist}/bin" includes="*.bat" eol="crlf" encoding="ISO-8859-1" fixlast="false"/>
- <chmod dir="${tomcat.dist}/bin" includes="*.sh" perm="+x"/>
-
- </target>
-
- <target name="dist-javadoc" depends="dist-source" description="Create the Tomcat javadoc" >
- <javadoc packagenames="org.apache.*"
- sourcepath="${tomcat.dist}/src/java"
- destdir="${tomcat.dist}/webapps/docs/api"
- author="true" version="true"
- windowtitle="JBoss Web API Documentation"
- doctitle="JBoss Web API"
- bottom="Copyright &#169; 2000-${year} Apache Software Foundation. All Rights Reserved."
- additionalparam="-breakiterator"
- maxmemory="256m" >
- </javadoc>
- </target>
-
- <target name="dist-deployer" description="Create the Tomcat deployer binary" >
-
- <!-- Servlet and JSP -->
- <copy todir="${tomcat.deployer}/lib">
- <fileset dir="${tomcat.build}/lib">
- <include name="catalina-ant.jar"/>
- <include name="el-api.jar"/>
- <include name="jsp-api.jar"/>
- <include name="jasper.jar"/>
- <include name="jasper-el.jar"/>
- <include name="servlet-api.jar"/>
- </fileset>
- <fileset dir="${tomcat.build}/bin">
- <include name="tomcat-juli.jar"/>
- </fileset>
- </copy>
-
- <!-- Digester and dependencies -->
- <jar jarfile="${tomcat.deployer}/lib/catalina-deployer.jar">
- <fileset dir="${tomcat.classes}">
- <include name="org/apache/catalina/startup/DigesterFactory.class" />
- <include name="org/apache/catalina/util/SchemaResolver.class" />
- <include name="org/apache/catalina/util/StringManager.class" />
- <include name="org/apache/tomcat/*" />
- <include name="org/apache/tomcat/util/*" />
- <include name="org/apache/tomcat/util/digester/*" />
- <exclude name="**/package.html" />
- <exclude name="**/LocalStrings_*" />
- </fileset>
- </jar>
-
- <!-- Main build script -->
- <copy todir="${tomcat.deployer}">
- <fileset dir="${basedir}/res/deployer" />
- </copy>
-
- <!-- Copy deployer documentation -->
- <copy todir="${tomcat.deployer}">
- <fileset dir="${tomcat.build}/webapps/docs">
- <include name="images/jbossorg_logo.gif" />
- <include name="images/jboss_logo.gif" />
- </fileset>
- </copy>
- <copy tofile="${tomcat.deployer}/docs/manual.html"
- file="${tomcat.build}/webapps/docs/printer/deployer-howto.html"
- failonerror="false"/>
-
- </target>
-
- <!-- ====================== DIST: Create Sources ======================== -->
- <target name="dist-source">
-
- <mkdir dir="${tomcat.dist}/src"/>
-
- <!-- Tomcat source -->
- <copy todir="${tomcat.dist}/src">
- <fileset dir="${basedir}">
- <exclude name=".*/**"/>
- <exclude name="output/**"/>
- <exclude name="build.properties"/>
- </fileset>
- </copy>
-
- </target>
-
-
- <!-- ================= DIST: Create Windows Installer =================== -->
- <target name="installer"
- description="Create Windows 32-bit installer" unless="skip.installer">
-
- <echo message="Builds a Windows installer based on Nullsoft Installer"/>
- <copy todir="${tomcat.dist}">
- <fileset dir="res" />
- </copy>
- <copy file="${nsis.installoptions.dll}" todir="${tomcat.dist}" />
- <copy file="${nsis.nsexec.dll}" todir="${tomcat.dist}" />
- <copy file="${nsis.nsisdl.dll}" todir="${tomcat.dist}" />
- <copy todir="${tomcat.dist}/bin">
- <fileset dir="res/procrun/" includes="jboss*.exe"/>
- </copy>
- <copy todir="${tomcat.dist}/bin">
- <fileset dir="${jbossnative.dlls}" includes="*.dll"/>
- </copy>
- <copy todir="${tomcat.dist}/bin" file="${jbossnative.openssl}" />
-
- <filter token="VERSION" value="${version}"/>
- <filter token="VERSION_NUMBER" value="${version.number}"/>
-
- <copy file="res/jboss-web.nsi" tofile="${tomcat.dist}/jboss-web.nsi" filtering="true" overwrite="true"/>
- <exec dir="${tomcat.dist}" executable="${nsis.exe}" osfamily="windows">
- <arg value="/DNSISDIR=${nsis.home}" />
- <arg value="jboss-web.nsi" />
- </exec>
- <exec dir="${tomcat.dist}" executable="wine" osfamily="unix">
- <arg value="${nsis.exe}" />
- <arg value="/DNSISDIR=${nsis.home}" />
- <arg value="jboss-web.nsi" />
- </exec>
-
- <move file="${tomcat.dist}/jboss-web-installer.exe" tofile="${tomcat.release}/v${version}/bin/${final.name}.exe" />
-
- <checksum file="${tomcat.release}/v${version}/bin/${final.name}.exe"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/bin/${final.name}.exe.md5"
- message="${md5sum.binary-prefix}${final.name}.exe${line.separator}" append="true" />
- </target>
-
-
- <!-- ==================== RELEASE: Create Release ======================= -->
- <target name="release" depends="clean,dist-static,installer,package-zip,package-tgz,dist-source,dist-javadoc,package-docs-tgz,package-src-zip,package-src-tgz"
- description="Create a JBoss Web packaged distribution">
-
- <filter token="VERSION" value="${version}"/>
- <copy file="KEYS"
- todir="${tomcat.release}/v${version}"/>
- <copy file="RELEASE-NOTES"
- todir="${tomcat.release}/v${version}"
- filtering="true"/>
-
- <!--
- <copy file="res/welcome.main.html"
- tofile="${tomcat.release}/v${version}/README.html"
- filtering="true"/>
- <copy file="res/welcome.bin.html"
- tofile="${tomcat.release}/v${version}/bin/README.html"
- filtering="true"/>
-
- <mkdir dir="${tomcat.release}/v${version}/bin/extras" />
- <copy todir="${tomcat.release}/v${version}/bin/extras">
- <fileset dir="${tomcat.extras}">
- <include name="*.*"/>
- </fileset>
- </copy>
- -->
-
- </target>
-
- <target name="maven" description="Upload to Maven repository; if this looks like a hack, it's because it's one">
-
- <filter token="VERSION" value="${version}"/>
- <copy todir="${tomcat.jars}" filtering="true">
- <fileset dir="res">
- <include name="*-pom.xml"/>
- </fileset>
- </copy>
-
- <!-- Maven repository configuration -->
- <property name="maven.repository.url" value="file:///somepath"/>
- <property name="maven.repository.id" value="repository.jboss.org"/>
- <!--<property name="maven.repository.url" value="dav:https://snapshots.jboss.org/maven2"/>
- <property name="maven.repository.id" value="snapshots.jboss.org"/>-->
-
- <!-- Linux/Unix execs -->
- <!--
- <exec dir="." executable="/bin/sh" os="Linux">
- <arg value="-c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/el-api.jar -DpomFile=${tomcat.jars}/el-api-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- -->
- <exec dir="." executable="/bin/sh" os="Linux">
- <arg value="-c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jasper-jdt.jar -DpomFile=${tomcat.jars}/jasper-jdt-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- <exec dir="." executable="/bin/sh" os="Linux">
- <arg value="-c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb.jar -DpomFile=${tomcat.jars}/jbossweb-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- <!--
- <exec dir="." executable="/bin/sh" os="Linux">
- <arg value="-c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jsp-api.jar -DpomFile=${tomcat.jars}/jsp-api-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- <exec dir="." executable="/bin/sh" os="Linux">
- <arg value="-c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/servlet-api.jar -DpomFile=${tomcat.jars}/servlet-api-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- -->
- <exec dir="." executable="/bin/sh" os="Linux">
- <arg value="-c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb-src.zip -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id} -DgroupId=jboss.web -DartifactId=jbossweb -Dversion=${version} -Dclassifier=sources"/>
- </exec>
-
- <!-- Windows exec -->
- <!--
- <exec dir="." executable="cmd" os="Windows NT">
- <arg value="/c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/el-api.jar -DpomFile=${tomcat.jars}/el-api-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- -->
- <exec dir="." executable="cmd" os="Windows NT">
- <arg value="/c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jasper-jdt.jar -DpomFile=${tomcat.jars}/jasper-jdt-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- <exec dir="." executable="cmd" os="Windows NT">
- <arg value="/c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb.jar -DpomFile=${tomcat.jars}/jbossweb-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- <!--
- <exec dir="." executable="cmd" os="Windows NT">
- <arg value="/c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jsp-api.jar -DpomFile=${tomcat.jars}/jsp-api-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- <exec dir="." executable="cmd" os="Windows NT">
- <arg value="/c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/servlet-api.jar -DpomFile=${tomcat.jars}/servlet-api-pom.xml -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id}"/>
- </exec>
- -->
- <exec dir="." executable="cmd" os="Windows NT">
- <arg value="/c" />
- <arg value="mvn deploy:deploy-file -Dfile=${tomcat.jars}/jbossweb-src.zip -Durl=${maven.repository.url} -Dpackaging=jar -DrepositoryId=${maven.repository.id} -DgroupId=jboss.web -DartifactId=jbossweb -Dversion=${version} -Dclassifier=sources"/>
- </exec>
-
- </target>
-
- <!-- Packages the core zip distro -->
- <target name="package-zip">
- <copy todir="${tomcat.dist}/bin">
- <fileset dir="res/procrun/" includes="jboss*.exe"/>
- </copy>
- <zip zipfile="${tomcat.release}/v${version}/bin/${final.name}.zip">
- <zipfileset dir="${tomcat.dist}" prefix="${final.name}">
- <include name="bin/**"/>
- <include name="conf/**"/>
- <include name="logs/**"/>
- <include name="lib/**"/>
- <include name="webapps/**"/>
- <include name="work/**"/>
- <include name="temp/**"/>
- <include name="LICENSE"/>
- <include name="NOTICE"/>
- <include name="README.txt"/>
- <include name="RELEASE-NOTES"/>
- <include name="RUNNING.txt"/>
- <include name="BENCHMARKS.txt"/>
- <!-- If we choose not to have service binaries by default
- the exclude.service.binaries must be defined
- in build.properties or in this file
- -->
- <exclude name="bin/*.exe" if="exclude.service.binaries"/>
- <exclude name="bin/service.bat" if="exclude.service.binaries"/>
- </zipfileset>
- </zip>
-
- <checksum file="${tomcat.release}/v${version}/bin/${final.name}.zip"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/bin/${final.name}.zip.md5"
- message="${md5sum.binary-prefix}${final.name}.zip${line.separator}" append="true" />
- </target>
-
- <!-- Packages the deployer distribution in zip format -->
- <target name="package-deployer-zip">
- <zip zipfile="${tomcat.release}/v${version}/bin/${final.name}-deployer.zip">
- <zipfileset dir="${tomcat.deployer}" prefix="${final.name}-deployer" includes="**" />
- <zipfileset dir="${tomcat.dist}" prefix="${final.name}-deployer" includes="LICENSE" />
- <zipfileset dir="${tomcat.dist}" prefix="${final.name}-deployer" includes="NOTICE" />
- <zipfileset dir="${tomcat.dist}" prefix="${final.name}-deployer" includes="README.txt" />
- <zipfileset dir="${tomcat.dist}" prefix="${final.name}-deployer" includes="RELEASE-NOTES" />
- </zip>
-
- <checksum file="${tomcat.release}/v${version}/bin/${final.name}-deployer.zip"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/bin/${final.name}-deployer.zip.md5"
- message="${md5sum.binary-prefix}${final.name}-deployer.zip${line.separator}" append="true" />
- </target>
-
- <!-- Packages the core tar.gz distro -->
- <target name="package-tgz">
- <fixcrlf srcdir="${tomcat.dist}" includes="*.txt,LICENSE,NOTICE" eol="lf" encoding="ISO-8859-1" fixlast="false"/>
- <fixcrlf srcdir="${tomcat.dist}/conf" eol="lf" encoding="ISO-8859-1" fixlast="false"/>
- <tar longfile="gnu" compression="gzip"
- tarfile="${tomcat.release}/v${version}/bin/${final.name}.tar.gz">
- <tarfileset dir="${tomcat.dist}" mode="755" prefix="${final.name}">
- <include name="bin/catalina.sh" />
- <include name="bin/digest.sh" />
- <include name="bin/jasper.sh" />
- <include name="bin/jspc.sh" />
- <include name="bin/setclasspath.sh" />
- <include name="bin/startup.sh" />
- <include name="bin/shutdown.sh" />
- <include name="bin/tool-wrapper.sh" />
- <include name="bin/tool-wrapper-using-launcher.sh" />
- <include name="bin/shutdown-using-launcher.sh" />
- <include name="bin/startup-using-launcher.sh" />
- </tarfileset>
- <tarfileset dir="${tomcat.dist}" mode="600" prefix="${final.name}">
- <include name="conf/**" />
- </tarfileset>
- <tarfileset dir="${tomcat.dist}" prefix="${final.name}">
- <include name="bin/**" />
- <include name="lib/**" />
- <include name="logs/**" />
- <include name="temp/**" />
- <include name="webapps/**" />
- <include name="work/**" />
- <include name="LICENSE" />
- <include name="NOTICE" />
- <include name="README.txt" />
- <include name="RELEASE-NOTES" />
- <include name="RUNNING.txt" />
- <include name="BENCHMARKS.txt" />
- <exclude name="bin/catalina.sh" />
- <exclude name="bin/digest.sh" />
- <exclude name="bin/jasper.sh" />
- <exclude name="bin/jspc.sh" />
- <exclude name="bin/setclasspath.sh" />
- <exclude name="bin/startup.sh" />
- <exclude name="bin/shutdown.sh" />
- <exclude name="bin/tool-wrapper.sh" />
- <exclude name="bin/tool-wrapper-using-launcher.sh" />
- <exclude name="bin/shutdown-using-launcher.sh" />
- <exclude name="bin/startup-using-launcher.sh" />
- <exclude name="conf/**" />
- <exclude name="src/**" />
- <exclude name="bin/*.dll"/>
- <exclude name="bin/*.exe"/>
- <exclude name="bin/service.bat"/>
- <!-- Do we need windows .bat files as part of .tgz?
- If not apply the following rule
- <exclude name="bin/*.bat"/>
- -->
- </tarfileset>
- </tar>
-
- <checksum file="${tomcat.release}/v${version}/bin/${final.name}.tar.gz"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/bin/${final.name}.tar.gz.md5"
- message="${md5sum.binary-prefix}${final.name}.tar.gz${line.separator}" append="true" />
- </target>
-
- <!-- Packages the deployer Tomcat distro in tar.gz format -->
- <target name="package-deployer-tgz">
- <fixcrlf srcdir="${tomcat.dist}"
- includes="*.txt,LICENSE,NOTICE" eol="lf" encoding="ISO-8859-1" fixlast="false"/>
- <fixcrlf srcdir="${tomcat.deployer}" includes="*.xml" eol="lf" encoding="ISO-8859-1" fixlast="false"/>
-
- <tar longfile="gnu" compression="gzip"
- tarfile="${tomcat.release}/v${version}/bin/${final.name}-deployer.tar.gz">
- <tarfileset dir="${tomcat.dist}" prefix="${final.name}-deployer">
- <include name="LICENSE" />
- <include name="NOTICE" />
- <include name="README.txt" />
- <include name="RELEASE-NOTES" />
- </tarfileset>
- <tarfileset dir="${tomcat.deployer}" prefix="${final.name}-deployer">
- <include name="**" />
- </tarfileset>
- </tar>
-
- <checksum file="${tomcat.release}/v${version}/bin/${final.name}-deployer.tar.gz"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/bin/${final.name}-deployer.tar.gz.md5"
- message="${md5sum.binary-prefix}${final.name}-deployer.tar.gz${line.separator}" append="true" />
- </target>
-
- <!-- Packages the documentation distro in tar.gz format -->
- <target name="package-docs-tgz">
-
- <!-- Package gocs -->
- <fixcrlf srcdir="${tomcat.dist}" includes="*.txt,LICENSE,NOTICE" eol="lf" encoding="ISO-8859-1" fixlast="false"/>
-
- <tar longfile="gnu" compression="gzip"
- tarfile="${tomcat.release}/v${version}/bin/${final.name}-fulldocs.tar.gz">
- <tarfileset dir="${tomcat.dist}" prefix="jboss-web-doc">
- <include name="LICENSE" />
- <include name="NOTICE" />
- <include name="README.txt" />
- <include name="RUNNING.txt" />
- </tarfileset>
- <tarfileset dir="${tomcat.dist}/webapps/docs" prefix="jboss-web-doc">
- <include name="**" />
- </tarfileset>
- </tar>
-
- <checksum file="${tomcat.release}/v${version}/bin/${final.name}-fulldocs.tar.gz"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/bin/${final.name}-fulldocs.tar.gz.md5"
- message="${md5sum.binary-prefix}${final.name}-fulldocs.tar.gz${line.separator}" append="true" />
- </target>
-
- <!-- Packages the source code distribution in zip format -->
- <target name="package-src-zip">
- <zip zipfile="${tomcat.release}/v${version}/src/${final-src.name}.zip">
- <zipfileset dir="${tomcat.dist}/src" prefix="${final-src.name}" />
- </zip>
-
- <checksum file="${tomcat.release}/v${version}/src/${final-src.name}.zip"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/src/${final-src.name}.zip.md5"
- message="${md5sum.binary-prefix}${final-src.name}.zip${line.separator}" append="true" />
- </target>
-
- <!-- Packages the source code distribution in tar.gz format -->
- <target name="package-src-tgz">
- <fixcrlf srcdir="${tomcat.dist}/src"
- excludes="**/*.jar,**/*.gif,**/*.bmp,**/*.jpg,**/*.ico,**/*.war,**/*.exe,**/*.pdf,**/*.bin,**/*.dia" eol="lf"
- encoding="ISO-8859-1" fixlast="false"/>
- <tar longfile="gnu" compression="gzip"
- tarfile="${tomcat.release}/v${version}/src/${final-src.name}.tar.gz">
- <tarfileset dir="${tomcat.dist}/src" prefix="${final-src.name}" />
- </tar>
- <checksum file="${tomcat.release}/v${version}/src/${final-src.name}.tar.gz"
- forceOverwrite="yes" fileext=".md5" />
- <echo file="${tomcat.release}/v${version}/src/${final-src.name}.tar.gz.md5"
- message="${md5sum.binary-prefix}${final-src.name}.tar.gz${line.separator}" append="true" />
- </target>
-
-</project>
14 years, 9 months
JBossWeb SVN: r1410 - in trunk: webapps/docs and 1 other directory.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-12 13:44:44 -0500 (Fri, 12 Mar 2010)
New Revision: 1410
Added:
trunk/java/org/apache/catalina/filters/Constants.java
trunk/java/org/apache/catalina/filters/FilterBase.java
trunk/java/org/apache/catalina/filters/LocalStrings.properties
trunk/java/org/apache/catalina/filters/LocalStrings_es.properties
trunk/java/org/apache/catalina/filters/LocalStrings_fr.properties
trunk/java/org/apache/catalina/filters/RemoteAddrFilter.java
trunk/java/org/apache/catalina/filters/RemoteHostFilter.java
trunk/java/org/apache/catalina/filters/RemoteIpFilter.java
trunk/java/org/apache/catalina/filters/RequestDumperFilter.java
trunk/java/org/apache/catalina/filters/RequestFilter.java
Modified:
trunk/webapps/docs/changelog.xml
Log:
- Port utility filters from Tomcat.
Added: trunk/java/org/apache/catalina/filters/Constants.java
===================================================================
--- trunk/java/org/apache/catalina/filters/Constants.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/Constants.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.filters;
+
+
+/**
+ * Manifest constants for this Java package.
+ *
+ *
+ * @author Craig R. McClanahan
+ * @version $Revision: 794798 $ $Date: 2009-07-16 21:34:49 +0200 (Thu, 16 Jul 2009) $
+ */
+
+public final class Constants {
+
+ public static final String Package = "org.apache.catalina.filters";
+
+}
Added: trunk/java/org/apache/catalina/filters/FilterBase.java
===================================================================
--- trunk/java/org/apache/catalina/filters/FilterBase.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/FilterBase.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.filters;
+
+import java.util.Enumeration;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+
+import org.apache.tomcat.util.IntrospectionUtils;
+import org.apache.tomcat.util.res.StringManager;
+
+/**
+ * Base class for filters that provides generic initialisation and a simple
+ * no-op destruction.
+ *
+ * @author xxd
+ *
+ */
+public abstract class FilterBase implements Filter {
+
+ protected static final StringManager sm =
+ StringManager.getManager(Constants.Package);
+
+ public void init(FilterConfig filterConfig) throws ServletException {
+ Enumeration<String> paramNames = filterConfig.getInitParameterNames();
+ while (paramNames.hasMoreElements()) {
+ String paramName = paramNames.nextElement();
+ if (!IntrospectionUtils.setProperty(this, paramName,
+ filterConfig.getInitParameter(paramName))) {
+ filterConfig.getServletContext().log(sm.getString("filterbase.noSuchProperty",
+ paramName, this.getClass().getName()));
+ }
+ }
+ }
+
+ @Override
+ public void destroy() {
+ // NOOP
+ }
+
+}
Added: trunk/java/org/apache/catalina/filters/LocalStrings.properties
===================================================================
--- trunk/java/org/apache/catalina/filters/LocalStrings.properties (rev 0)
+++ trunk/java/org/apache/catalina/filters/LocalStrings.properties 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+
+filterbase.noSuchProperty=The property "{0}" is not defined for filters of type "{1}"
+
+http.403=Access to the specified resource ({0}) has been forbidden.
Added: trunk/java/org/apache/catalina/filters/LocalStrings_es.properties
===================================================================
--- trunk/java/org/apache/catalina/filters/LocalStrings_es.properties (rev 0)
+++ trunk/java/org/apache/catalina/filters/LocalStrings_es.properties 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+
+http.403=El acceso al recurso especificado ({0}) ha sido prohibido.
Added: trunk/java/org/apache/catalina/filters/LocalStrings_fr.properties
===================================================================
--- trunk/java/org/apache/catalina/filters/LocalStrings_fr.properties (rev 0)
+++ trunk/java/org/apache/catalina/filters/LocalStrings_fr.properties 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+
+http.403=L''acc\u00e8s \u00e0 la ressource demand\u00e9e ({0}) a \u00e9t\u00e9 interdit.
Added: trunk/java/org/apache/catalina/filters/RemoteAddrFilter.java
===================================================================
--- trunk/java/org/apache/catalina/filters/RemoteAddrFilter.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/RemoteAddrFilter.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.filters;
+
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.jboss.servlet.http.HttpEvent;
+import org.jboss.servlet.http.HttpEventFilterChain;
+
+
+/**
+ * Concrete implementation of <code>RequestFilter</code> that filters
+ * based on the string representation of the remote client's IP address.
+ *
+ * @author Craig R. McClanahan
+ *
+ */
+
+public final class RemoteAddrFilter
+ extends RequestFilter {
+
+ // --------------------------------------------------------- Public Methods
+
+
+ /**
+ * Extract the desired request property, and pass it (along with the
+ * specified request and response objects and associated filter chain) to
+ * the protected <code>process()</code> method to perform the actual
+ * filtering.
+ *
+ * @param request The servlet request to be processed
+ * @param response The servlet response to be created
+ * @param chain The filter chain for this request
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+
+ process(request.getRemoteAddr(), request, response, chain);
+
+ }
+
+ /**
+ * Extract the desired request property, and pass it (along with the comet
+ * event and filter chain) to the protected <code>process()</code> method
+ * to perform the actual filtering.
+ *
+ * @param event The comet event to be processed
+ * @param chain The filter chain for this event
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ @Override
+ public void doFilterEvent(HttpEvent event, HttpEventFilterChain chain)
+ throws IOException, ServletException {
+ processCometEvent(event.getHttpServletRequest().getRemoteHost(),
+ event, chain);
+ }
+
+}
Added: trunk/java/org/apache/catalina/filters/RemoteHostFilter.java
===================================================================
--- trunk/java/org/apache/catalina/filters/RemoteHostFilter.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/RemoteHostFilter.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.filters;
+
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.jboss.servlet.http.HttpEvent;
+import org.jboss.servlet.http.HttpEventFilterChain;
+
+
+/**
+ * Concrete implementation of <code>RequestFilter</code> that filters
+ * based on the remote client's host name.
+ *
+ * @author Craig R. McClanahan
+ *
+ */
+
+public final class RemoteHostFilter
+ extends RequestFilter {
+
+
+ // --------------------------------------------------------- Public Methods
+
+
+ /**
+ * Extract the desired request property, and pass it (along with the
+ * specified request and response objects and associated filter chain) to
+ * the protected <code>process()</code> method to perform the actual
+ * filtering.
+ *
+ * @param request The servlet request to be processed
+ * @param response The servlet response to be created
+ * @param chain The filter chain for this request
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+
+ process(request.getRemoteHost(), request, response, chain);
+
+ }
+
+ /**
+ * Extract the desired request property, and pass it (along with the comet
+ * event and filter chain) to the protected <code>process()</code> method
+ * to perform the actual filtering.
+ *
+ * @param event The comet event to be processed
+ * @param chain The filter chain for this event
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ @Override
+ public void doFilterEvent(HttpEvent event, HttpEventFilterChain chain)
+ throws IOException, ServletException {
+ processCometEvent(event.getHttpServletRequest().getRemoteHost(),
+ event, chain);
+ }
+
+}
Added: trunk/java/org/apache/catalina/filters/RemoteIpFilter.java
===================================================================
--- trunk/java/org/apache/catalina/filters/RemoteIpFilter.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/RemoteIpFilter.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,969 @@
+/*
+ * 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.filters;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * <p>
+ * Servlet filter to integrate "X-Forwarded-For" and "X-Forwarded-Proto" HTTP headers.
+ * </p>
+ * <p>
+ * Most of the design of this Servlet Filter is a port of <a
+ * href="http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this servlet filter replaces the apparent client remote
+ * IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g.
+ * "X-Forwarded-For").
+ * </p>
+ * <p>
+ * Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme presented by a
+ * proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto").
+ * </p>
+ * <p>
+ * This servlet filter proceeds as follows:
+ * </p>
+ * <p>
+ * If the incoming <code>request.getRemoteAddr()</code> matches the servlet filter's list of internal proxies :
+ * <ul>
+ * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http
+ * header named <code>$remoteIPHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li>
+ * <li>For each ip/host of the list:
+ * <ul>
+ * <li>if it matches the internal proxies list, the ip/host is swallowed</li>
+ * <li>if it matches the trusted proxies list, the ip/host is added to the created proxies header</li>
+ * <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li>
+ * </ul>
+ * </li>
+ * <li>If the request http header named <code>$protocolHeader</code> (e.g. <code>x-forwarded-for</code>) equals to the value of
+ * <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>,
+ * <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the
+ * <code>$httpsServerPort</code> configuration parameter.</li>
+ * </ul>
+ * </p>
+ * <p>
+ * <strong>Configuration parameters:</strong>
+ * <table border="1">
+ * <tr>
+ * <th>XForwardedFilter property</th>
+ * <th>Description</th>
+ * <th>Equivalent mod_remoteip directive</th>
+ * <th>Format</th>
+ * <th>Default Value</th>
+ * </tr>
+ * <tr>
+ * <td>remoteIPHeader</td>
+ * <td>Name of the Http Header read by this servlet filter that holds the list of traversed IP addresses starting from the requesting client
+ * </td>
+ * <td>RemoteIPHeader</td>
+ * <td>Compliant http header name</td>
+ * <td>x-forwarded-for</td>
+ * </tr>
+ * <tr>
+ * <td>internalProxies</td>
+ * <td>List of internal proxies ip adress. If they appear in the <code>remoteIpHeader</code> value, they will be trusted and will not appear
+ * in the <code>proxiesHeader</code> value</td>
+ * <td>RemoteIPInternalProxy</td>
+ * <td>Comma delimited list of regular expressions (in the syntax supported by the {@link java.util.regex.Pattern} library)</td>
+ * <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}, 192\.168\.\d{1,3}\.\d{1,3}, 169\.254\.\d{1,3}\.\d{1,3}, 127\.\d{1,3}\.\d{1,3}\.\d{1,3} <br/>
+ * By default, 10/8, 192.168/16, 169.254/16 and 127/8 are allowed ; 172.16/12 has not been enabled by default because it is complex to
+ * describe with regular expressions</td>
+ * </tr>
+ * </tr>
+ * <tr>
+ * <td>proxiesHeader</td>
+ * <td>Name of the http header created by this servlet filter to hold the list of proxies that have been processed in the incoming
+ * <code>remoteIPHeader</code></td>
+ * <td>RemoteIPProxiesHeader</td>
+ * <td>Compliant http header name</td>
+ * <td>x-forwarded-by</td>
+ * </tr>
+ * <tr>
+ * <td>trustedProxies</td>
+ * <td>List of trusted proxies ip adress. If they appear in the <code>remoteIpHeader</code> value, they will be trusted and will appear in
+ * the <code>proxiesHeader</code> value</td>
+ * <td>RemoteIPTrustedProxy</td>
+ * <td>Comma delimited list of regular expressions (in the syntax supported by the {@link java.util.regex.Pattern} library)</td>
+ * <td> </td>
+ * </tr>
+ * <tr>
+ * <td>protocolHeader</td>
+ * <td>Name of the http header read by this servlet filter that holds the flag that this request</td>
+ * <td>N/A</td>
+ * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td>
+ * <td><code>null</code></td>
+ * </tr>
+ * <tr>
+ * <td>protocolHeaderHttpsValue</td>
+ * <td>Value of the <code>protocolHeader</code> to indicate that it is an Https request</td>
+ * <td>N/A</td>
+ * <td>String like <code>https</code> or <code>ON</code></td>
+ * <td><code>https</code></td>
+ * </tr>
+ * <tr>
+ * <td>httpServerPort</td>
+ * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td>
+ * <td>N/A</td>
+ * <td>integer</td>
+ * <td>80</td>
+ * </tr>
+ * <tr>
+ * <td>httpsServerPort</td>
+ * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td>
+ * <td>N/A</td>
+ * <td>integer</td>
+ * <td>443</td>
+ * </tr>
+ * </table>
+ * </p>
+ * <p>
+ * <p>
+ * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g.
+ * <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as the JVM doesn't have a
+ * library similar to <a
+ * href="http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8...">apr_ipsubnet_test</a>, we rely on
+ * regular expressions.
+ * </p>
+ * <hr/>
+ * <p>
+ * <strong>Sample with internal proxies</strong>
+ * </p>
+ * <p>
+ * XForwardedFilter configuration:
+ * </p>
+ * <code><pre>
+ * <filter>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
+ * <init-param>
+ * <param-name>internalProxies</param-name><param-value>192\.168\.0\.10, 192\.168\.0\.11</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPHeader</param-name><param-value>x-forwarded-for</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPProxiesHeader</param-name><param-value>x-forwarded-by</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>protocolHeader</param-name><param-value>x-forwarded-proto</param-value>
+ * </init-param>
+ * </filter>
+ *
+ * <filter-mapping>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <url-pattern>/*</url-pattern>
+ * <dispatcher>REQUEST</dispatcher>
+ * </filter-mapping></pre></code>
+ * <p>
+ * Request values:
+ * <table border="1">
+ * <tr>
+ * <th>property</th>
+ * <th>Value Before RemoteIpFilter</th>
+ * <th>Value After RemoteIpFilter</th>
+ * </tr>
+ * <tr>
+ * <td>request.remoteAddr</td>
+ * <td>192.168.0.10</td>
+ * <td>140.211.11.130</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-for']</td>
+ * <td>140.211.11.130, 192.168.0.10</td>
+ * <td>null</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-by']</td>
+ * <td>null</td>
+ * <td>null</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-proto']</td>
+ * <td>https</td>
+ * <td>https</td>
+ * </tr>
+ * <tr>
+ * <td>request.scheme</td>
+ * <td>http</td>
+ * <td>https</td>
+ * </tr>
+ * <tr>
+ * <td>request.secure</td>
+ * <td>false</td>
+ * <td>true</td>
+ * </tr>
+ * <tr>
+ * <td>request.serverPort</td>
+ * <td>80</td>
+ * <td>443</td>
+ * </tr>
+ * </table>
+ * Note : <code>x-forwarded-by</code> header is null because only internal proxies as been traversed by the request.
+ * <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
+ * </p>
+ * <hr/>
+ * <p>
+ * <strong>Sample with trusted proxies</strong>
+ * </p>
+ * <p>
+ * RemoteIpFilter configuration:
+ * </p>
+ * <code><pre>
+ * <filter>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
+ * <init-param>
+ * <param-name>internalProxies</param-name><param-value>192\.168\.0\.10, 192\.168\.0\.11</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPHeader</param-name><param-value>x-forwarded-for</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPProxiesHeader</param-name><param-value>x-forwarded-by</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>trustedProxies</param-name><param-value>proxy1, proxy2</param-value>
+ * </init-param>
+ * </filter>
+ *
+ * <filter-mapping>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <url-pattern>/*</url-pattern>
+ * <dispatcher>REQUEST</dispatcher>
+ * </filter-mapping></pre></code>
+ * <p>
+ * Request values:
+ * <table border="1">
+ * <tr>
+ * <th>property</th>
+ * <th>Value Before RemoteIpFilter</th>
+ * <th>Value After RemoteIpFilter</th>
+ * </tr>
+ * <tr>
+ * <td>request.remoteAddr</td>
+ * <td>192.168.0.10</td>
+ * <td>140.211.11.130</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-for']</td>
+ * <td>140.211.11.130, proxy1, proxy2</td>
+ * <td>null</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-by']</td>
+ * <td>null</td>
+ * <td>proxy1, proxy2</td>
+ * </tr>
+ * </table>
+ * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
+ * are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
+ * </p>
+ * <hr/>
+ * <p>
+ * <strong>Sample with internal and trusted proxies</strong>
+ * </p>
+ * <p>
+ * RemoteIpFilter configuration:
+ * </p>
+ * <code><pre>
+ * <filter>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
+ * <init-param>
+ * <param-name>internalProxies</param-name><param-value>192\.168\.0\.10, 192\.168\.0\.11</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPHeader</param-name><param-value>x-forwarded-for</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPProxiesHeader</param-name><param-value>x-forwarded-by</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>trustedProxies</param-name><param-value>proxy1, proxy2</param-value>
+ * </init-param>
+ * </filter>
+ *
+ * <filter-mapping>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <url-pattern>/*</url-pattern>
+ * <dispatcher>REQUEST</dispatcher>
+ * </filter-mapping></pre></code>
+ * <p>
+ * Request values:
+ * <table border="1">
+ * <tr>
+ * <th>property</th>
+ * <th>Value Before RemoteIpFilter</th>
+ * <th>Value After RemoteIpFilter</th>
+ * </tr>
+ * <tr>
+ * <td>request.remoteAddr</td>
+ * <td>192.168.0.10</td>
+ * <td>140.211.11.130</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-for']</td>
+ * <td>140.211.11.130, proxy1, proxy2, 192.168.0.10</td>
+ * <td>null</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-by']</td>
+ * <td>null</td>
+ * <td>proxy1, proxy2</td>
+ * </tr>
+ * </table>
+ * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
+ * are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in
+ * <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
+ * </p>
+ * <hr/>
+ * <p>
+ * <strong>Sample with an untrusted proxy</strong>
+ * </p>
+ * <p>
+ * RemoteIpFilter configuration:
+ * </p>
+ * <code><pre>
+ * <filter>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
+ * <init-param>
+ * <param-name>internalProxies</param-name><param-value>192\.168\.0\.10, 192\.168\.0\.11</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPHeader</param-name><param-value>x-forwarded-for</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>remoteIPProxiesHeader</param-name><param-value>x-forwarded-by</param-value>
+ * </init-param>
+ * <init-param>
+ * <param-name>trustedProxies</param-name><param-value>proxy1, proxy2</param-value>
+ * </init-param>
+ * </filter>
+ *
+ * <filter-mapping>
+ * <filter-name>RemoteIpFilter</filter-name>
+ * <url-pattern>/*</url-pattern>
+ * <dispatcher>REQUEST</dispatcher>
+ * </filter-mapping></pre></code>
+ * <p>
+ * Request values:
+ * <table border="1">
+ * <tr>
+ * <th>property</th>
+ * <th>Value Before RemoteIpFilter</th>
+ * <th>Value After RemoteIpFilter</th>
+ * </tr>
+ * <tr>
+ * <td>request.remoteAddr</td>
+ * <td>192.168.0.10</td>
+ * <td>untrusted-proxy</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-for']</td>
+ * <td>140.211.11.130, untrusted-proxy, proxy1</td>
+ * <td>140.211.11.130</td>
+ * </tr>
+ * <tr>
+ * <td>request.header['x-forwarded-by']</td>
+ * <td>null</td>
+ * <td>proxy1</td>
+ * </tr>
+ * </table>
+ * Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds
+ * <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we can not trust that
+ * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP
+ * verified by <code>proxy1</code>.
+ * </p>
+ * <hr/>
+ */
+public class RemoteIpFilter implements Filter {
+ public static class XForwardedRequest extends HttpServletRequestWrapper {
+
+ final static ThreadLocal<SimpleDateFormat[]> threadLocalDateFormats = new ThreadLocal<SimpleDateFormat[]>() {
+ @Override
+ protected SimpleDateFormat[] initialValue() {
+ return new SimpleDateFormat[] {
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
+ new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
+ new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)
+ };
+
+ }
+ };
+
+ protected Map<String, List<String>> headers;
+
+ protected String remoteAddr;
+
+ protected String remoteHost;
+
+ protected String scheme;
+
+ protected boolean secure;
+
+ protected int serverPort;
+
+ public XForwardedRequest(HttpServletRequest request) {
+ super(request);
+ this.remoteAddr = request.getRemoteAddr();
+ this.remoteHost = request.getRemoteHost();
+ this.scheme = request.getScheme();
+ this.secure = request.isSecure();
+ this.serverPort = request.getServerPort();
+
+ headers = new HashMap<String, List<String>>();
+ for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
+ String header = headerNames.nextElement();
+ headers.put(header, Collections.list(request.getHeaders(header)));
+ }
+ }
+
+ @Override
+ public long getDateHeader(String name) {
+ String value = getHeader(name);
+ if (value == null) {
+ return -1;
+ }
+ DateFormat[] dateFormats = threadLocalDateFormats.get();
+ Date date = null;
+ for (int i = 0; ((i < dateFormats.length) && (date == null)); i++) {
+ DateFormat dateFormat = dateFormats[i];
+ try {
+ date = dateFormat.parse(value);
+ } catch (Exception ParseException) {
+ // Ignore
+ }
+ }
+ if (date == null) {
+ throw new IllegalArgumentException(value);
+ }
+ return date.getTime();
+ }
+
+ @Override
+ public String getHeader(String name) {
+ Map.Entry<String, List<String>> header = getHeaderEntry(name);
+ if (header == null || header.getValue() == null || header.getValue().isEmpty()) {
+ return null;
+ }
+ return header.getValue().get(0);
+ }
+
+ protected Map.Entry<String, List<String>> getHeaderEntry(String name) {
+ for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(name)) {
+ return entry;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public Enumeration<String> getHeaderNames() {
+ return Collections.enumeration(headers.keySet());
+ }
+
+ @Override
+ public Enumeration<String> getHeaders(String name) {
+ Map.Entry<String, List<String>> header = getHeaderEntry(name);
+ if (header == null || header.getValue() == null) {
+ return Collections.enumeration(Collections.<String>emptyList());
+ }
+ return Collections.enumeration(header.getValue());
+ }
+
+ @Override
+ public int getIntHeader(String name) {
+ String value = getHeader(name);
+ if (value == null) {
+ return -1;
+ }
+ return Integer.parseInt(value);
+ }
+
+ @Override
+ public String getRemoteAddr() {
+ return this.remoteAddr;
+ }
+
+ @Override
+ public String getRemoteHost() {
+ return this.remoteHost;
+ }
+
+ @Override
+ public String getScheme() {
+ return scheme;
+ }
+
+ @Override
+ public int getServerPort() {
+ return serverPort;
+ }
+
+ @Override
+ public boolean isSecure() {
+ return secure;
+ }
+
+ public void removeHeader(String name) {
+ Map.Entry<String, List<String>> header = getHeaderEntry(name);
+ if (header != null) {
+ headers.remove(header.getKey());
+ }
+ }
+
+ public void setHeader(String name, String value) {
+ List<String> values = Arrays.asList(value);
+ Map.Entry<String, List<String>> header = getHeaderEntry(name);
+ if (header == null) {
+ headers.put(name, values);
+ } else {
+ header.setValue(values);
+ }
+
+ }
+
+ public void setRemoteAddr(String remoteAddr) {
+ this.remoteAddr = remoteAddr;
+ }
+
+ public void setRemoteHost(String remoteHost) {
+ this.remoteHost = remoteHost;
+ }
+
+ public void setScheme(String scheme) {
+ this.scheme = scheme;
+ }
+
+ public void setSecure(boolean secure) {
+ this.secure = secure;
+ }
+
+ public void setServerPort(int serverPort) {
+ this.serverPort = serverPort;
+ }
+ }
+
+ /**
+ * {@link Pattern} for a comma delimited string that support whitespace characters
+ */
+ private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*");
+
+ protected static final String HTTP_SERVER_PORT_PARAMETER = "httpServerPort";
+
+ protected static final String HTTPS_SERVER_PORT_PARAMETER = "httpsServerPort";
+
+ protected static final String INTERNAL_PROXIES_PARAMETER = "internalProxies";
+
+ protected static final String PROTOCOL_HEADER_PARAMETER = "protocolHeader";
+
+ protected static final String PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER = "protocolHeaderHttpsValue";
+
+ protected static final String PROXIES_HEADER_PARAMETER = "proxiesHeader";
+
+ protected static final String REMOTE_IP_HEADER_PARAMETER = "remoteIPHeader";
+
+ protected static final String TRUSTED_PROXIES_PARAMETER = "trustedProxies";
+
+ /**
+ * Convert a given comma delimited list of regular expressions into an array of compiled {@link Pattern}
+ *
+ * @return array of patterns (not <code>null</code>)
+ */
+ protected static Pattern[] commaDelimitedListToPatternArray(String commaDelimitedPatterns) {
+ String[] patterns = commaDelimitedListToStringArray(commaDelimitedPatterns);
+ List<Pattern> patternsList = new ArrayList<Pattern>();
+ for (String pattern : patterns) {
+ try {
+ patternsList.add(Pattern.compile(pattern));
+ } catch (PatternSyntaxException e) {
+ throw new IllegalArgumentException("Illegal pattern syntax '" + pattern + "'", e);
+ }
+ }
+ return patternsList.toArray(new Pattern[0]);
+ }
+
+ /**
+ * Convert a given comma delimited list of regular expressions into an array of String
+ *
+ * @return array of patterns (non <code>null</code>)
+ */
+ protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) {
+ return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern
+ .split(commaDelimitedStrings);
+ }
+
+ /**
+ * Convert an array of strings in a comma delimited string
+ */
+ protected static String listToCommaDelimitedString(List<String> stringList) {
+ if (stringList == null) {
+ return "";
+ }
+ StringBuilder result = new StringBuilder();
+ for (Iterator<String> it = stringList.iterator(); it.hasNext();) {
+ Object element = it.next();
+ if (element != null) {
+ result.append(element);
+ if (it.hasNext()) {
+ result.append(", ");
+ }
+ }
+ }
+ return result.toString();
+ }
+
+ /**
+ * Return <code>true</code> if the given <code>str</code> matches at least one of the given <code>patterns</code>.
+ */
+ protected static boolean matchesOne(String str, Pattern... patterns) {
+ for (Pattern pattern : patterns) {
+ if (pattern.matcher(str).matches()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @see #setHttpServerPort(int)
+ */
+ private int httpServerPort = 80;
+
+ /**
+ * @see #setHttpsServerPort(int)
+ */
+ private int httpsServerPort = 443;
+
+ /**
+ * @see #setInternalProxies(String)
+ */
+ private Pattern[] internalProxies = new Pattern[] {
+ Pattern.compile("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"), Pattern.compile("192\\.168\\.\\d{1,3}\\.\\d{1,3}"),
+ Pattern.compile("169\\.254\\.\\d{1,3}\\.\\d{1,3}"), Pattern.compile("127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")
+ };
+
+ /**
+ * @see #setProtocolHeader(String)
+ */
+ private String protocolHeader = null;
+
+ private String protocolHeaderHttpsValue = "https";
+
+ /**
+ * @see #setProxiesHeader(String)
+ */
+ private String proxiesHeader = "X-Forwarded-By";
+
+ /**
+ * @see #setRemoteIPHeader(String)
+ */
+ private String remoteIPHeader = "X-Forwarded-For";
+
+ /**
+ * @see #setTrustedProxies(String)
+ */
+ private Pattern[] trustedProxies = new Pattern[0];
+
+ public void destroy() {
+ // NOOP
+ }
+
+ public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
+
+ if (matchesOne(request.getRemoteAddr(), internalProxies)) {
+ String remoteIp = null;
+ // In java 6, proxiesHeaderValue should be declared as a java.util.Deque
+ LinkedList<String> proxiesHeaderValue = new LinkedList<String>();
+
+ String[] remoteIPHeaderValue = commaDelimitedListToStringArray(request.getHeader(remoteIPHeader));
+ int idx;
+ // loop on remoteIPHeaderValue to find the first trusted remote ip and to build the proxies chain
+ for (idx = remoteIPHeaderValue.length - 1; idx >= 0; idx--) {
+ String currentRemoteIp = remoteIPHeaderValue[idx];
+ remoteIp = currentRemoteIp;
+ if (matchesOne(currentRemoteIp, internalProxies)) {
+ // do nothing, internalProxies IPs are not appended to the
+ } else if (matchesOne(currentRemoteIp, trustedProxies)) {
+ proxiesHeaderValue.addFirst(currentRemoteIp);
+ } else {
+ idx--; // decrement idx because break statement doesn't do it
+ break;
+ }
+ }
+ // continue to loop on remoteIPHeaderValue to build the new value of the remoteIPHeader
+ LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>();
+ for (; idx >= 0; idx--) {
+ String currentRemoteIp = remoteIPHeaderValue[idx];
+ newRemoteIpHeaderValue.addFirst(currentRemoteIp);
+ }
+
+ XForwardedRequest xRequest = new XForwardedRequest(request);
+ if (remoteIp != null) {
+
+ xRequest.setRemoteAddr(remoteIp);
+ xRequest.setRemoteHost(remoteIp);
+
+ if (proxiesHeaderValue.size() == 0) {
+ xRequest.removeHeader(proxiesHeader);
+ } else {
+ String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue);
+ xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies);
+ }
+ if (newRemoteIpHeaderValue.size() == 0) {
+ xRequest.removeHeader(remoteIPHeader);
+ } else {
+ String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue);
+ xRequest.setHeader(remoteIPHeader, commaDelimitedRemoteIpHeaderValue);
+ }
+ }
+
+ if (protocolHeader != null) {
+ String protocolHeaderValue = request.getHeader(protocolHeader);
+ if (protocolHeaderValue == null) {
+ // don't modify the secure,scheme and serverPort attributes of the request
+ } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) {
+ xRequest.setSecure(true);
+ xRequest.setScheme("https");
+ xRequest.setServerPort(httpsServerPort);
+ } else {
+ xRequest.setSecure(false);
+ xRequest.setScheme("http");
+ xRequest.setServerPort(httpServerPort);
+ }
+ }
+
+ chain.doFilter(xRequest, response);
+ } else {
+ chain.doFilter(request, response);
+ }
+
+ }
+
+ /**
+ * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwareded-for</code> is not empty.
+ */
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
+ doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain);
+ } else {
+ chain.doFilter(request, response);
+ }
+ }
+
+ public int getHttpsServerPort() {
+ return httpsServerPort;
+ }
+
+ public Pattern[] getInternalProxies() {
+ return internalProxies;
+ }
+
+ public String getProtocolHeader() {
+ return protocolHeader;
+ }
+
+ public String getProtocolHeaderHttpsValue() {
+ return protocolHeaderHttpsValue;
+ }
+
+ public String getProxiesHeader() {
+ return proxiesHeader;
+ }
+
+ public String getRemoteIPHeader() {
+ return remoteIPHeader;
+ }
+
+ public Pattern[] getTrustedProxies() {
+ return trustedProxies;
+ }
+
+ public void init(FilterConfig filterConfig) throws ServletException {
+ if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) {
+ setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER));
+ }
+
+ if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) {
+ setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER));
+ }
+
+ if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) {
+ setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER));
+ }
+
+ if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) {
+ setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER));
+ }
+
+ if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) {
+ setRemoteIPHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER));
+ }
+
+ if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) {
+ setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER));
+ }
+
+ if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) {
+ try {
+ setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER)));
+ } catch (NumberFormatException e) {
+ throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage());
+ }
+ }
+
+ if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) {
+ try {
+ setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER)));
+ } catch (NumberFormatException e) {
+ throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * <p>
+ * Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and
+ * has a value different of {@link #protocolHeaderHttpsValue}).
+ * </p>
+ * <p>
+ * Default value : 80
+ * </p>
+ */
+ public void setHttpServerPort(int httpServerPort) {
+ this.httpServerPort = httpServerPort;
+ }
+
+ /**
+ * <p>
+ * Server Port value if the {@link #protocolHeader} indicates HTTPS
+ * </p>
+ * <p>
+ * Default value : 443
+ * </p>
+ */
+ public void setHttpsServerPort(int httpsServerPort) {
+ this.httpsServerPort = httpsServerPort;
+ }
+
+ /**
+ * <p>
+ * Comma delimited list of internal proxies. Can be expressed with regular expressions.
+ * </p>
+ * <p>
+ * Default value : 10\.\d{1,3}\.\d{1,3}\.\d{1,3}, 192\.168\.\d{1,3}\.\d{1,3}, 127\.\d{1,3}\.\d{1,3}\.\d{1,3}
+ * </p>
+ */
+ public void setInternalProxies(String internalProxies) {
+ this.internalProxies = commaDelimitedListToPatternArray(internalProxies);
+ }
+
+ /**
+ * <p>
+ * Header that holds the incoming protocol, usally named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and
+ * request.secure will not be modified.
+ * </p>
+ * <p>
+ * Default value : <code>null</code>
+ * </p>
+ */
+ public void setProtocolHeader(String protocolHeader) {
+ this.protocolHeader = protocolHeader;
+ }
+
+ /**
+ * <p>
+ * Case insensitive value of the protocol header to indicate that the incoming http request uses HTTPS.
+ * </p>
+ * <p>
+ * Default value : <code>https</code>
+ * </p>
+ */
+ public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) {
+ this.protocolHeaderHttpsValue = protocolHeaderHttpsValue;
+ }
+
+ /**
+ * <p>
+ * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP
+ * addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header,
+ * while any intermediate RemoteIPInternalProxy addresses are discarded.
+ * </p>
+ * <p>
+ * Name of the http header that holds the list of trusted proxies that has been traversed by the http request.
+ * </p>
+ * <p>
+ * The value of this header can be comma delimited.
+ * </p>
+ * <p>
+ * Default value : <code>X-Forwarded-By</code>
+ * </p>
+ */
+ public void setProxiesHeader(String proxiesHeader) {
+ this.proxiesHeader = proxiesHeader;
+ }
+
+ /**
+ * <p>
+ * Name of the http header from which the remote ip is extracted.
+ * </p>
+ * <p>
+ * The value of this header can be comma delimited.
+ * </p>
+ * <p>
+ * Default value : <code>X-Forwarded-For</code>
+ * </p>
+ */
+ public void setRemoteIPHeader(String remoteIPHeader) {
+ this.remoteIPHeader = remoteIPHeader;
+ }
+
+ /**
+ * <p>
+ * Comma delimited list of proxies that are trusted when they appear in the {@link #remoteIPHeader} header. Can be expressed as a
+ * regular expression.
+ * </p>
+ * <p>
+ * Default value : empty list, no external proxy is trusted.
+ * </p>
+ */
+ public void setTrustedProxies(String trustedProxies) {
+ this.trustedProxies = commaDelimitedListToPatternArray(trustedProxies);
+ }
+}
Added: trunk/java/org/apache/catalina/filters/RequestDumperFilter.java
===================================================================
--- trunk/java/org/apache/catalina/filters/RequestDumperFilter.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/RequestDumperFilter.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,280 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.filters;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Enumeration;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+
+/**
+ * <p>Implementation of a Filter that logs interesting contents from the
+ * specified Request (before processing) and the corresponding Response
+ * (after processing). It is especially useful in debugging problems
+ * related to headers and cookies.</p>
+ *
+ * <p>When using this Filter, it is strongly recommended that the
+ * <code>org.apache.catalina.filter.RequestDumperFilter</code> logger is
+ * directed to a dedicated file and that the
+ * <code>org.apache.juli.VerbatimFormmater</code> is used.</p>
+ *
+ * @author Craig R. McClanahan
+ */
+
+public class RequestDumperFilter implements Filter {
+
+ private static final String NON_HTTP_REQ_MSG =
+ "Not available. Non-http request.";
+ private static final String NON_HTTP_RES_MSG =
+ "Not available. Non-http response.";
+
+ private ServletContext context;
+
+ private static final ThreadLocal<Timestamp> timestamp =
+ new ThreadLocal<Timestamp>() {
+ @Override
+ protected Timestamp initialValue() {
+ return new Timestamp();
+ }
+ };
+
+ /**
+ * Log the interesting request parameters, invoke the next Filter in the
+ * sequence, and log the interesting response parameters.
+ *
+ * @param request The servlet request to be processed
+ * @param response The servlet response to be created
+ * @param chain The filter chain being processed
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain)
+ throws IOException, ServletException {
+
+ HttpServletRequest hRequest = null;
+ HttpServletResponse hResponse = null;
+
+ if (request instanceof HttpServletRequest) {
+ hRequest = (HttpServletRequest) request;
+ }
+ if (response instanceof HttpServletResponse) {
+ hResponse = (HttpServletResponse) response;
+ }
+
+ // Log pre-service information
+ doLog("START TIME ", getTimestamp());
+
+ if (hRequest == null) {
+ doLog(" requestURI", NON_HTTP_REQ_MSG);
+ doLog(" authType", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" requestURI", hRequest.getRequestURI());
+ doLog(" authType", hRequest.getAuthType());
+ }
+
+ doLog(" characterEncoding", request.getCharacterEncoding());
+ doLog(" contentLength",
+ Integer.valueOf(request.getContentLength()).toString());
+ doLog(" contentType", request.getContentType());
+
+ if (hRequest == null) {
+ doLog(" contextPath", NON_HTTP_REQ_MSG);
+ doLog(" cookie", NON_HTTP_REQ_MSG);
+ doLog(" header", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" contextPath", hRequest.getContextPath());
+ Cookie cookies[] = hRequest.getCookies();
+ if (cookies != null) {
+ for (int i = 0; i < cookies.length; i++)
+ doLog(" cookie", cookies[i].getName() +
+ "=" + cookies[i].getValue());
+ }
+ Enumeration<String> hnames = hRequest.getHeaderNames();
+ while (hnames.hasMoreElements()) {
+ String hname = hnames.nextElement();
+ Enumeration<String> hvalues = hRequest.getHeaders(hname);
+ while (hvalues.hasMoreElements()) {
+ String hvalue = hvalues.nextElement();
+ doLog(" header", hname + "=" + hvalue);
+ }
+ }
+ }
+
+ doLog(" locale", request.getLocale().toString());
+
+ if (hRequest == null) {
+ doLog(" method", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" method", hRequest.getMethod());
+ }
+
+ Enumeration<String> pnames = request.getParameterNames();
+ while (pnames.hasMoreElements()) {
+ String pname = pnames.nextElement();
+ String pvalues[] = request.getParameterValues(pname);
+ StringBuilder result = new StringBuilder(pname);
+ result.append('=');
+ for (int i = 0; i < pvalues.length; i++) {
+ if (i > 0)
+ result.append(", ");
+ result.append(pvalues[i]);
+ }
+ doLog(" parameter", result.toString());
+ }
+
+ if (hRequest == null) {
+ doLog(" pathInfo", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" pathInfo", hRequest.getPathInfo());
+ }
+
+ doLog(" protocol", request.getProtocol());
+
+ if (hRequest == null) {
+ doLog(" queryString", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" queryString", hRequest.getQueryString());
+ }
+
+ doLog(" remoteAddr", request.getRemoteAddr());
+ doLog(" remoteHost", request.getRemoteHost());
+
+ if (hRequest == null) {
+ doLog(" remoteUser", NON_HTTP_REQ_MSG);
+ doLog("requestedSessionId", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" remoteUser", hRequest.getRemoteUser());
+ doLog("requestedSessionId", hRequest.getRequestedSessionId());
+ }
+
+ doLog(" scheme", request.getScheme());
+ doLog(" serverName", request.getServerName());
+ doLog(" serverPort",
+ Integer.valueOf(request.getServerPort()).toString());
+
+ if (hRequest == null) {
+ doLog(" servletPath", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" servletPath", hRequest.getServletPath());
+ }
+
+ doLog(" isSecure",
+ Boolean.valueOf(request.isSecure()).toString());
+ doLog("------------------",
+ "--------------------------------------------");
+
+ // Perform the request
+ chain.doFilter(request, response);
+
+ // Log post-service information
+ doLog("------------------",
+ "--------------------------------------------");
+ if (hRequest == null) {
+ doLog(" authType", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" authType", hRequest.getAuthType());
+ }
+
+ doLog(" contentType", response.getContentType());
+
+ if (hResponse == null) {
+ doLog(" header", NON_HTTP_RES_MSG);
+ } else {
+ Iterable<String> rhnames = hResponse.getHeaderNames();
+ for (String rhname : rhnames) {
+ Iterable<String> rhvalues = hResponse.getHeaders(rhname);
+ for (String rhvalue : rhvalues)
+ doLog(" header", rhname + "=" + rhvalue);
+ }
+ }
+
+ if (hRequest == null) {
+ doLog(" remoteUser", NON_HTTP_REQ_MSG);
+ } else {
+ doLog(" remoteUser", hRequest.getRemoteUser());
+ }
+
+ if (hResponse == null) {
+ doLog(" remoteUser", NON_HTTP_RES_MSG);
+ } else {
+ doLog(" status",
+ Integer.valueOf(hResponse.getStatus()).toString());
+ }
+
+ doLog("END TIME ", getTimestamp());
+ doLog("==================",
+ "============================================");
+ }
+
+ private void doLog(String attribute, String value) {
+ StringBuilder sb = new StringBuilder(80);
+ sb.append(Thread.currentThread().getName());
+ sb.append(' ');
+ sb.append(attribute);
+ sb.append('=');
+ sb.append(value);
+ if (context != null) {
+ context.log(sb.toString());
+ }
+ }
+
+ private String getTimestamp() {
+ Timestamp ts = timestamp.get();
+ long currentTime = System.currentTimeMillis();
+
+ if ((ts.date.getTime() + 999) < currentTime) {
+ ts.date.setTime(currentTime - (currentTime % 1000));
+ ts.update();
+ }
+ return ts.dateString;
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ context = filterConfig.getServletContext();
+ }
+
+ @Override
+ public void destroy() {
+ context = null;
+ }
+
+ private static final class Timestamp {
+ private Date date = new Date(0);
+ private SimpleDateFormat format =
+ new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
+ private String dateString = format.format(date);
+ private void update() {
+ dateString = format.format(date);
+ }
+ }
+}
Added: trunk/java/org/apache/catalina/filters/RequestFilter.java
===================================================================
--- trunk/java/org/apache/catalina/filters/RequestFilter.java (rev 0)
+++ trunk/java/org/apache/catalina/filters/RequestFilter.java 2010-03-12 18:44:44 UTC (rev 1410)
@@ -0,0 +1,313 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.filters;
+
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+
+import org.jboss.servlet.http.HttpEvent;
+import org.jboss.servlet.http.HttpEventFilter;
+import org.jboss.servlet.http.HttpEventFilterChain;
+
+/**
+ * Implementation of a Filter that performs filtering based on comparing the
+ * appropriate request property (selected based on which subclass you choose
+ * to configure into your Container's pipeline) against a set of regular
+ * expressions configured for this Filter.
+ * <p>
+ * This filter is configured by setting the <code>allow</code> and/or
+ * <code>deny</code> properties to a comma-delimited list of regular
+ * expressions (in the syntax supported by the jakarta-regexp library) to
+ * which the appropriate request property will be compared. Evaluation
+ * proceeds as follows:
+ * <ul>
+ * <li>The subclass extracts the request property to be filtered, and
+ * calls the common <code>process()</code> method.
+ * <li>If there are any deny expressions configured, the property will
+ * be compared to each such expression. If a match is found, this
+ * request will be rejected with a "Forbidden" HTTP response.</li>
+ * <li>If there are any allow expressions configured, the property will
+ * be compared to each such expression. If a match is found, this
+ * request will be allowed to pass through to the next filter in the
+ * current pipeline.</li>
+ * <li>If one or more deny expressions was specified but no allow expressions,
+ * allow this request to pass through (because none of the deny
+ * expressions matched it).
+ * <li>The request will be rejected with a "Forbidden" HTTP response.</li>
+ * </ul>
+ * <p>
+ * This Filter may be attached to any Container, depending on the granularity
+ * of the filtering you wish to perform.
+ *
+ * @author Craig R. McClanahan
+ *
+ */
+
+public abstract class RequestFilter
+ extends FilterBase implements HttpEventFilter {
+
+
+ // ----------------------------------------------------- Instance Variables
+
+ /**
+ * The comma-delimited set of <code>allow</code> expressions.
+ */
+ protected String allow = null;
+
+
+ /**
+ * The set of <code>allow</code> regular expressions we will evaluate.
+ */
+ protected Pattern allows[] = new Pattern[0];
+
+
+ /**
+ * The set of <code>deny</code> regular expressions we will evaluate.
+ */
+ protected Pattern denies[] = new Pattern[0];
+
+
+ /**
+ * The comma-delimited set of <code>deny</code> expressions.
+ */
+ protected String deny = null;
+
+ /**
+ * mime type -- "text/plain"
+ */
+ private static final String PLAIN_TEXT_MIME_TYPE = "text/plain";
+
+
+ // ------------------------------------------------------------- Properties
+
+
+ /**
+ * Return a comma-delimited set of the <code>allow</code> expressions
+ * configured for this Filter, if any; otherwise, return <code>null</code>.
+ */
+ public String getAllow() {
+
+ return (this.allow);
+
+ }
+
+
+ /**
+ * Set the comma-delimited set of the <code>allow</code> expressions
+ * configured for this Filter, if any.
+ *
+ * @param allow The new set of allow expressions
+ */
+ public void setAllow(String allow) {
+
+ this.allow = allow;
+ this.allows = precalculate(allow);
+
+ }
+
+
+ /**
+ * Return a comma-delimited set of the <code>deny</code> expressions
+ * configured for this Filter, if any; otherwise, return <code>null</code>.
+ */
+ public String getDeny() {
+
+ return (this.deny);
+
+ }
+
+
+ /**
+ * Set the comma-delimited set of the <code>deny</code> expressions
+ * configured for this Filter, if any.
+ *
+ * @param deny The new set of deny expressions
+ */
+ public void setDeny(String deny) {
+
+
+ this.deny = deny;
+ this.denies = precalculate(deny);
+
+ }
+
+
+ // --------------------------------------------------------- Public Methods
+
+
+ /**
+ * Extract the desired request property, and pass it (along with the
+ * specified request and response objects) to the protected
+ * <code>process()</code> method to perform the actual filtering.
+ * This method must be implemented by a concrete subclass.
+ *
+ * @param request The servlet request to be processed
+ * @param response The servlet response to be created
+ * @param chain The filter chain
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ public abstract void doFilter(ServletRequest request,
+ ServletResponse response, FilterChain chain) throws IOException,
+ ServletException;
+
+
+ // ------------------------------------------------------ Protected Methods
+
+
+ /**
+ * Return an array of regular expression objects initialized from the
+ * specified argument, which must be <code>null</code> or a comma-delimited
+ * list of regular expression patterns.
+ *
+ * @param list The comma-separated list of patterns
+ *
+ * @exception IllegalArgumentException if one of the patterns has
+ * invalid syntax
+ */
+ protected Pattern[] precalculate(String list) {
+
+ if (list == null)
+ return (new Pattern[0]);
+ list = list.trim();
+ if (list.length() < 1)
+ return (new Pattern[0]);
+ list += ",";
+
+ ArrayList<Pattern> reList = new ArrayList<Pattern>();
+ while (list.length() > 0) {
+ int comma = list.indexOf(',');
+ if (comma < 0)
+ break;
+ String pattern = list.substring(0, comma).trim();
+ try {
+ reList.add(Pattern.compile(pattern));
+ } catch (PatternSyntaxException e) {
+ IllegalArgumentException iae = new IllegalArgumentException
+ (sm.getString("requestFilterFilter.syntax", pattern));
+ iae.initCause(e);
+ throw iae;
+ }
+ list = list.substring(comma + 1);
+ }
+
+ Pattern reArray[] = new Pattern[reList.size()];
+ return reList.toArray(reArray);
+
+ }
+
+
+ /**
+ * Perform the filtering that has been configured for this Filter, matching
+ * against the specified request property.
+ *
+ * @param property The request property on which to filter
+ * @param request The servlet request to be processed
+ * @param response The servlet response to be processed
+ *
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ protected void process(String property, ServletRequest request,
+ ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+
+ if (isAllowed(property)) {
+ chain.doFilter(request, response);
+ } else {
+ if (response instanceof HttpServletResponse) {
+ ((HttpServletResponse) response)
+ .sendError(HttpServletResponse.SC_FORBIDDEN);
+ } else {
+ sendErrorWhenNotHttp(response);
+ }
+ }
+ }
+
+ /**
+ * Perform the filtering that has been configured for this Filter, matching
+ * against the specified request property.
+ *
+ * @param property The property to check against the allow/deny rules
+ * @param event The comet event to be filtered
+ * @param chain The comet filter chain
+ * @exception IOException if an input/output error occurs
+ * @exception ServletException if a servlet error occurs
+ */
+ protected void processCometEvent(String property, HttpEvent event, HttpEventFilterChain chain)
+ throws IOException, ServletException {
+ HttpServletResponse response = event.getHttpServletResponse();
+
+ if (isAllowed(property)) {
+ chain.doFilterEvent(event);
+ } else {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN);
+ event.close();
+ }
+ }
+
+ /**
+ * Process the allow and deny rules for the provided property.
+ *
+ * @param property The property to test against the allow and deny lists
+ * @return <code>true</code> if this request should be allowed,
+ * <code>false</code> otherwise
+ */
+ private boolean isAllowed(String property) {
+ for (int i = 0; i < this.denies.length; i++) {
+ if (this.denies[i].matcher(property).matches()) {
+ return false;
+ }
+ }
+
+ // Check the allow patterns, if any
+ for (int i = 0; i < this.allows.length; i++) {
+ if (this.allows[i].matcher(property).matches()) {
+ return true;
+ }
+ }
+
+ // Allow if denies specified but not allows
+ if ((this.denies.length > 0) && (this.allows.length == 0)) {
+ return true;
+ }
+
+ // Deny this request
+ return false;
+ }
+
+ private void sendErrorWhenNotHttp(ServletResponse response)
+ throws IOException {
+ response.setContentType(PLAIN_TEXT_MIME_TYPE);
+ response.getWriter().write(sm.getString("http.403"));
+ response.getWriter().flush();
+ }
+
+
+}
Modified: trunk/webapps/docs/changelog.xml
===================================================================
--- trunk/webapps/docs/changelog.xml 2010-03-12 17:44:17 UTC (rev 1409)
+++ trunk/webapps/docs/changelog.xml 2010-03-12 18:44:44 UTC (rev 1410)
@@ -40,6 +40,9 @@
<update>
Drop standalone code: XML parsing, webapp deployer, annotation processing, naming support. (remm)
</update>
+ <add>
+ Port over Tomcat utility filters. (markt)
+ </add>
</changelog>
</subsection>
<subsection name="Coyote">
14 years, 9 months
JBossWeb SVN: r1409 - in trunk/java/org/apache/catalina: startup and 1 other directories.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-12 12:44:17 -0500 (Fri, 12 Mar 2010)
New Revision: 1409
Removed:
trunk/java/org/apache/catalina/util/Queue.java
Modified:
trunk/java/org/apache/catalina/core/mbeans-descriptors.xml
trunk/java/org/apache/catalina/startup/ExpandWar.java
trunk/java/org/apache/catalina/startup/mbeans-descriptors.xml
Log:
- Part 3.
- Drop some useless code and descriptors.
Modified: trunk/java/org/apache/catalina/core/mbeans-descriptors.xml
===================================================================
--- trunk/java/org/apache/catalina/core/mbeans-descriptors.xml 2010-03-12 15:42:13 UTC (rev 1408)
+++ trunk/java/org/apache/catalina/core/mbeans-descriptors.xml 2010-03-12 17:44:17 UTC (rev 1409)
@@ -24,19 +24,6 @@
</mbean>
- <mbean name="NamingContextListener"
- description="Helper class used to initialize and populate the JNDI context associated with each context and server"
- domain="Catalina"
- group="Listener"
- type="org.apache.catalina.core.NamingContextListener">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- </mbean>
-
<mbean name="StandardContext"
description="Standard Context Component"
domain="Catalina"
@@ -433,23 +420,10 @@
description="The application root for this Host"
type="java.lang.String"/>
- <attribute name="autoDeploy"
- description="The auto deploy flag for this Host"
- type="boolean"/>
-
<attribute name="configClass"
description="The configuration class for contexts"
type="java.lang.String"/>
- <attribute name="deployOnStartup"
- description="The deploy on startup flag for this Host"
- type="boolean"/>
-
- <attribute name="deployXML"
- description="deploy Context XML config files property"
- is="true"
- type="boolean"/>
-
<attribute name="managedResource"
description="The managed resource this MBean is associated with"
type="java.lang.Object"/>
@@ -463,14 +437,6 @@
is="true"
type="boolean"/>
- <attribute name="xmlNamespaceAware"
- description="Attribute value used to turn on/off XML namespace awareness"
- type="boolean"/>
-
- <attribute name="xmlValidation"
- description="Attribute value used to turn on/off XML validation"
- type="boolean"/>
-
<attribute name="children"
description="Object names of all children"
type="[Ljavax.management.ObjectName;"/>
Modified: trunk/java/org/apache/catalina/startup/ExpandWar.java
===================================================================
--- trunk/java/org/apache/catalina/startup/ExpandWar.java 2010-03-12 15:42:13 UTC (rev 1408)
+++ trunk/java/org/apache/catalina/startup/ExpandWar.java 2010-03-12 17:44:17 UTC (rev 1409)
@@ -22,19 +22,12 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.InputStream;
import java.io.IOException;
-import java.net.JarURLConnection;
-import java.net.URL;
+import java.io.InputStream;
import java.nio.channels.FileChannel;
-import java.util.Enumeration;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import org.apache.catalina.Host;
import org.apache.catalina.util.StringManager;
import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
/**
* Expand out a WAR in a Host's appBase.
@@ -57,225 +50,6 @@
/**
- * Expand the WAR file found at the specified URL into an unpacked
- * directory structure, and return the absolute pathname to the expanded
- * directory.
- *
- * @param host Host war is being installed for
- * @param war URL of the web application archive to be expanded
- * (must start with "jar:")
- *
- * @exception IllegalArgumentException if this is not a "jar:" URL
- * @exception IOException if an input/output error was encountered
- * during expansion
- */
- public static String expand(Host host, URL war)
- throws IOException {
-
- // Calculate the directory name of the expanded directory
- if (host.getLogger().isDebugEnabled()) {
- host.getLogger().debug("expand(" + war.toString() + ")");
- }
- String pathname = war.toString().replace('\\', '/');
- if (pathname.endsWith("!/")) {
- pathname = pathname.substring(0, pathname.length() - 2);
- }
- int period = pathname.lastIndexOf('.');
- if (period >= pathname.length() - 4)
- pathname = pathname.substring(0, period);
- int slash = pathname.lastIndexOf('/');
- if (slash >= 0) {
- pathname = pathname.substring(slash + 1);
- }
- if (host.getLogger().isDebugEnabled()) {
- host.getLogger().debug(" Proposed directory name: " + pathname);
- }
- return expand(host, war, pathname);
-
- }
-
-
- /**
- * Expand the WAR file found at the specified URL into an unpacked
- * directory structure, and return the absolute pathname to the expanded
- * directory.
- *
- * @param host Host war is being installed for
- * @param war URL of the web application archive to be expanded
- * (must start with "jar:")
- * @param pathname Context path name for web application
- *
- * @exception IllegalArgumentException if this is not a "jar:" URL or if the
- * WAR file is invalid
- * @exception IOException if an input/output error was encountered
- * during expansion
- */
- public static String expand(Host host, URL war, String pathname)
- throws IOException {
-
- // Make sure that there is no such directory already existing
- File appBase = new File(host.getAppBase());
- if (!appBase.isAbsolute()) {
- appBase = new File(System.getProperty("catalina.base"),
- host.getAppBase());
- }
- if (!appBase.exists() || !appBase.isDirectory()) {
- throw new IOException
- (sm.getString("hostConfig.appBase",
- appBase.getAbsolutePath()));
- }
-
- File docBase = new File(appBase, pathname);
- if (docBase.exists()) {
- // War file is already installed
- return (docBase.getAbsolutePath());
- }
-
- // Create the new document base directory
- docBase.mkdir();
-
- // Expand the WAR into the new document base directory
- String canonicalDocBasePrefix = docBase.getCanonicalPath();
- if (!canonicalDocBasePrefix.endsWith(File.separator)) {
- canonicalDocBasePrefix += File.separator;
- }
- JarURLConnection juc = (JarURLConnection) war.openConnection();
- juc.setUseCaches(false);
- JarFile jarFile = null;
- InputStream input = null;
- boolean success = false;
- try {
- jarFile = juc.getJarFile();
- Enumeration jarEntries = jarFile.entries();
- while (jarEntries.hasMoreElements()) {
- JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
- String name = jarEntry.getName();
- File expandedFile = new File(docBase, name);
- if (!expandedFile.getCanonicalPath().startsWith(
- canonicalDocBasePrefix)) {
- // Trying to expand outside the docBase
- // Throw an exception to stop the deployment
- throw new IllegalArgumentException(
- sm.getString("expandWar.illegalPath",war, name));
- }
- int last = name.lastIndexOf('/');
- if (last >= 0) {
- File parent = new File(docBase,
- name.substring(0, last));
- parent.mkdirs();
- }
- if (name.endsWith("/")) {
- continue;
- }
- input = jarFile.getInputStream(jarEntry);
-
- // Bugzilla 33636
- expand(input, expandedFile);
- long lastModified = jarEntry.getTime();
- if ((lastModified != -1) && (lastModified != 0)) {
- expandedFile.setLastModified(lastModified);
- }
-
- input.close();
- input = null;
- }
- success = true;
- } catch (IOException e) {
- throw e;
- } finally {
- if (!success) {
- // If something went wrong, delete expanded dir to keep things
- // clean
- deleteDir(docBase);
- }
- if (input != null) {
- try {
- input.close();
- } catch (Throwable t) {
- ;
- }
- input = null;
- }
- if (jarFile != null) {
- try {
- jarFile.close();
- } catch (Throwable t) {
- ;
- }
- jarFile = null;
- }
- }
-
- // Return the absolute path to our new document base directory
- return (docBase.getAbsolutePath());
-
- }
-
-
- /**
- * Validate the WAR file found at the specified URL.
- *
- * @param host Host war is being installed for
- * @param war URL of the web application archive to be validated
- * (must start with "jar:")
- * @param pathname Context path name for web application
- *
- * @exception IllegalArgumentException if this is not a "jar:" URL or if the
- * WAR file is invalid
- * @exception IOException if an input/output error was encountered
- * during validation
- */
- public static void validate(Host host, URL war, String pathname)
- throws IOException {
-
- // Make the appBase absolute
- File appBase = new File(host.getAppBase());
- if (!appBase.isAbsolute()) {
- appBase = new File(System.getProperty("catalina.base"),
- host.getAppBase());
- }
-
- File docBase = new File(appBase, pathname);
-
- // Calculate the document base directory
- String canonicalDocBasePrefix = docBase.getCanonicalPath();
- if (!canonicalDocBasePrefix.endsWith(File.separator)) {
- canonicalDocBasePrefix += File.separator;
- }
- JarURLConnection juc = (JarURLConnection) war.openConnection();
- juc.setUseCaches(false);
- JarFile jarFile = null;
- try {
- jarFile = juc.getJarFile();
- Enumeration<JarEntry> jarEntries = jarFile.entries();
- while (jarEntries.hasMoreElements()) {
- JarEntry jarEntry = jarEntries.nextElement();
- String name = jarEntry.getName();
- File expandedFile = new File(docBase, name);
- if (!expandedFile.getCanonicalPath().startsWith(
- canonicalDocBasePrefix)) {
- // Entry located outside the docBase
- // Throw an exception to stop the deployment
- throw new IllegalArgumentException(
- sm.getString("expandWar.illegalPath",war, name));
- }
- }
- } catch (IOException e) {
- throw e;
- } finally {
- if (jarFile != null) {
- try {
- jarFile.close();
- } catch (Throwable t) {
- // Ignore
- }
- jarFile = null;
- }
- }
- }
-
-
- /**
* Copy the specified file or directory to the destination.
*
* @param src File object representing the source
@@ -421,58 +195,4 @@
}
- /**
- * Expand the specified input stream into the specified directory, creating
- * a file named from the specified relative path.
- *
- * @param input InputStream to be copied
- * @param docBase Document base directory into which we are expanding
- * @param name Relative pathname of the file to be created
- * @return A handle to the expanded File
- *
- * @exception IOException if an input/output error occurs
- *
- * @deprecated
- */
- protected static File expand(InputStream input, File docBase, String name)
- throws IOException {
- File file = new File(docBase, name);
- expand(input, file);
- return file;
- }
-
-
- /**
- * Expand the specified input stream into the specified file.
- *
- * @param input InputStream to be copied
- * @param file The file to be created
- *
- * @exception IOException if an input/output error occurs
- */
- private static void expand(InputStream input, File file)
- throws IOException {
- BufferedOutputStream output = null;
- try {
- output =
- new BufferedOutputStream(new FileOutputStream(file));
- byte buffer[] = new byte[2048];
- while (true) {
- int n = input.read(buffer);
- if (n <= 0)
- break;
- output.write(buffer, 0, n);
- }
- } finally {
- if (output != null) {
- try {
- output.close();
- } catch (IOException e) {
- // Ignore
- }
- }
- }
- }
-
-
}
Modified: trunk/java/org/apache/catalina/startup/mbeans-descriptors.xml
===================================================================
--- trunk/java/org/apache/catalina/startup/mbeans-descriptors.xml 2010-03-12 15:42:13 UTC (rev 1408)
+++ trunk/java/org/apache/catalina/startup/mbeans-descriptors.xml 2010-03-12 17:44:17 UTC (rev 1409)
@@ -52,69 +52,6 @@
description="The Java class name of the Context implementation we should use"
type="java.lang.String"/>
- <operation name="check"
- description="Check a web application name for updates"
- impact="ACTION"
- returnType="void">
- <parameter name="name"
- description="Application name"
- type="java.lang.String"/>
- </operation>
-
- <operation name="addServiced"
- description="Add a web application name to the serviced list"
- impact="ACTION"
- returnType="void">
- <parameter name="name"
- description="Application name"
- type="java.lang.String"/>
- </operation>
-
- <operation name="isServiced"
- description="Add a web application name to the serviced list"
- impact="ACTION"
- returnType="boolean">
- <parameter name="name"
- description="Application name"
- type="java.lang.String"/>
- </operation>
-
- <operation name="isDeployed"
- description="Was this web application deployed by this component"
- impact="ACTION"
- returnType="boolean">
- <parameter name="name"
- description="Application name"
- type="java.lang.String"/>
- </operation>
-
- <operation name="manageApp"
- description="Add a web application managed externally"
- impact="ACTION"
- returnType="void">
- <parameter name="context"
- description="Context to add"
- type="org.apache.catalina.Context" />
- </operation>
-
- <operation name="removeServiced"
- description="Add a web application name to the serviced list"
- impact="ACTION"
- returnType="void">
- <parameter name="name"
- description="Application name"
- type="java.lang.String"/>
- </operation>
-
- <operation name="unmanageApp"
- description="Remove a web application from checks"
- impact="ACTION"
- returnType="void">
- <parameter name="contextPath"
- description="The application path"
- type="java.lang.String" />
- </operation>
-
</mbean>
</mbeans-descriptors>
Deleted: trunk/java/org/apache/catalina/util/Queue.java
===================================================================
--- trunk/java/org/apache/catalina/util/Queue.java 2010-03-12 15:42:13 UTC (rev 1408)
+++ trunk/java/org/apache/catalina/util/Queue.java 2010-03-12 17:44:17 UTC (rev 1409)
@@ -1,88 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util.Vector;
-
-/**
- * A simple FIFO queue class which causes the calling thread to wait
- * if the queue is empty and notifies threads that are waiting when it
- * is not empty.
- *
- * @author Anil V (akv(a)eng.sun.com)
- */
-public class Queue {
- private Vector vector = new Vector();
-
- /**
- * Put the object into the queue.
- *
- * @param object the object to be appended to the
- * queue.
- */
- public synchronized void put(Object object) {
- vector.addElement(object);
- notify();
- }
-
- /**
- * Pull the first object out of the queue. Wait if the queue is
- * empty.
- */
- public synchronized Object pull() {
- while (isEmpty())
- try {
- wait();
- } catch (InterruptedException ex) {
- }
- return get();
- }
-
- /**
- * Get the first object out of the queue. Return null if the queue
- * is empty.
- */
- public synchronized Object get() {
- Object object = peek();
- if (object != null)
- vector.removeElementAt(0);
- return object;
- }
-
- /**
- * Peek to see if something is available.
- */
- public Object peek() {
- if (isEmpty())
- return null;
- return vector.elementAt(0);
- }
-
- /**
- * Is the queue empty?
- */
- public boolean isEmpty() {
- return vector.isEmpty();
- }
-
- /**
- * How many elements are there in this queue?
- */
- public int size() {
- return vector.size();
- }
-}
14 years, 9 months
JBossWeb SVN: r1408 - in trunk/java/org: apache/catalina/realm and 11 other directories.
by jbossweb-commits@lists.jboss.org
Author: remy.maucherat(a)jboss.com
Date: 2010-03-12 10:42:13 -0500 (Fri, 12 Mar 2010)
New Revision: 1408
Removed:
trunk/java/org/apache/catalina/realm/CombinedRealm.java
trunk/java/org/apache/catalina/realm/DataSourceRealm.java
trunk/java/org/apache/catalina/realm/JAASCallbackHandler.java
trunk/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
trunk/java/org/apache/catalina/realm/JAASRealm.java
trunk/java/org/apache/catalina/realm/JDBCRealm.java
trunk/java/org/apache/catalina/realm/JNDIRealm.java
trunk/java/org/apache/catalina/realm/LockOutRealm.java
trunk/java/org/apache/catalina/realm/MemoryRealm.java
trunk/java/org/apache/catalina/realm/MemoryRuleSet.java
trunk/java/org/apache/catalina/realm/mbeans-descriptors.xml
trunk/java/org/apache/catalina/util/SchemaResolver.java
trunk/java/org/apache/juli/ClassLoaderLogManager.java
trunk/java/org/apache/juli/FileHandler.java
trunk/java/org/apache/juli/JdkLoggerFormatter.java
trunk/java/org/apache/juli/OneLineFormatter.java
trunk/java/org/apache/naming/ContextAccessController.java
trunk/java/org/apache/naming/ContextBindings.java
trunk/java/org/apache/naming/EjbRef.java
trunk/java/org/apache/naming/HandlerRef.java
trunk/java/org/apache/naming/NamingContext.java
trunk/java/org/apache/naming/NamingService.java
trunk/java/org/apache/naming/NamingServiceMBean.java
trunk/java/org/apache/naming/ResourceEnvRef.java
trunk/java/org/apache/naming/ResourceLinkRef.java
trunk/java/org/apache/naming/ResourceRef.java
trunk/java/org/apache/naming/SelectorContext.java
trunk/java/org/apache/naming/ServiceRef.java
trunk/java/org/apache/naming/TransactionRef.java
trunk/java/org/apache/naming/factory/BeanFactory.java
trunk/java/org/apache/naming/factory/Constants.java
trunk/java/org/apache/naming/factory/EjbFactory.java
trunk/java/org/apache/naming/factory/OpenEjbFactory.java
trunk/java/org/apache/naming/factory/ResourceEnvFactory.java
trunk/java/org/apache/naming/factory/ResourceFactory.java
trunk/java/org/apache/naming/factory/ResourceLinkFactory.java
trunk/java/org/apache/naming/factory/TransactionFactory.java
trunk/java/org/apache/naming/factory/package.html
trunk/java/org/apache/naming/java/javaURLContextFactory.java
trunk/java/org/apache/naming/java/package.html
trunk/java/org/apache/tomcat/util/digester/AbstractObjectCreationFactory.java
trunk/java/org/apache/tomcat/util/digester/AbstractRulesImpl.java
trunk/java/org/apache/tomcat/util/digester/ArrayStack.java
trunk/java/org/apache/tomcat/util/digester/CallMethodRule.java
trunk/java/org/apache/tomcat/util/digester/CallParamRule.java
trunk/java/org/apache/tomcat/util/digester/Digester.java
trunk/java/org/apache/tomcat/util/digester/FactoryCreateRule.java
trunk/java/org/apache/tomcat/util/digester/GenericParser.java
trunk/java/org/apache/tomcat/util/digester/NodeCreateRule.java
trunk/java/org/apache/tomcat/util/digester/ObjectCreateRule.java
trunk/java/org/apache/tomcat/util/digester/ObjectCreationFactory.java
trunk/java/org/apache/tomcat/util/digester/ObjectParamRule.java
trunk/java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
trunk/java/org/apache/tomcat/util/digester/PathCallParamRule.java
trunk/java/org/apache/tomcat/util/digester/Rule.java
trunk/java/org/apache/tomcat/util/digester/RuleSet.java
trunk/java/org/apache/tomcat/util/digester/RuleSetBase.java
trunk/java/org/apache/tomcat/util/digester/Rules.java
trunk/java/org/apache/tomcat/util/digester/RulesBase.java
trunk/java/org/apache/tomcat/util/digester/SetNextRule.java
trunk/java/org/apache/tomcat/util/digester/SetPropertiesRule.java
trunk/java/org/apache/tomcat/util/digester/SetPropertyRule.java
trunk/java/org/apache/tomcat/util/digester/SetRootRule.java
trunk/java/org/apache/tomcat/util/digester/SetTopRule.java
trunk/java/org/apache/tomcat/util/digester/WithDefaultsRulesWrapper.java
trunk/java/org/apache/tomcat/util/digester/XercesParser.java
trunk/java/org/apache/tomcat/util/digester/package.html
trunk/java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
trunk/java/org/jboss/web/cluster/ClusterListener.java
trunk/java/org/jboss/web/cluster/Constants.java
trunk/java/org/jboss/web/cluster/JSSEKeyManager.java
trunk/java/org/jboss/web/cluster/JSSESocketFactory.java
trunk/java/org/jboss/web/cluster/LocalStrings.properties
trunk/java/org/jboss/web/cluster/advertise/AdvertiseEventType.java
trunk/java/org/jboss/web/cluster/advertise/AdvertiseListener.java
trunk/java/org/jboss/web/cluster/advertise/AdvertisedServer.java
trunk/java/org/jboss/web/cluster/mbeans-descriptors.xml
Modified:
trunk/java/org/apache/catalina/core/StandardEngine.java
trunk/java/org/apache/catalina/startup/Catalina.java
trunk/java/org/apache/tomcat/util/modeler/Registry.java
Log:
- Part 2.
- Drop custom realms.
- Drop digester.
- Drop JULI.
- Drop EE naming impl.
- Drop mod_cluster prototype.
Modified: trunk/java/org/apache/catalina/core/StandardEngine.java
===================================================================
--- trunk/java/org/apache/catalina/core/StandardEngine.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/core/StandardEngine.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -30,10 +30,7 @@
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
-import org.apache.catalina.Realm;
import org.apache.catalina.Service;
-import org.apache.catalina.realm.JAASRealm;
-import org.apache.catalina.util.ServerInfo;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.modeler.modules.MbeansSource;
import org.jboss.logging.Logger;
@@ -126,22 +123,6 @@
// ------------------------------------------------------------- Properties
- /** Provide a default in case no explicit configuration is set
- *
- * @return configured realm, or a JAAS realm by default
- */
- public Realm getRealm() {
- Realm configured=super.getRealm();
- // If no set realm has been called - default to JAAS
- // This can be overriden at engine, context and host level
- if( configured==null ) {
- configured=new JAASRealm();
- this.setRealm( configured );
- }
- return configured;
- }
-
-
/**
* Return the default host.
*/
Deleted: trunk/java/org/apache/catalina/realm/CombinedRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/CombinedRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/CombinedRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,321 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-import java.security.Principal;
-
-import java.security.cert.X509Certificate;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.management.ObjectName;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.Lifecycle;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.Realm;
-import org.apache.catalina.util.StringManager;
-import org.jboss.logging.Logger;
-
-/**
- * Realm implementation that contains one or more realms. Authentication is
- * attempted for each realm in the order they were configured. If any realm
- * authenticates the user then the authentication succeeds. When combining
- * realms usernames should be unique across all combined realms.
- */
-public class CombinedRealm extends RealmBase {
-
- private static Logger log = Logger.getLogger(CombinedRealm.class);
-
- /**
- * The string manager for this package.
- */
- protected static StringManager sm =
- StringManager.getManager(Constants.Package);
-
- /**
- * The list of Realms contained by this Realm.
- */
- protected List<Realm> realms = new LinkedList<Realm>();
-
-
- /**
- * Add a realm to the list of realms that will be used to authenticate
- * users.
- */
- public void addRealm(Realm theRealm) {
- realms.add(theRealm);
-
- if (log.isDebugEnabled()) {
- sm.getString("combinedRealm.addRealm", theRealm.getInfo(),
- Integer.toString(realms.size()));
- }
- }
-
-
- /**
- * Return the set of Realms that this Realm is wrapping
- */
- public ObjectName[] getRealms() {
- ObjectName[] result = new ObjectName[realms.size()];
- for (Realm realm : realms) {
- if (realm instanceof RealmBase) {
- result[realms.indexOf(realm)] =
- ((RealmBase) realm).getObjectName();
- }
- }
- return result;
- }
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, byte[] credentials) {
- Principal authenticatedUser = null;
-
- for (Realm realm : realms) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
- }
-
- authenticatedUser = realm.authenticate(username, credentials);
-
- if (authenticatedUser == null) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSucess", username, realm.getInfo()));
- }
- break;
- }
- }
- return authenticatedUser;
- }
-
-
- /**
- * Return the Principal associated with the specified username, which
- * matches the digest calculated using the given parameters using the
- * method described in RFC 2069; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param clientDigest Digest which has been submitted by the client
- * @param nOnce Unique (or supposedly unique) token which has been used
- * for this request
- * @param realm Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest :
- * MD5(Method + ":" + uri)
- */
- public Principal authenticate(String username, String clientDigest,
- String once, String nc, String cnonce, String qop,
- String realmName, String md5a2) {
- Principal authenticatedUser = null;
-
- for (Realm realm : realms) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
- }
-
- authenticatedUser = realm.authenticate(username, clientDigest, once,
- nc, cnonce, qop, realmName, md5a2);
-
- if (authenticatedUser == null) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSucess", username, realm.getInfo()));
- }
- break;
- }
- }
- return authenticatedUser;
- }
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, String credentials) {
- Principal authenticatedUser = null;
-
- for (Realm realm : realms) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
- }
-
- authenticatedUser = realm.authenticate(username, credentials);
-
- if (authenticatedUser == null) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSucess", username, realm.getInfo()));
- }
- break;
- }
- }
- return authenticatedUser;
- }
-
-
- /**
- * Set the Container with which this Realm has been associated.
- *
- * @param container The associated Container
- */
- public void setContainer(Container container) {
- for(Realm realm : realms) {
- // Set the realmPath for JMX naming
- if (realm instanceof RealmBase) {
- ((RealmBase) realm).setRealmPath(
- getRealmPath() + "/realm" + realms.indexOf(realm));
- }
-
- // Set the container for sub-realms. Mainly so logging works.
- realm.setContainer(container);
- }
- super.setContainer(container);
- }
-
-
- /**
- * Prepare for the beginning of active use of the public methods of this
- * component. This method should be called before any of the public
- * methods of this component are utilized. It should also send a
- * LifecycleEvent of type START_EVENT to any registered listeners.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
- */
- public void start() throws LifecycleException {
- // Start 'sub-realms' then this one
- for (Realm realm : realms) {
- if (realm instanceof Lifecycle) {
- ((Lifecycle) realm).start();
- }
- }
- super.start();
- }
-
-
- /**
- * Gracefully terminate the active use of the public methods of this
- * component. This method should be the last one called on a given
- * instance of this component. It should also send a LifecycleEvent
- * of type STOP_EVENT to any registered listeners.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
- */
- public void stop() throws LifecycleException {
- // Stop this realm, then the sub-realms (reverse order to start)
- super.stop();
- for (Realm realm : realms) {
- if (realm instanceof Lifecycle) {
- ((Lifecycle) realm).stop();
- }
- }
- }
-
-
- /**
- * Return the Principal associated with the specified chain of X509
- * client certificates. If there is none, return <code>null</code>.
- *
- * @param certs Array of client certificates, with the first one in
- * the array being the certificate of the client itself.
- */
- public Principal authenticate(X509Certificate[] certs) {
- Principal authenticatedUser = null;
- String username = null;
- if (certs != null && certs.length >0) {
- username = certs[0].getSubjectDN().getName();
- }
-
- for (Realm realm : realms) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
- }
-
- authenticatedUser = realm.authenticate(certs);
-
- if (authenticatedUser == null) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSucess", username, realm.getInfo()));
- }
- break;
- }
- }
- return authenticatedUser;
- }
-
- @Override
- protected String getName() {
- // This method should never be called
- // Stack trace will show where this was called from
- UnsupportedOperationException uoe =
- new UnsupportedOperationException(
- sm.getString("combinedRealm.getName"));
- log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
- throw uoe;
- }
-
- @Override
- protected String getPassword(String username) {
- // This method should never be called
- // Stack trace will show where this was called from
- UnsupportedOperationException uoe =
- new UnsupportedOperationException(
- sm.getString("combinedRealm.getPassword"));
- log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
- throw uoe;
- }
-
- @Override
- protected Principal getPrincipal(String username) {
- // This method should never be called
- // Stack trace will show where this was called from
- UnsupportedOperationException uoe =
- new UnsupportedOperationException(
- sm.getString("combinedRealm.getPrincipal"));
- log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
- throw uoe;
- }
-
-}
Deleted: trunk/java/org/apache/catalina/realm/DataSourceRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/DataSourceRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/DataSourceRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,662 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import java.security.Principal;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-
-import javax.naming.Context;
-import javax.sql.DataSource;
-
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.core.StandardServer;
-import org.apache.catalina.util.StringManager;
-import org.apache.naming.ContextBindings;
-
-/**
-*
-* Implmentation of <b>Realm</b> that works with any JDBC JNDI DataSource.
-* See the JDBCRealm.howto for more details on how to set up the database and
-* for configuration options.
-*
-* @author Glenn L. Nielsen
-* @author Craig R. McClanahan
-* @author Carson McDonald
-* @author Ignacio Ortega
-* @version $Revision$
-*/
-
-public class DataSourceRealm
- extends RealmBase {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The generated string for the roles PreparedStatement
- */
- private String preparedRoles = null;
-
-
- /**
- * The generated string for the credentials PreparedStatement
- */
- private String preparedCredentials = null;
-
-
- /**
- * The name of the JNDI JDBC DataSource
- */
- protected String dataSourceName = null;
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected static final String info =
- "org.apache.catalina.realm.DataSourceRealm/1.0";
-
-
- /**
- * Context local datasource.
- */
- protected boolean localDataSource = true;
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected static final String name = "DataSourceRealm";
-
-
- /**
- * The column in the user role table that names a role
- */
- protected String roleNameCol = null;
-
-
- /**
- * The string manager for this package.
- */
- protected static final StringManager sm =
- StringManager.getManager(Constants.Package);
-
-
- /**
- * The column in the user table that holds the user's credintials
- */
- protected String userCredCol = null;
-
-
- /**
- * The column in the user table that holds the user's name
- */
- protected String userNameCol = null;
-
-
- /**
- * The table that holds the relation between user's and roles
- */
- protected String userRoleTable = null;
-
-
- /**
- * The table that holds user data.
- */
- protected String userTable = null;
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return the name of the JNDI JDBC DataSource.
- *
- */
- public String getDataSourceName() {
- return dataSourceName;
- }
-
- /**
- * Set the name of the JNDI JDBC DataSource.
- *
- * @param dataSourceName the name of the JNDI JDBC DataSource
- */
- public void setDataSourceName( String dataSourceName) {
- this.dataSourceName = dataSourceName;
- }
-
- /**
- * Return if the datasource will be looked up in the webapp JNDI Context.
- */
- public boolean getLocalDataSource() {
- return localDataSource;
- }
-
- /**
- * Set to true to cause the datasource to be looked up in the webapp JNDI
- * Context.
- *
- * @param localDataSource the new flag value
- */
- public void setLocalDataSource(boolean localDataSource) {
- this.localDataSource = localDataSource;
- }
-
- /**
- * Return the column in the user role table that names a role.
- *
- */
- public String getRoleNameCol() {
- return roleNameCol;
- }
-
- /**
- * Set the column in the user role table that names a role.
- *
- * @param roleNameCol The column name
- */
- public void setRoleNameCol( String roleNameCol ) {
- this.roleNameCol = roleNameCol;
- }
-
- /**
- * Return the column in the user table that holds the user's credentials.
- *
- */
- public String getUserCredCol() {
- return userCredCol;
- }
-
- /**
- * Set the column in the user table that holds the user's credentials.
- *
- * @param userCredCol The column name
- */
- public void setUserCredCol( String userCredCol ) {
- this.userCredCol = userCredCol;
- }
-
- /**
- * Return the column in the user table that holds the user's name.
- *
- */
- public String getUserNameCol() {
- return userNameCol;
- }
-
- /**
- * Set the column in the user table that holds the user's name.
- *
- * @param userNameCol The column name
- */
- public void setUserNameCol( String userNameCol ) {
- this.userNameCol = userNameCol;
- }
-
- /**
- * Return the table that holds the relation between user's and roles.
- *
- */
- public String getUserRoleTable() {
- return userRoleTable;
- }
-
- /**
- * Set the table that holds the relation between user's and roles.
- *
- * @param userRoleTable The table name
- */
- public void setUserRoleTable( String userRoleTable ) {
- this.userRoleTable = userRoleTable;
- }
-
- /**
- * Return the table that holds user data..
- *
- */
- public String getUserTable() {
- return userTable;
- }
-
- /**
- * Set the table that holds user data.
- *
- * @param userTable The table name
- */
- public void setUserTable( String userTable ) {
- this.userTable = userTable;
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * If there are any errors with the JDBC connection, executing
- * the query or anything we return null (don't authenticate). This
- * event is also logged, and the connection will be closed so that
- * a subsequent request will automatically re-open it.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, String credentials) {
-
- // No user or no credentials
- // Can't possibly authenticate, don't bother the database then
- if (username == null || credentials == null) {
- return null;
- }
-
- Connection dbConnection = null;
-
- try {
-
- // Ensure that we have an open database connection
- dbConnection = open();
- if (dbConnection == null) {
- // If the db connection open fails, return "not authenticated"
- return null;
- }
-
- // Acquire a Principal object for this user
- return authenticate(dbConnection, username, credentials);
-
- } catch (SQLException e) {
- // Log the problem for posterity
- containerLog.error(sm.getString("dataSourceRealm.exception"), e);
-
- // Return "not authenticated" for this request
- return (null);
-
- } finally {
- close(dbConnection);
- }
-
- }
-
-
- // -------------------------------------------------------- Package Methods
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param dbConnection The database connection to be used
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- protected Principal authenticate(Connection dbConnection,
- String username,
- String credentials) throws SQLException{
-
- String dbCredentials = getPassword(dbConnection, username);
-
- // Validate the user's credentials
- boolean validated = false;
- if (hasMessageDigest()) {
- // Hex hashes should be compared case-insensitive
- validated = (digest(credentials).equalsIgnoreCase(dbCredentials));
- } else
- validated = (digest(credentials).equals(dbCredentials));
-
- if (validated) {
- if (containerLog.isTraceEnabled())
- containerLog.trace(
- sm.getString("dataSourceRealm.authenticateSuccess",
- username));
- } else {
- if (containerLog.isTraceEnabled())
- containerLog.trace(
- sm.getString("dataSourceRealm.authenticateFailure",
- username));
- return (null);
- }
-
- ArrayList list = getRoles(dbConnection, username);
-
- // Create and return a suitable Principal for this user
- return (new GenericPrincipal(this, username, credentials, list));
-
- }
-
-
- /**
- * Close the specified database connection.
- *
- * @param dbConnection The connection to be closed
- */
- protected void close(Connection dbConnection) {
-
- // Do nothing if the database connection is already closed
- if (dbConnection == null)
- return;
-
- // Commit if not auto committed
- try {
- if (!dbConnection.getAutoCommit()) {
- dbConnection.commit();
- }
- } catch (SQLException e) {
- containerLog.error("Exception committing connection before closing:", e);
- }
-
- // Close this database connection, and log any errors
- try {
- dbConnection.close();
- } catch (SQLException e) {
- containerLog.error(sm.getString("dataSourceRealm.close"), e); // Just log it here
- }
-
- }
-
- /**
- * Open the specified database connection.
- *
- * @return Connection to the database
- */
- protected Connection open() {
-
- try {
- Context context = null;
- if (localDataSource) {
- context = ContextBindings.getClassLoader();
- context = (Context) context.lookup("comp/env");
- } else {
- // FIXME: no non local DS
- context = null;//((StandardServer) getServer()).getGlobalNamingContext();
- }
- DataSource dataSource = (DataSource)context.lookup(dataSourceName);
- return dataSource.getConnection();
- } catch (Exception e) {
- // Log the problem for posterity
- containerLog.error(sm.getString("dataSourceRealm.exception"), e);
- }
- return null;
- }
-
- /**
- * Return a short name for this Realm implementation.
- */
- protected String getName() {
-
- return (name);
-
- }
-
- /**
- * Return the password associated with the given principal's user name.
- */
- protected String getPassword(String username) {
-
- Connection dbConnection = null;
-
- // Ensure that we have an open database connection
- dbConnection = open();
- if (dbConnection == null) {
- return null;
- }
-
- try {
- return getPassword(dbConnection, username);
- } finally {
- close(dbConnection);
- }
- }
-
- /**
- * Return the password associated with the given principal's user name.
- * @param dbConnection The database connection to be used
- * @param username Username for which password should be retrieved
- */
- protected String getPassword(Connection dbConnection,
- String username) {
-
- ResultSet rs = null;
- PreparedStatement stmt = null;
- String dbCredentials = null;
-
- try {
- stmt = credentials(dbConnection, username);
- rs = stmt.executeQuery();
- if (rs.next()) {
- dbCredentials = rs.getString(1);
- }
-
- return (dbCredentials != null) ? dbCredentials.trim() : null;
-
- } catch(SQLException e) {
- containerLog.error(
- sm.getString("dataSourceRealm.getPassword.exception",
- username));
- } finally {
- try {
- if (rs != null) {
- rs.close();
- }
- if (stmt != null) {
- stmt.close();
- }
- } catch (SQLException e) {
- containerLog.error(
- sm.getString("dataSourceRealm.getPassword.exception",
- username));
-
- }
- }
-
- return null;
- }
-
-
- /**
- * Return the Principal associated with the given user name.
- */
- protected Principal getPrincipal(String username) {
- Connection dbConnection = open();
- if (dbConnection == null) {
- return new GenericPrincipal(this,username, null, null);
- }
- try {
- return (new GenericPrincipal(this,
- username,
- getPassword(dbConnection, username),
- getRoles(dbConnection, username)));
- } finally {
- close(dbConnection);
- }
-
- }
-
- /**
- * Return the roles associated with the given user name.
- * @param username Username for which roles should be retrieved
- */
- protected ArrayList getRoles(String username) {
-
- Connection dbConnection = null;
-
- // Ensure that we have an open database connection
- dbConnection = open();
- if (dbConnection == null) {
- return null;
- }
-
- try {
- return getRoles(dbConnection, username);
- } finally {
- close(dbConnection);
- }
- }
-
- /**
- * Return the roles associated with the given user name
- * @param dbConnection The database connection to be used
- * @param username Username for which roles should be retrieved
- */
- protected ArrayList getRoles(Connection dbConnection,
- String username) {
-
- ResultSet rs = null;
- PreparedStatement stmt = null;
- ArrayList list = null;
-
- try {
- stmt = roles(dbConnection, username);
- rs = stmt.executeQuery();
- list = new ArrayList();
-
- while (rs.next()) {
- String role = rs.getString(1);
- if (role != null) {
- list.add(role.trim());
- }
- }
- return list;
- } catch(SQLException e) {
- containerLog.error(
- sm.getString("dataSourceRealm.getRoles.exception", username));
- }
- finally {
- try {
- if (rs != null) {
- rs.close();
- }
- if (stmt != null) {
- stmt.close();
- }
- } catch (SQLException e) {
- containerLog.error(
- sm.getString("dataSourceRealm.getRoles.exception",
- username));
- }
- }
-
- return null;
- }
-
- /**
- * Return a PreparedStatement configured to perform the SELECT required
- * to retrieve user credentials for the specified username.
- *
- * @param dbConnection The database connection to be used
- * @param username Username for which credentials should be retrieved
- *
- * @exception SQLException if a database error occurs
- */
- private PreparedStatement credentials(Connection dbConnection,
- String username)
- throws SQLException {
-
- PreparedStatement credentials =
- dbConnection.prepareStatement(preparedCredentials);
-
- credentials.setString(1, username);
- return (credentials);
-
- }
-
- /**
- * Return a PreparedStatement configured to perform the SELECT required
- * to retrieve user roles for the specified username.
- *
- * @param dbConnection The database connection to be used
- * @param username Username for which roles should be retrieved
- *
- * @exception SQLException if a database error occurs
- */
- private PreparedStatement roles(Connection dbConnection, String username)
- throws SQLException {
-
- PreparedStatement roles =
- dbConnection.prepareStatement(preparedRoles);
-
- roles.setString(1, username);
- return (roles);
-
- }
-
- // ------------------------------------------------------ Lifecycle Methods
-
-
- /**
- *
- * Prepare for active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents it from being started
- */
- public void start() throws LifecycleException {
-
- // Perform normal superclass initialization
- super.start();
-
- // Create the roles PreparedStatement string
- StringBuilder temp = new StringBuilder("SELECT ");
- temp.append(roleNameCol);
- temp.append(" FROM ");
- temp.append(userRoleTable);
- temp.append(" WHERE ");
- temp.append(userNameCol);
- temp.append(" = ?");
- preparedRoles = temp.toString();
-
- // Create the credentials PreparedStatement string
- temp = new StringBuilder("SELECT ");
- temp.append(userCredCol);
- temp.append(" FROM ");
- temp.append(userTable);
- temp.append(" WHERE ");
- temp.append(userNameCol);
- temp.append(" = ?");
- preparedCredentials = temp.toString();
- }
-
-
- /**
- * Gracefully shut down active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
- */
- public void stop() throws LifecycleException {
-
- // Perform normal superclass finalization
- super.stop();
-
- }
-
-
-}
Deleted: trunk/java/org/apache/catalina/realm/JAASCallbackHandler.java
===================================================================
--- trunk/java/org/apache/catalina/realm/JAASCallbackHandler.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/JAASCallbackHandler.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,226 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import java.io.IOException;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.TextInputCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.catalina.util.StringManager;
-
-/**
- * <p>Implementation of the JAAS <code>CallbackHandler</code> interface,
- * used to negotiate delivery of the username and credentials that were
- * specified to our constructor. No interaction with the user is required
- * (or possible).</p>
- *
- * <p>This <code>CallbackHandler</code> will pre-digest the supplied
- * password, if required by the <code><Realm></code> element in
- * <code>server.xml</code>.</p>
- * <p>At present, <code>JAASCallbackHandler</code> knows how to handle callbacks of
- * type <code>javax.security.auth.callback.NameCallback</code> and
- * <code>javax.security.auth.callback.PasswordCallback</code>.</p>
- *
- * @author Craig R. McClanahan
- * @author Andrew R. Jaquith
- * @version $Revision$ $Date$
- */
-
-public class JAASCallbackHandler implements CallbackHandler {
-
- // ------------------------------------------------------------ Constructor
-
-
- /**
- * Construct a callback handler configured with the specified values.
- * Note that if the <code>JAASRealm</code> instance specifies digested passwords,
- * the <code>password</code> parameter will be pre-digested here.
- *
- * @param realm Our associated JAASRealm instance
- * @param username Username to be authenticated with
- * @param password Password to be authenticated with
- */
- public JAASCallbackHandler(JAASRealm realm, String username,
- String password) {
-
- super();
- this.realm = realm;
- this.username = username;
-
- if (realm.hasMessageDigest()) {
- this.password = realm.digest(password);
- }
- else {
- this.password = password;
- }
- }
-
-
- /**
- * Construct a callback handler for DIGEST authentication.
- *
- * @param realm Our associated JAASRealm instance
- * @param username Username to be authenticated with
- * @param password Password to be authenticated with
- * @param nonce Server generated nonce
- * @param nc Nonce count
- * @param cnonce Client generated nonce
- * @param qop Quality of protection aplied to the message
- * @param realmName Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest
- * MD5(Method + ":" + uri)
- * @param authMethod The authentication mehtod in use
- */
- public JAASCallbackHandler(JAASRealm realm, String username,
- String password, String nonce, String nc,
- String cnonce, String qop, String realmName,
- String md5a2, String authMethod) {
- this(realm, username, password);
- this.nonce = nonce;
- this.nc = nc;
- this.cnonce = cnonce;
- this.qop = qop;
- this.realmName = realmName;
- this.md5a2 = md5a2;
- this.authMethod = authMethod;
- }
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * The string manager for this package.
- */
- protected static final StringManager sm =
- StringManager.getManager(Constants.Package);
-
- /**
- * The password to be authenticated with.
- */
- protected String password = null;
-
-
- /**
- * The associated <code>JAASRealm</code> instance.
- */
- protected JAASRealm realm = null;
-
- /**
- * The username to be authenticated with.
- */
- protected String username = null;
-
- /**
- * Server generated nonce.
- */
- protected String nonce = null;
-
- /**
- * Nonce count.
- */
- protected String nc = null;
-
- /**
- * Client generated nonce.
- */
- protected String cnonce = null;
-
- /**
- * Quality of protection aplied to the message.
- */
- protected String qop;
-
- /**
- * Realm name.
- */
- protected String realmName;
-
- /**
- * Second MD5 digest.
- */
- protected String md5a2;
-
- /**
- * The authentication methdod to be used. If null, assume BASIC/FORM.
- */
- protected String authMethod;
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Retrieve the information requested in the provided <code>Callbacks</code>.
- * This implementation only recognizes {@link NameCallback},
- * {@link PasswordCallback} and {@link TextInputCallback}.
- * {@link TextInputCallback} is ued to pass the various additional
- * parameters required for DIGEST authentication.
- *
- * @param callbacks The set of <code>Callback</code>s to be processed
- *
- * @exception IOException if an input/output error occurs
- * @exception UnsupportedCallbackException if the login method requests
- * an unsupported callback type
- */
- public void handle(Callback callbacks[])
- throws IOException, UnsupportedCallbackException {
-
- for (int i = 0; i < callbacks.length; i++) {
-
- if (callbacks[i] instanceof NameCallback) {
- if (realm.getContainer().getLogger().isTraceEnabled())
- realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username));
- ((NameCallback) callbacks[i]).setName(username);
- } else if (callbacks[i] instanceof PasswordCallback) {
- final char[] passwordcontents;
- if (password != null) {
- passwordcontents = password.toCharArray();
- } else {
- passwordcontents = new char[0];
- }
- ((PasswordCallback) callbacks[i]).setPassword
- (passwordcontents);
- } else if (callbacks[i] instanceof TextInputCallback) {
- TextInputCallback cb = ((TextInputCallback) callbacks[i]);
- if (cb.getPrompt().equals("nonce")) {
- cb.setText(nonce);
- } else if (cb.getPrompt().equals("nc")) {
- cb.setText(nc);
- } else if (cb.getPrompt().equals("cnonce")) {
- cb.setText(cnonce);
- } else if (cb.getPrompt().equals("qop")) {
- cb.setText(qop);
- } else if (cb.getPrompt().equals("realmName")) {
- cb.setText(realmName);
- } else if (cb.getPrompt().equals("md5a2")) {
- cb.setText(md5a2);
- } else if (cb.getPrompt().equals("authMethod")) {
- cb.setText(authMethod);
- } else {
- throw new UnsupportedCallbackException(callbacks[i]);
- }
- } else {
- throw new UnsupportedCallbackException(callbacks[i]);
- }
- }
- }
-}
Deleted: trunk/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
===================================================================
--- trunk/java/org/apache/catalina/realm/JAASMemoryLoginModule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/JAASMemoryLoginModule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,432 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import java.io.File;
-import java.io.IOException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.TextInputCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.login.FailedLoginException;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.spi.LoginModule;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.catalina.Context;
-import org.apache.catalina.Realm;
-import org.apache.catalina.authenticator.Constants;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.deploy.SecurityConstraint;
-import org.apache.catalina.util.RequestUtil;
-import org.apache.catalina.util.StringManager;
-import org.apache.tomcat.util.digester.Digester;
-import org.jboss.logging.Logger;
-
-
-/**
- * <p>Implementation of the JAAS <strong>LoginModule</strong> interface,
- * primarily for use in testing <code>JAASRealm</code>. It utilizes an
- * XML-format data file of username/password/role information identical to
- * that supported by <code>org.apache.catalina.realm.MemoryRealm</code>
- * (except that digested passwords are not supported).</p>
- *
- * <p>This class recognizes the following string-valued options, which are
- * specified in the configuration file (and passed to our constructor in
- * the <code>options</code> argument:</p>
- * <ul>
- * <li><strong>debug</strong> - Set to "true" to get debugging messages
- * generated to System.out. The default value is <code>false</code>.</li>
- * <li><strong>pathname</strong> - Relative (to the pathname specified by the
- * "catalina.base" system property) or absolute pahtname to the
- * XML file containing our user information, in the format supported by
- * {@link MemoryRealm}. The default value matches the MemoryRealm
- * default.</li>
- * </ul>
- *
- * <p><strong>IMPLEMENTATION NOTE</strong> - This class implements
- * <code>Realm</code> only to satisfy the calling requirements of the
- * <code>GenericPrincipal</code> constructor. It does not actually perform
- * the functionality required of a <code>Realm</code> implementation.</p>
- *
- * @author Craig R. McClanahan
- * @version $Revision$ $Date$
- */
-
-public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule, Realm {
- // We need to extend MemoryRealm to avoid class cast
-
- private static Logger log = Logger.getLogger(JAASMemoryLoginModule.class);
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The callback handler responsible for answering our requests.
- */
- protected CallbackHandler callbackHandler = null;
-
-
- /**
- * Has our own <code>commit()</code> returned successfully?
- */
- protected boolean committed = false;
-
-
- /**
- * The configuration information for this <code>LoginModule</code>.
- */
- protected Map options = null;
-
-
- /**
- * The absolute or relative pathname to the XML configuration file.
- */
- protected String pathname = "conf/tomcat-users.xml";
-
-
- /**
- * The <code>Principal</code> identified by our validation, or
- * <code>null</code> if validation falied.
- */
- protected Principal principal = null;
-
-
- /**
- * The set of <code>Principals</code> loaded from our configuration file.
- */
- protected HashMap principals = new HashMap();
-
- /**
- * The string manager for this package.
- */
- protected static StringManager sm =
- StringManager.getManager(Constants.Package);
-
- /**
- * The state information that is shared with other configured
- * <code>LoginModule</code> instances.
- */
- protected Map sharedState = null;
-
-
- /**
- * The subject for which we are performing authentication.
- */
- protected Subject subject = null;
-
-
- // --------------------------------------------------------- Public Methods
-
- public JAASMemoryLoginModule() {
- log.debug("MEMORY LOGIN MODULE");
- }
-
- /**
- * Phase 2 of authenticating a <code>Subject</code> when Phase 1
- * fails. This method is called if the <code>LoginContext</code>
- * failed somewhere in the overall authentication chain.
- *
- * @return <code>true</code> if this method succeeded, or
- * <code>false</code> if this <code>LoginModule</code> should be
- * ignored
- *
- * @exception LoginException if the abort fails
- */
- public boolean abort() throws LoginException {
-
- // If our authentication was not successful, just return false
- if (principal == null)
- return (false);
-
- // Clean up if overall authentication failed
- if (committed)
- logout();
- else {
- committed = false;
- principal = null;
- }
- log.debug("Abort");
- return (true);
-
- }
-
-
- /**
- * Phase 2 of authenticating a <code>Subject</code> when Phase 1
- * was successful. This method is called if the <code>LoginContext</code>
- * succeeded in the overall authentication chain.
- *
- * @return <code>true</code> if the authentication succeeded, or
- * <code>false</code> if this <code>LoginModule</code> should be
- * ignored
- *
- * @exception LoginException if the commit fails
- */
- public boolean commit() throws LoginException {
- log.debug("commit " + principal);
-
- // If authentication was not successful, just return false
- if (principal == null)
- return (false);
-
- // Add our Principal to the Subject if needed
- if (!subject.getPrincipals().contains(principal)) {
- subject.getPrincipals().add(principal);
- // Add the roles as additional sudjucts as per the contract with the
- // JAASRealm
- if (principal instanceof GenericPrincipal) {
- String roles[] = ((GenericPrincipal) principal).getRoles();
- for (int i = 0; i < roles.length; i++) {
- subject.getPrincipals().add(
- new GenericPrincipal(null, roles[i], null));
- }
-
- }
- }
-
- committed = true;
- return (true);
-
- }
-
-
- /**
- * Return the SecurityConstraints configured to guard the request URI for
- * this request, or <code>null</code> if there is no such constraint.
- *
- * @param request Request we are processing
- * @param context Context the Request is mapped to
- */
- public SecurityConstraint [] findSecurityConstraints(Request request,
- Context context) {
- ArrayList<SecurityConstraint> results = null;
- // Are there any defined security constraints?
- SecurityConstraint constraints[] = context.findConstraints();
- if ((constraints == null) || (constraints.length == 0)) {
- if (context.getLogger().isDebugEnabled())
- context.getLogger().debug(" No applicable constraints defined");
- return (null);
- }
-
- // Check each defined security constraint
- String uri = request.getDecodedRequestURI();
- String contextPath = request.getContextPath();
- if (contextPath.length() > 0)
- uri = uri.substring(contextPath.length());
- uri = RequestUtil.URLDecode(uri); // Before checking constraints
- String method = request.getMethod();
- for (int i = 0; i < constraints.length; i++) {
- if (context.getLogger().isDebugEnabled())
- context.getLogger().debug(" Checking constraint '" + constraints[i] +
- "' against " + method + " " + uri + " --> " +
- constraints[i].included(uri, method));
- if (constraints[i].included(uri, method)) {
- if(results == null) {
- results = new ArrayList<SecurityConstraint>();
- }
- results.add(constraints[i]);
- }
- }
-
- // No applicable security constraint was found
- if (context.getLogger().isDebugEnabled())
- context.getLogger().debug(" No applicable constraint located");
- if(results == null)
- return null;
- SecurityConstraint [] array = new SecurityConstraint[results.size()];
- System.arraycopy(results.toArray(), 0, array, 0, array.length);
- return array;
- }
-
-
- /**
- * Initialize this <code>LoginModule</code> with the specified
- * configuration information.
- *
- * @param subject The <code>Subject</code> to be authenticated
- * @param callbackHandler A <code>CallbackHandler</code> for communicating
- * with the end user as necessary
- * @param sharedState State information shared with other
- * <code>LoginModule</code> instances
- * @param options Configuration information for this specific
- * <code>LoginModule</code> instance
- */
- public void initialize(Subject subject, CallbackHandler callbackHandler,
- Map sharedState, Map options) {
- log.debug("Init");
-
- // Save configuration values
- this.subject = subject;
- this.callbackHandler = callbackHandler;
- this.sharedState = sharedState;
- this.options = options;
-
- // Perform instance-specific initialization
- if (options.get("pathname") != null)
- this.pathname = (String) options.get("pathname");
-
- // Load our defined Principals
- load();
-
- }
-
-
- /**
- * Phase 1 of authenticating a <code>Subject</code>.
- *
- * @return <code>true</code> if the authentication succeeded, or
- * <code>false</code> if this <code>LoginModule</code> should be
- * ignored
- *
- * @exception LoginException if the authentication fails
- */
- public boolean login() throws LoginException {
-
- // Set up our CallbackHandler requests
- if (callbackHandler == null)
- throw new LoginException("No CallbackHandler specified");
- Callback callbacks[] = new Callback[9];
- callbacks[0] = new NameCallback("Username: ");
- callbacks[1] = new PasswordCallback("Password: ", false);
- callbacks[2] = new TextInputCallback("nonce");
- callbacks[3] = new TextInputCallback("nc");
- callbacks[4] = new TextInputCallback("cnonce");
- callbacks[5] = new TextInputCallback("qop");
- callbacks[6] = new TextInputCallback("realmName");
- callbacks[7] = new TextInputCallback("md5a2");
- callbacks[8] = new TextInputCallback("authMethod");
-
- // Interact with the user to retrieve the username and password
- String username = null;
- String password = null;
- String nonce = null;
- String nc = null;
- String cnonce = null;
- String qop = null;
- String realmName = null;
- String md5a2 = null;
- String authMethod = null;
-
- try {
- callbackHandler.handle(callbacks);
- username = ((NameCallback) callbacks[0]).getName();
- password =
- new String(((PasswordCallback) callbacks[1]).getPassword());
- nonce = ((TextInputCallback) callbacks[2]).getText();
- nc = ((TextInputCallback) callbacks[3]).getText();
- cnonce = ((TextInputCallback) callbacks[4]).getText();
- qop = ((TextInputCallback) callbacks[5]).getText();
- realmName = ((TextInputCallback) callbacks[6]).getText();
- md5a2 = ((TextInputCallback) callbacks[7]).getText();
- authMethod = ((TextInputCallback) callbacks[8]).getText();
- } catch (IOException e) {
- throw new LoginException(e.toString());
- } catch (UnsupportedCallbackException e) {
- throw new LoginException(e.toString());
- }
-
- // Validate the username and password we have received
- if (authMethod == null) {
- // BASIC or FORM
- principal = super.authenticate(username, password);
- } else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) {
- principal = super.authenticate(username, password, nonce, nc,
- cnonce, qop, realmName, md5a2);
- } else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) {
- principal = super.getPrincipal(username);
- } else {
- throw new LoginException("Unknown authentication method");
- }
-
- log.debug("login " + username + " " + principal);
-
- // Report results based on success or failure
- if (principal != null) {
- return (true);
- } else {
- throw new
- FailedLoginException("Username or password is incorrect");
- }
-
- }
-
-
- /**
- * Log out this user.
- *
- * @return <code>true</code> in all cases because thie
- * <code>LoginModule</code> should not be ignored
- *
- * @exception LoginException if logging out failed
- */
- public boolean logout() throws LoginException {
-
- subject.getPrincipals().remove(principal);
- committed = false;
- principal = null;
- return (true);
-
- }
-
-
- // ---------------------------------------------------------- Realm Methods
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Load the contents of our configuration file.
- */
- protected void load() {
-
- // Validate the existence of our configuration file
- File file = new File(pathname);
- if (!file.isAbsolute())
- file = new File(System.getProperty("catalina.base"), pathname);
- if (!file.exists() || !file.canRead()) {
- log.warn("Cannot load configuration file " + file.getAbsolutePath());
- return;
- }
-
- // Load the contents of our configuration file
- Digester digester = new Digester();
- digester.setValidating(false);
- digester.addRuleSet(new MemoryRuleSet());
- try {
- digester.push(this);
- digester.parse(file);
- } catch (Exception e) {
- log.warn("Error processing configuration file " +
- file.getAbsolutePath(), e);
- return;
- } finally {
- digester.reset();
- }
-
- }
-}
Deleted: trunk/java/org/apache/catalina/realm/JAASRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/JAASRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/JAASRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,609 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.AccountExpiredException;
-import javax.security.auth.login.CredentialExpiredException;
-import javax.security.auth.login.FailedLoginException;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.authenticator.Constants;
-import org.apache.catalina.util.StringManager;
-import org.jboss.logging.Logger;
-
-
-/**
- * <p>Implementation of <b>Realm</b> that authenticates users via the <em>Java
- * Authentication and Authorization Service</em> (JAAS). JAAS support requires
- * either JDK 1.4 (which includes it as part of the standard platform) or
- * JDK 1.3 (with the plug-in <code>jaas.jar</code> file).</p>
- *
- * <p>The value configured for the <code>appName</code> property is passed to
- * the <code>javax.security.auth.login.LoginContext</code> constructor, to
- * specify the <em>application name</em> used to select the set of relevant
- * <code>LoginModules</code> required.</p>
- *
- * <p>The JAAS Specification describes the result of a successful login as a
- * <code>javax.security.auth.Subject</code> instance, which can contain zero
- * or more <code>java.security.Principal</code> objects in the return value
- * of the <code>Subject.getPrincipals()</code> method. However, it provides
- * no guidance on how to distinguish Principals that describe the individual
- * user (and are thus appropriate to return as the value of
- * request.getUserPrincipal() in a web application) from the Principal(s)
- * that describe the authorized roles for this user. To maintain as much
- * independence as possible from the underlying <code>LoginMethod</code>
- * implementation executed by JAAS, the following policy is implemented by
- * this Realm:</p>
- * <ul>
- * <li>The JAAS <code>LoginModule</code> is assumed to return a
- * <code>Subject</code> with at least one <code>Principal</code> instance
- * representing the user himself or herself, and zero or more separate
- * <code>Principals</code> representing the security roles authorized
- * for this user.</li>
- * <li>On the <code>Principal</code> representing the user, the Principal
- * name is an appropriate value to return via the Servlet API method
- * <code>HttpServletRequest.getRemoteUser()</code>.</li>
- * <li>On the <code>Principals</code> representing the security roles, the
- * name is the name of the authorized security role.</li>
- * <li>This Realm will be configured with two lists of fully qualified Java
- * class names of classes that implement
- * <code>java.security.Principal</code> - one that identifies class(es)
- * representing a user, and one that identifies class(es) representing
- * a security role.</li>
- * <li>As this Realm iterates over the <code>Principals</code> returned by
- * <code>Subject.getPrincipals()</code>, it will identify the first
- * <code>Principal</code> that matches the "user classes" list as the
- * <code>Principal</code> for this user.</li>
- * <li>As this Realm iterates over the <code>Princpals</code> returned by
- * <code>Subject.getPrincipals()</code>, it will accumulate the set of
- * all <code>Principals</code> matching the "role classes" list as
- * identifying the security roles for this user.</li>
- * <li>It is a configuration error for the JAAS login method to return a
- * validated <code>Subject</code> without a <code>Principal</code> that
- * matches the "user classes" list.</li>
- * <li>By default, the enclosing Container's name serves as the
- * application name used to obtain the JAAS LoginContext ("Catalina" in
- * a default installation). Tomcat must be able to find an application
- * with this name in the JAAS configuration file. Here is a hypothetical
- * JAAS configuration file entry for a database-oriented login module that uses
- * a Tomcat-managed JNDI database resource:
- * <blockquote><pre>Catalina {
-org.foobar.auth.DatabaseLoginModule REQUIRED
- JNDI_RESOURCE=jdbc/AuthDB
- USER_TABLE=users
- USER_ID_COLUMN=id
- USER_NAME_COLUMN=name
- USER_CREDENTIAL_COLUMN=password
- ROLE_TABLE=roles
- ROLE_NAME_COLUMN=name
- PRINCIPAL_FACTORY=org.foobar.auth.impl.SimplePrincipalFactory;
-};</pre></blockquote></li>
- * <li>To set the JAAS configuration file
- * location, set the <code>CATALINA_OPTS</code> environment variable
- * similar to the following:
-<blockquote><code>CATALINA_OPTS="-Djava.security.auth.login.config=$CATALINA_HOME/conf/jaas.config"</code></blockquote>
- * </li>
- * <li>As part of the login process, JAASRealm registers its own <code>CallbackHandler</code>,
- * called (unsurprisingly) <code>JAASCallbackHandler</code>. This handler supplies the
- * HTTP requests's username and credentials to the user-supplied <code>LoginModule</code></li>
- * <li>As with other <code>Realm</code> implementations, digested passwords are supported if
- * the <code><Realm></code> element in <code>server.xml</code> contains a
- * <code>digest</code> attribute; <code>JAASCallbackHandler</code> will digest the password
- * prior to passing it back to the <code>LoginModule</code></li>
-* </ul>
-*
-* @author Craig R. McClanahan
-* @author Yoav Shapira
- * @version $Revision$ $Date$
- */
-
-public class JAASRealm
- extends RealmBase
- {
- private static Logger log = Logger.getLogger(JAASRealm.class);
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The application name passed to the JAAS <code>LoginContext</code>,
- * which uses it to select the set of relevant <code>LoginModule</code>s.
- */
- protected String appName = null;
-
-
- /**
- * Descriptive information about this <code>Realm</code> implementation.
- */
- protected static final String info =
- "org.apache.catalina.realm.JAASRealm/1.0";
-
-
- /**
- * Descriptive information about this <code>Realm</code> implementation.
- */
- protected static final String name = "JAASRealm";
-
-
- /**
- * The list of role class names, split out for easy processing.
- */
- protected List<String> roleClasses = new ArrayList<String>();
-
-
- /**
- * The string manager for this package.
- */
- protected static final StringManager sm =
- StringManager.getManager(Constants.Package);
-
-
- /**
- * The set of user class names, split out for easy processing.
- */
- protected List<String> userClasses = new ArrayList<String>();
-
-
- /**
- * Whether to use context ClassLoader or default ClassLoader.
- * True means use context ClassLoader, and True is the default
- * value.
- */
- protected boolean useContextClassLoader = true;
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * setter for the <code>appName</code> member variable
- * @deprecated JAAS should use the <code>Engine</code> (domain) name and webpp/host overrides
- */
- public void setAppName(String name) {
- appName = name;
- }
-
- /**
- * getter for the <code>appName</code> member variable
- */
- public String getAppName() {
- return appName;
- }
-
- /**
- * Sets whether to use the context or default ClassLoader.
- * True means use context ClassLoader.
- *
- * @param useContext True means use context ClassLoader
- */
- public void setUseContextClassLoader(boolean useContext) {
- useContextClassLoader = useContext;
- log.info("Setting useContextClassLoader = " + useContext);
- }
-
- /**
- * Returns whether to use the context or default ClassLoader.
- * True means to use the context ClassLoader.
- *
- * @return The value of useContextClassLoader
- */
- public boolean isUseContextClassLoader() {
- return useContextClassLoader;
- }
-
- public void setContainer(Container container) {
- super.setContainer(container);
-
- if( appName==null ) {
- String name=container.getName();
- name = makeLegalForJAAS(name);
-
- appName=name;
-
- log.info("Set JAAS app name " + appName);
- }
- }
-
- /**
- * Comma-delimited list of <code>java.security.Principal</code> classes
- * that represent security roles.
- */
- protected String roleClassNames = null;
-
- public String getRoleClassNames() {
- return (this.roleClassNames);
- }
-
- /**
- * Sets the list of comma-delimited classes that represent roles. The
- * classes in the list must implement <code>java.security.Principal</code>.
- * The supplied list of classes will be parsed when {@link #start()} is
- * called.
- */
- public void setRoleClassNames(String roleClassNames) {
- this.roleClassNames = roleClassNames;
- }
-
- /**
- * Parses a comma-delimited list of class names, and store the class names
- * in the provided List. Each class must implement
- * <code>java.security.Principal</code>.
- *
- * @param classNamesString a comma-delimited list of fully qualified class names.
- * @param classNamesList the list in which the class names will be stored.
- * The list is cleared before being populated.
- */
- protected void parseClassNames(String classNamesString, List<String> classNamesList) {
- classNamesList.clear();
- if (classNamesString == null) return;
-
- ClassLoader loader = this.getClass().getClassLoader();
- if (isUseContextClassLoader())
- loader = Thread.currentThread().getContextClassLoader();
-
- String[] classNames = classNamesString.split("[ ]*,[ ]*");
- for (int i=0; i<classNames.length; i++) {
- if (classNames[i].length()==0) continue;
- try {
- Class principalClass = Class.forName(classNames[i], false,
- loader);
- if (Principal.class.isAssignableFrom(principalClass)) {
- classNamesList.add(classNames[i]);
- } else {
- log.error("Class "+classNames[i]+" is not implementing "+
- "java.security.Principal! Class not added.");
- }
- } catch (ClassNotFoundException e) {
- log.error("Class "+classNames[i]+" not found! Class not added.");
- }
- }
- }
-
- /**
- * Comma-delimited list of <code>java.security.Principal</code> classes
- * that represent individual users.
- */
- protected String userClassNames = null;
-
- public String getUserClassNames() {
- return (this.userClassNames);
- }
-
- /**
- * Sets the list of comma-delimited classes that represent individual
- * users. The classes in the list must implement
- * <code>java.security.Principal</code>. The supplied list of classes will
- * be parsed when {@link #start()} is called.
- */
- public void setUserClassNames(String userClassNames) {
- this.userClassNames = userClassNames;
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return the <code>Principal</code> associated with the specified username
- * and credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the <code>Principal</code> to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, String credentials) {
- return authenticate(username,
- new JAASCallbackHandler(this, username, credentials));
- }
-
-
- /**
- * Return the <code>Principal</code> associated with the specified username
- * and digest, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the <code>Principal</code> to look up
- * @param clientDigest Digest to use in authenticating this username
- * @param nonce Server generated nonce
- * @param nc Nonce count
- * @param cnonce Client generated nonce
- * @param qop Quality of protection aplied to the message
- * @param realmName Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest
- * MD5(Method + ":" + uri)
- * @param authMethod The authentication scheme in use
- */
- public Principal authenticate(String username, String clientDigest,
- String nonce, String nc, String cnonce, String qop,
- String realmName, String md5a2) {
- return authenticate(username,
- new JAASCallbackHandler(this, username, clientDigest, nonce,
- nc, cnonce, qop, realmName, md5a2,
- HttpServletRequest.DIGEST_AUTH));
- }
-
-
- // -------------------------------------------------------- Package Methods
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Perform the actual JAAS authentication
- */
- protected Principal authenticate(String username,
- CallbackHandler callbackHandler) {
-
- // Establish a LoginContext to use for authentication
- try {
- LoginContext loginContext = null;
- if( appName==null ) appName="Tomcat";
-
- if( log.isDebugEnabled())
- log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
-
- // What if the LoginModule is in the container class loader ?
- ClassLoader ocl = null;
-
- if (!isUseContextClassLoader()) {
- ocl = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(
- this.getClass().getClassLoader());
- }
-
- try {
- loginContext = new LoginContext(appName, callbackHandler);
- } catch (Throwable e) {
- log.error(sm.getString("jaasRealm.unexpectedError"), e);
- return (null);
- } finally {
- if(!isUseContextClassLoader()) {
- Thread.currentThread().setContextClassLoader(ocl);
- }
- }
-
- if( log.isDebugEnabled())
- log.debug("Login context created " + username);
-
- // Negotiate a login via this LoginContext
- Subject subject = null;
- try {
- loginContext.login();
- subject = loginContext.getSubject();
- if (subject == null) {
- if( log.isDebugEnabled())
- log.debug(sm.getString("jaasRealm.failedLogin", username));
- return (null);
- }
- } catch (AccountExpiredException e) {
- if (log.isDebugEnabled())
- log.debug(sm.getString("jaasRealm.accountExpired", username));
- return (null);
- } catch (CredentialExpiredException e) {
- if (log.isDebugEnabled())
- log.debug(sm.getString("jaasRealm.credentialExpired", username));
- return (null);
- } catch (FailedLoginException e) {
- if (log.isDebugEnabled())
- log.debug(sm.getString("jaasRealm.failedLogin", username));
- return (null);
- } catch (LoginException e) {
- log.warn(sm.getString("jaasRealm.loginException", username), e);
- return (null);
- } catch (Throwable e) {
- log.error(sm.getString("jaasRealm.unexpectedError"), e);
- return (null);
- }
-
- if( log.isDebugEnabled())
- log.debug(sm.getString("jaasRealm.loginContextCreated", username));
-
- // Return the appropriate Principal for this authenticated Subject
- Principal principal = createPrincipal(username, subject, loginContext);
- if (principal == null) {
- log.debug(sm.getString("jaasRealm.authenticateFailure", username));
- return (null);
- }
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
- }
-
- return (principal);
- } catch( Throwable t) {
- log.error( "error ", t);
- return null;
- }
- }
-
- /**
- * Return a short name for this <code>Realm</code> implementation.
- */
- protected String getName() {
-
- return (name);
-
- }
-
-
- /**
- * Return the password associated with the given principal's user name. This
- * always returns null as the JAASRealm has no way of obtaining this
- * information.
- */
- protected String getPassword(String username) {
-
- return (null);
-
- }
-
-
- /**
- * Return the <code>Principal</code> associated with the given user name.
- */
- protected Principal getPrincipal(String username) {
-
- return authenticate(username,
- new JAASCallbackHandler(this, username, null, null, null, null,
- null, null, null, HttpServletRequest.CLIENT_CERT_AUTH));
-
- }
-
-
- /**
- * Identify and return a <code>java.security.Principal</code> instance
- * representing the authenticated user for the specified <code>Subject</code>.
- * The Principal is constructed by scanning the list of Principals returned
- * by the JAASLoginModule. The first <code>Principal</code> object that matches
- * one of the class names supplied as a "user class" is the user Principal.
- * This object is returned to tha caller.
- * Any remaining principal objects returned by the LoginModules are mapped to
- * roles, but only if their respective classes match one of the "role class" classes.
- * If a user Principal cannot be constructed, return <code>null</code>.
- * @param subject The <code>Subject</code> representing the logged-in user
- * @param loginContext Associated with th Princpal so
- * {@link LoginContext#logout()} can be called later
- */
- protected Principal createPrincipal(String username, Subject subject,
- LoginContext loginContext) {
- // Prepare to scan the Principals for this Subject
-
- List<String> roles = new ArrayList<String>();
- Principal userPrincipal = null;
-
- // Scan the Principals for this Subject
- Iterator<Principal> principals = subject.getPrincipals().iterator();
- while (principals.hasNext()) {
- Principal principal = principals.next();
-
- String principalClass = principal.getClass().getName();
-
- if( log.isDebugEnabled() ) {
- log.debug(sm.getString("jaasRealm.checkPrincipal", principal, principalClass));
- }
-
- if (userPrincipal == null && userClasses.contains(principalClass)) {
- userPrincipal = principal;
- if( log.isDebugEnabled() ) {
- log.debug(sm.getString("jaasRealm.userPrincipalSuccess", principal.getName()));
- }
- }
-
- if (roleClasses.contains(principalClass)) {
- roles.add(principal.getName());
- if( log.isDebugEnabled() ) {
- log.debug(sm.getString("jaasRealm.rolePrincipalAdd", principal.getName()));
- }
- }
- }
-
- // Print failure message if needed
- if (userPrincipal == null) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("jaasRealm.userPrincipalFailure"));
- log.debug(sm.getString("jaasRealm.rolePrincipalFailure"));
- }
- } else {
- if (roles.size() == 0) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("jaasRealm.rolePrincipalFailure"));
- }
- }
- }
-
- // Return the resulting Principal for our authenticated user
- return new GenericPrincipal(this, username, null, roles, userPrincipal,
- loginContext);
- }
-
- /**
- * Ensure the given name is legal for JAAS configuration.
- * Added for Bugzilla 30869, made protected for easy customization
- * in case my implementation is insufficient, which I think is
- * very likely.
- *
- * @param src The name to validate
- * @return A string that's a valid JAAS realm name
- */
- protected String makeLegalForJAAS(final String src) {
- String result = src;
-
- // Default name is "other" per JAAS spec
- if(result == null) {
- result = "other";
- }
-
- // Strip leading slash if present, as Sun JAAS impl
- // barfs on it (see Bugzilla 30869 bug report).
- if(result.startsWith("/")) {
- result = result.substring(1);
- }
-
- return result;
- }
-
-
- // ------------------------------------------------------ Lifecycle Methods
-
-
- /**
- *
- * Prepare for active use of the public methods of this <code>Component</code>.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents it from being started
- */
- public void start() throws LifecycleException {
-
- // Perform normal superclass initialization
- super.start();
-
- // These need to be called after loading configuration, in case
- // useContextClassLoader appears after them in xml config
- parseClassNames(userClassNames, userClasses);
- parseClassNames(roleClassNames, roleClasses);
- }
-
-
- /**
- * Gracefully shut down active use of the public methods of this <code>Component</code>.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
- */
- public void stop() throws LifecycleException {
-
- // Perform normal superclass finalization
- super.stop();
-
- }
-
-
-}
Deleted: trunk/java/org/apache/catalina/realm/JDBCRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/JDBCRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/JDBCRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,797 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import java.security.Principal;
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Properties;
-
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.util.StringManager;
-
-
-/**
-*
-* Implmentation of <b>Realm</b> that works with any JDBC supported database.
-* See the JDBCRealm.howto for more details on how to set up the database and
-* for configuration options.
-*
-* <p><strong>NOTE</strong>: This realm features simple configuration, but
-* uses a single connection to the database. In cases where authentication
-* becomes a bottleneck, the DataSource realm must be used instead.</p>
-*
-* @author Craig R. McClanahan
-* @author Carson McDonald
-* @author Ignacio Ortega
-* @version $Revision$ $Date$
-*/
-
-public class JDBCRealm
- extends RealmBase {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The connection username to use when trying to connect to the database.
- */
- protected String connectionName = null;
-
-
- /**
- * The connection URL to use when trying to connect to the database.
- */
- protected String connectionPassword = null;
-
-
- /**
- * The connection URL to use when trying to connect to the database.
- */
- protected String connectionURL = null;
-
-
- /**
- * The connection to the database.
- */
- protected Connection dbConnection = null;
-
-
- /**
- * Instance of the JDBC Driver class we use as a connection factory.
- */
- protected Driver driver = null;
-
-
- /**
- * The JDBC driver to use.
- */
- protected String driverName = null;
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected static final String info =
- "org.apache.catalina.realm.JDBCRealm/1.0";
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected static final String name = "JDBCRealm";
-
-
- /**
- * The PreparedStatement to use for authenticating users.
- */
- protected PreparedStatement preparedCredentials = null;
-
-
- /**
- * The PreparedStatement to use for identifying the roles for
- * a specified user.
- */
- protected PreparedStatement preparedRoles = null;
-
-
- /**
- * The column in the user role table that names a role
- */
- protected String roleNameCol = null;
-
-
- /**
- * The string manager for this package.
- */
- protected static final StringManager sm =
- StringManager.getManager(Constants.Package);
-
-
- /**
- * The column in the user table that holds the user's credintials
- */
- protected String userCredCol = null;
-
-
- /**
- * The column in the user table that holds the user's name
- */
- protected String userNameCol = null;
-
-
- /**
- * The table that holds the relation between user's and roles
- */
- protected String userRoleTable = null;
-
-
- /**
- * The table that holds user data.
- */
- protected String userTable = null;
-
-
- // ------------------------------------------------------------- Properties
-
- /**
- * Return the username to use to connect to the database.
- *
- */
- public String getConnectionName() {
- return connectionName;
- }
-
- /**
- * Set the username to use to connect to the database.
- *
- * @param connectionName Username
- */
- public void setConnectionName(String connectionName) {
- this.connectionName = connectionName;
- }
-
- /**
- * Return the password to use to connect to the database.
- *
- */
- public String getConnectionPassword() {
- return connectionPassword;
- }
-
- /**
- * Set the password to use to connect to the database.
- *
- * @param connectionPassword User password
- */
- public void setConnectionPassword(String connectionPassword) {
- this.connectionPassword = connectionPassword;
- }
-
- /**
- * Return the URL to use to connect to the database.
- *
- */
- public String getConnectionURL() {
- return connectionURL;
- }
-
- /**
- * Set the URL to use to connect to the database.
- *
- * @param connectionURL The new connection URL
- */
- public void setConnectionURL( String connectionURL ) {
- this.connectionURL = connectionURL;
- }
-
- /**
- * Return the JDBC driver that will be used.
- *
- */
- public String getDriverName() {
- return driverName;
- }
-
- /**
- * Set the JDBC driver that will be used.
- *
- * @param driverName The driver name
- */
- public void setDriverName( String driverName ) {
- this.driverName = driverName;
- }
-
- /**
- * Return the column in the user role table that names a role.
- *
- */
- public String getRoleNameCol() {
- return roleNameCol;
- }
-
- /**
- * Set the column in the user role table that names a role.
- *
- * @param roleNameCol The column name
- */
- public void setRoleNameCol( String roleNameCol ) {
- this.roleNameCol = roleNameCol;
- }
-
- /**
- * Return the column in the user table that holds the user's credentials.
- *
- */
- public String getUserCredCol() {
- return userCredCol;
- }
-
- /**
- * Set the column in the user table that holds the user's credentials.
- *
- * @param userCredCol The column name
- */
- public void setUserCredCol( String userCredCol ) {
- this.userCredCol = userCredCol;
- }
-
- /**
- * Return the column in the user table that holds the user's name.
- *
- */
- public String getUserNameCol() {
- return userNameCol;
- }
-
- /**
- * Set the column in the user table that holds the user's name.
- *
- * @param userNameCol The column name
- */
- public void setUserNameCol( String userNameCol ) {
- this.userNameCol = userNameCol;
- }
-
- /**
- * Return the table that holds the relation between user's and roles.
- *
- */
- public String getUserRoleTable() {
- return userRoleTable;
- }
-
- /**
- * Set the table that holds the relation between user's and roles.
- *
- * @param userRoleTable The table name
- */
- public void setUserRoleTable( String userRoleTable ) {
- this.userRoleTable = userRoleTable;
- }
-
- /**
- * Return the table that holds user data..
- *
- */
- public String getUserTable() {
- return userTable;
- }
-
- /**
- * Set the table that holds user data.
- *
- * @param userTable The table name
- */
- public void setUserTable( String userTable ) {
- this.userTable = userTable;
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * If there are any errors with the JDBC connection, executing
- * the query or anything we return null (don't authenticate). This
- * event is also logged, and the connection will be closed so that
- * a subsequent request will automatically re-open it.
- *
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public synchronized Principal authenticate(String username, String credentials) {
-
- // No user or no credentials
- // Can't possibly authenticate, don't bother the database then
- if (username == null || credentials == null) {
- return null;
- }
-
- // Number of tries is the numebr of attempts to connect to the database
- // during this login attempt (if we need to open the database)
- // This needs rewritten wuth better pooling support, the existing code
- // needs signature changes since the Prepared statements needs cached
- // with the connections.
- // The code below will try twice if there is a SQLException so the
- // connection may try to be opened again. On normal conditions (including
- // invalid login - the above is only used once.
- int numberOfTries = 2;
- while (numberOfTries>0) {
- try {
-
- // Ensure that we have an open database connection
- open();
-
- // Acquire a Principal object for this user
- Principal principal = authenticate(dbConnection,
- username, credentials);
-
-
- // Return the Principal (if any)
- return (principal);
-
- } catch (SQLException e) {
-
- // Log the problem for posterity
- containerLog.error(sm.getString("jdbcRealm.exception"), e);
-
- // Close the connection so that it gets reopened next time
- if (dbConnection != null)
- close(dbConnection);
-
- }
-
- numberOfTries--;
- }
-
- // Worst case scenario
- return null;
-
- }
-
-
- // -------------------------------------------------------- Package Methods
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param dbConnection The database connection to be used
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- protected synchronized Principal authenticate(Connection dbConnection,
- String username,
- String credentials) {
-
- // Look up the user's credentials
- String dbCredentials = getPassword(username);
-
- // Validate the user's credentials
- boolean validated = false;
- if (hasMessageDigest()) {
- // Hex hashes should be compared case-insensitive
- validated = (digest(credentials).equalsIgnoreCase(dbCredentials));
- } else {
- validated = (digest(credentials).equals(dbCredentials));
- }
-
- if (validated) {
- if (containerLog.isTraceEnabled())
- containerLog.trace(sm.getString("jdbcRealm.authenticateSuccess",
- username));
- } else {
- if (containerLog.isTraceEnabled())
- containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
- username));
- return (null);
- }
-
- ArrayList roles = getRoles(username);
-
- // Create and return a suitable Principal for this user
- return (new GenericPrincipal(this, username, credentials, roles));
-
- }
-
-
- /**
- * Close the specified database connection.
- *
- * @param dbConnection The connection to be closed
- */
- protected void close(Connection dbConnection) {
-
- // Do nothing if the database connection is already closed
- if (dbConnection == null)
- return;
-
- // Close our prepared statements (if any)
- try {
- preparedCredentials.close();
- } catch (Throwable f) {
- ;
- }
- this.preparedCredentials = null;
-
-
- try {
- preparedRoles.close();
- } catch (Throwable f) {
- ;
- }
- this.preparedRoles = null;
-
-
- // Close this database connection, and log any errors
- try {
- dbConnection.close();
- } catch (SQLException e) {
- containerLog.warn(sm.getString("jdbcRealm.close"), e); // Just log it here
- } finally {
- this.dbConnection = null;
- }
-
- }
-
-
- /**
- * Return a PreparedStatement configured to perform the SELECT required
- * to retrieve user credentials for the specified username.
- *
- * @param dbConnection The database connection to be used
- * @param username Username for which credentials should be retrieved
- *
- * @exception SQLException if a database error occurs
- */
- protected PreparedStatement credentials(Connection dbConnection,
- String username)
- throws SQLException {
-
- if (preparedCredentials == null) {
- StringBuilder sb = new StringBuilder("SELECT ");
- sb.append(userCredCol);
- sb.append(" FROM ");
- sb.append(userTable);
- sb.append(" WHERE ");
- sb.append(userNameCol);
- sb.append(" = ?");
-
- if(containerLog.isDebugEnabled()) {
- containerLog.debug("credentials query: " + sb.toString());
- }
-
- preparedCredentials =
- dbConnection.prepareStatement(sb.toString());
- }
-
- if (username == null) {
- preparedCredentials.setNull(1,java.sql.Types.VARCHAR);
- } else {
- preparedCredentials.setString(1, username);
- }
-
- return (preparedCredentials);
- }
-
-
- /**
- * Return a short name for this Realm implementation.
- */
- protected String getName() {
-
- return (name);
-
- }
-
-
- /**
- * Return the password associated with the given principal's user name.
- */
- protected synchronized String getPassword(String username) {
-
- // Look up the user's credentials
- String dbCredentials = null;
- PreparedStatement stmt = null;
- ResultSet rs = null;
-
- // Number of tries is the numebr of attempts to connect to the database
- // during this login attempt (if we need to open the database)
- // This needs rewritten wuth better pooling support, the existing code
- // needs signature changes since the Prepared statements needs cached
- // with the connections.
- // The code below will try twice if there is a SQLException so the
- // connection may try to be opened again. On normal conditions (including
- // invalid login - the above is only used once.
- int numberOfTries = 2;
- while (numberOfTries>0) {
- try {
-
- // Ensure that we have an open database connection
- open();
-
- try {
- stmt = credentials(dbConnection, username);
- rs = stmt.executeQuery();
-
- if (rs.next()) {
- dbCredentials = rs.getString(1);
- }
- rs.close();
- rs = null;
- if (dbCredentials == null) {
- return (null);
- }
-
- dbCredentials = dbCredentials.trim();
- return dbCredentials;
-
- } finally {
- if (rs!=null) {
- try {
- rs.close();
- } catch(SQLException e) {
- containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet"));
- }
- }
- dbConnection.commit();
- }
-
- } catch (SQLException e) {
-
- // Log the problem for posterity
- containerLog.error(sm.getString("jdbcRealm.exception"), e);
-
- // Close the connection so that it gets reopened next time
- if (dbConnection != null)
- close(dbConnection);
-
- }
-
- numberOfTries--;
- }
-
- return (null);
- }
-
-
- /**
- * Return the Principal associated with the given user name.
- */
- protected synchronized Principal getPrincipal(String username) {
-
- return (new GenericPrincipal(this,
- username,
- getPassword(username),
- getRoles(username)));
-
- }
-
-
- /**
- * Return the roles associated with the gven user name.
- */
- protected ArrayList getRoles(String username) {
-
- PreparedStatement stmt = null;
- ResultSet rs = null;
-
- // Number of tries is the numebr of attempts to connect to the database
- // during this login attempt (if we need to open the database)
- // This needs rewritten wuth better pooling support, the existing code
- // needs signature changes since the Prepared statements needs cached
- // with the connections.
- // The code below will try twice if there is a SQLException so the
- // connection may try to be opened again. On normal conditions (including
- // invalid login - the above is only used once.
- int numberOfTries = 2;
- while (numberOfTries>0) {
- try {
-
- // Ensure that we have an open database connection
- open();
-
- try {
- // Accumulate the user's roles
- ArrayList roleList = new ArrayList();
- stmt = roles(dbConnection, username);
- rs = stmt.executeQuery();
- while (rs.next()) {
- String role = rs.getString(1);
- if (null!=role) {
- roleList.add(role.trim());
- }
- }
- rs.close();
- rs = null;
-
- return (roleList);
-
- } finally {
- if (rs!=null) {
- try {
- rs.close();
- } catch(SQLException e) {
- containerLog.warn(sm.getString("jdbcRealm.abnormalCloseResultSet"));
- }
- }
- dbConnection.commit();
- }
-
- } catch (SQLException e) {
-
- // Log the problem for posterity
- containerLog.error(sm.getString("jdbcRealm.exception"), e);
-
- // Close the connection so that it gets reopened next time
- if (dbConnection != null)
- close(dbConnection);
-
- }
-
- numberOfTries--;
- }
-
- return (null);
-
- }
-
-
- /**
- * Open (if necessary) and return a database connection for use by
- * this Realm.
- *
- * @exception SQLException if a database error occurs
- */
- protected Connection open() throws SQLException {
-
- // Do nothing if there is a database connection already open
- if (dbConnection != null)
- return (dbConnection);
-
- // Instantiate our database driver if necessary
- if (driver == null) {
- try {
- Class clazz = Class.forName(driverName);
- driver = (Driver) clazz.newInstance();
- } catch (Throwable e) {
- throw new SQLException(e.getMessage());
- }
- }
-
- // Open a new connection
- Properties props = new Properties();
- if (connectionName != null)
- props.put("user", connectionName);
- if (connectionPassword != null)
- props.put("password", connectionPassword);
- dbConnection = driver.connect(connectionURL, props);
- if (dbConnection == null) {
- throw new SQLException(sm.getString("jdbcRealm.open.invalidurl",driverName, connectionURL));
- }
- dbConnection.setAutoCommit(false);
- return (dbConnection);
-
- }
-
-
- /**
- * Release our use of this connection so that it can be recycled.
- *
- * @param dbConnection The connection to be released
- */
- protected void release(Connection dbConnection) {
-
- ; // NO-OP since we are not pooling anything
-
- }
-
-
- /**
- * Return a PreparedStatement configured to perform the SELECT required
- * to retrieve user roles for the specified username.
- *
- * @param dbConnection The database connection to be used
- * @param username Username for which roles should be retrieved
- *
- * @exception SQLException if a database error occurs
- */
- protected synchronized PreparedStatement roles(Connection dbConnection,
- String username)
- throws SQLException {
-
- if (preparedRoles == null) {
- StringBuilder sb = new StringBuilder("SELECT ");
- sb.append(roleNameCol);
- sb.append(" FROM ");
- sb.append(userRoleTable);
- sb.append(" WHERE ");
- sb.append(userNameCol);
- sb.append(" = ?");
- preparedRoles =
- dbConnection.prepareStatement(sb.toString());
- }
-
- preparedRoles.setString(1, username);
- return (preparedRoles);
-
- }
-
-
- // ------------------------------------------------------ Lifecycle Methods
-
-
- /**
- *
- * Prepare for active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents it from being started
- */
- public void start() throws LifecycleException {
-
- // Perform normal superclass initialization
- super.start();
-
- // Validate that we can open our connection - but let tomcat
- // startup in case the database is temporarily unavailable
- try {
- open();
- } catch (SQLException e) {
- containerLog.error(sm.getString("jdbcRealm.open"), e);
- }
-
- }
-
-
- /**
- * Gracefully shut down active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
- */
- public void stop() throws LifecycleException {
-
- // Perform normal superclass finalization
- super.stop();
-
- // Close any open DB connection
- close(this.dbConnection);
-
- }
-
-
-}
Deleted: trunk/java/org/apache/catalina/realm/JNDIRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/JNDIRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/JNDIRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,2234 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.Principal;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import javax.naming.AuthenticationException;
-import javax.naming.CommunicationException;
-import javax.naming.CompositeName;
-import javax.naming.Context;
-import javax.naming.InvalidNameException;
-import javax.naming.Name;
-import javax.naming.NameNotFoundException;
-import javax.naming.NameParser;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.PartialResultException;
-import javax.naming.ServiceUnavailableException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.InitialDirContext;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.util.Base64;
-import org.apache.tomcat.util.buf.ByteChunk;
-import org.apache.tomcat.util.buf.CharChunk;
-
-/**
- * <p>Implementation of <strong>Realm</strong> that works with a directory
- * server accessed via the Java Naming and Directory Interface (JNDI) APIs.
- * The following constraints are imposed on the data structure in the
- * underlying directory server:</p>
- * <ul>
- *
- * <li>Each user that can be authenticated is represented by an individual
- * element in the top level <code>DirContext</code> that is accessed
- * via the <code>connectionURL</code> property.</li>
- *
- * <li>If a socket connection can not be made to the <code>connectURL</code>
- * an attempt will be made to use the <code>alternateURL</code> if it
- * exists.</li>
- *
- * <li>Each user element has a distinguished name that can be formed by
- * substituting the presented username into a pattern configured by the
- * <code>userPattern</code> property.</li>
- *
- * <li>Alternatively, if the <code>userPattern</code> property is not
- * specified, a unique element can be located by searching the directory
- * context. In this case:
- * <ul>
- * <li>The <code>userSearch</code> pattern specifies the search filter
- * after substitution of the username.</li>
- * <li>The <code>userBase</code> property can be set to the element that
- * is the base of the subtree containing users. If not specified,
- * the search base is the top-level context.</li>
- * <li>The <code>userSubtree</code> property can be set to
- * <code>true</code> if you wish to search the entire subtree of the
- * directory context. The default value of <code>false</code>
- * requests a search of only the current level.</li>
- * </ul>
- * </li>
- *
- * <li>The user may be authenticated by binding to the directory with the
- * username and password presented. This method is used when the
- * <code>userPassword</code> property is not specified.</li>
- *
- * <li>The user may be authenticated by retrieving the value of an attribute
- * from the directory and comparing it explicitly with the value presented
- * by the user. This method is used when the <code>userPassword</code>
- * property is specified, in which case:
- * <ul>
- * <li>The element for this user must contain an attribute named by the
- * <code>userPassword</code> property.
- * <li>The value of the user password attribute is either a cleartext
- * String, or the result of passing a cleartext String through the
- * <code>RealmBase.digest()</code> method (using the standard digest
- * support included in <code>RealmBase</code>).
- * <li>The user is considered to be authenticated if the presented
- * credentials (after being passed through
- * <code>RealmBase.digest()</code>) are equal to the retrieved value
- * for the user password attribute.</li>
- * </ul></li>
- *
- * <li>Each group of users that has been assigned a particular role may be
- * represented by an individual element in the top level
- * <code>DirContext</code> that is accessed via the
- * <code>connectionURL</code> property. This element has the following
- * characteristics:
- * <ul>
- * <li>The set of all possible groups of interest can be selected by a
- * search pattern configured by the <code>roleSearch</code>
- * property.</li>
- * <li>The <code>roleSearch</code> pattern optionally includes pattern
- * replacements "{0}" for the distinguished name, and/or "{1}" for
- * the username, of the authenticated user for which roles will be
- * retrieved.</li>
- * <li>The <code>roleBase</code> property can be set to the element that
- * is the base of the search for matching roles. If not specified,
- * the entire context will be searched.</li>
- * <li>The <code>roleSubtree</code> property can be set to
- * <code>true</code> if you wish to search the entire subtree of the
- * directory context. The default value of <code>false</code>
- * requests a search of only the current level.</li>
- * <li>The element includes an attribute (whose name is configured by
- * the <code>roleName</code> property) containing the name of the
- * role represented by this element.</li>
- * </ul></li>
- *
- * <li>In addition, roles may be represented by the values of an attribute
- * in the user's element whose name is configured by the
- * <code>userRoleName</code> property.</li>
- *
- * <li>A default role can be assigned to each user that was successfully
- * authenticated by setting the <code>commonRole</code> property to the
- * name of this role. The role doesn't have to exist in the directory.</li>
- *
- * <li>If the directory server contains nested roles, you can search for them
- * by setting <code>roleNested</code> to <code>true</code>.
- * The default value is <code>false</code>, so role searches will not find
- * nested roles.</li>
- *
- * <li>Note that the standard <code><security-role-ref></code> element in
- * the web application deployment descriptor allows applications to refer
- * to roles programmatically by names other than those used in the
- * directory server itself.</li>
- * </ul>
- *
- * <p><strong>TODO</strong> - Support connection pooling (including message
- * format objects) so that <code>authenticate()</code> does not have to be
- * synchronized.</p>
- *
- * <p><strong>WARNING</strong> - There is a reported bug against the Netscape
- * provider code (com.netscape.jndi.ldap.LdapContextFactory) with respect to
- * successfully authenticated a non-existing user. The
- * report is here: http://issues.apache.org/bugzilla/show_bug.cgi?id=11210 .
- * With luck, Netscape has updated their provider code and this is not an
- * issue. </p>
- *
- * @author John Holman
- * @author Craig R. McClanahan
- * @version $Revision$ $Date$
- */
-
-public class JNDIRealm extends RealmBase {
-
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * The type of authentication to use
- */
- protected String authentication = null;
-
- /**
- * The connection username for the server we will contact.
- */
- protected String connectionName = null;
-
-
- /**
- * The connection password for the server we will contact.
- */
- protected String connectionPassword = null;
-
-
- /**
- * The connection URL for the server we will contact.
- */
- protected String connectionURL = null;
-
-
- /**
- * The directory context linking us to our directory server.
- */
- protected DirContext context = null;
-
-
- /**
- * The JNDI context factory used to acquire our InitialContext. By
- * default, assumes use of an LDAP server using the standard JNDI LDAP
- * provider.
- */
- protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
-
-
- /**
- * How aliases should be dereferenced during search operations.
- */
- protected String derefAliases = null;
-
- /**
- * Constant that holds the name of the environment property for specifying
- * the manner in which aliases should be dereferenced.
- */
- public final static String DEREF_ALIASES = "java.naming.ldap.derefAliases";
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected static final String info =
- "org.apache.catalina.realm.JNDIRealm/1.0";
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected static final String name = "JNDIRealm";
-
-
- /**
- * The protocol that will be used in the communication with the
- * directory server.
- */
- protected String protocol = null;
-
-
- /**
- * Should we ignore PartialResultExceptions when iterating over NamingEnumerations?
- * Microsoft Active Directory often returns referrals, which lead
- * to PartialResultExceptions. Unfortunately there's no stable way to detect,
- * if the Exceptions really come from an AD referral.
- * Set to true to ignore PartialResultExceptions.
- */
- protected boolean adCompat = false;
-
-
- /**
- * How should we handle referrals? Microsoft Active Directory often returns
- * referrals. If you need to follow them set referrals to "follow".
- * Caution: if your DNS is not part of AD, the LDAP client lib might try
- * to resolve your domain name in DNS to find another LDAP server.
- */
- protected String referrals = null;
-
-
- /**
- * The base element for user searches.
- */
- protected String userBase = "";
-
-
- /**
- * The message format used to search for a user, with "{0}" marking
- * the spot where the username goes.
- */
- protected String userSearch = null;
-
-
- /**
- * The MessageFormat object associated with the current
- * <code>userSearch</code>.
- */
- protected MessageFormat userSearchFormat = null;
-
-
- /**
- * Should we search the entire subtree for matching users?
- */
- protected boolean userSubtree = false;
-
-
- /**
- * The attribute name used to retrieve the user password.
- */
- protected String userPassword = null;
-
-
- /**
- * A string of LDAP user patterns or paths, ":"-separated
- * These will be used to form the distinguished name of a
- * user, with "{0}" marking the spot where the specified username
- * goes.
- * This is similar to userPattern, but allows for multiple searches
- * for a user.
- */
- protected String[] userPatternArray = null;
-
-
- /**
- * The message format used to form the distinguished name of a
- * user, with "{0}" marking the spot where the specified username
- * goes.
- */
- protected String userPattern = null;
-
-
- /**
- * An array of MessageFormat objects associated with the current
- * <code>userPatternArray</code>.
- */
- protected MessageFormat[] userPatternFormatArray = null;
-
- /**
- * The base element for role searches.
- */
- protected String roleBase = "";
-
-
- /**
- * The MessageFormat object associated with the current
- * <code>roleSearch</code>.
- */
- protected MessageFormat roleFormat = null;
-
-
- /**
- * The name of an attribute in the user's entry containing
- * roles for that user
- */
- protected String userRoleName = null;
-
-
- /**
- * The name of the attribute containing roles held elsewhere
- */
- protected String roleName = null;
-
-
- /**
- * The message format used to select roles for a user, with "{0}" marking
- * the spot where the distinguished name of the user goes.
- */
- protected String roleSearch = null;
-
-
- /**
- * Should we search the entire subtree for matching memberships?
- */
- protected boolean roleSubtree = false;
-
- /**
- * Should we look for nested group in order to determine roles?
- */
- protected boolean roleNested = false;
-
-
- /**
- * An alternate URL, to which, we should connect if connectionURL fails.
- */
- protected String alternateURL;
-
- /**
- * The number of connection attempts. If greater than zero we use the
- * alternate url.
- */
- protected int connectionAttempt = 0;
-
- /**
- * Add this role to every authenticated user
- */
- protected String commonRole = null;
-
-
- /**
- * The timeout, in milliseconds, to use when trying to create a connection
- * to the directory. The default is 5000 (5 seconds).
- */
- protected String connectionTimeout = "5000";
-
-
- // ------------------------------------------------------------- Properties
-
- /**
- * Return the type of authentication to use.
- */
- public String getAuthentication() {
-
- return authentication;
-
- }
-
- /**
- * Set the type of authentication to use.
- *
- * @param authentication The authentication
- */
- public void setAuthentication(String authentication) {
-
- this.authentication = authentication;
-
- }
-
- /**
- * Return the connection username for this Realm.
- */
- public String getConnectionName() {
-
- return (this.connectionName);
-
- }
-
-
- /**
- * Set the connection username for this Realm.
- *
- * @param connectionName The new connection username
- */
- public void setConnectionName(String connectionName) {
-
- this.connectionName = connectionName;
-
- }
-
-
- /**
- * Return the connection password for this Realm.
- */
- public String getConnectionPassword() {
-
- return (this.connectionPassword);
-
- }
-
-
- /**
- * Set the connection password for this Realm.
- *
- * @param connectionPassword The new connection password
- */
- public void setConnectionPassword(String connectionPassword) {
-
- this.connectionPassword = connectionPassword;
-
- }
-
-
- /**
- * Return the connection timeout.
- */
- public String getConnectionTimeout() {
-
- return connectionTimeout;
-
- }
-
-
- /**
- * Set the connection timeout.
- *
- * @param timeout The new connection timeout
- */
- public void setConnectionTimeout(String timeout) {
-
- this.connectionTimeout = timeout;
-
- }
-
-
- /**
- * Return the connection URL for this Realm.
- */
- public String getConnectionURL() {
-
- return (this.connectionURL);
-
- }
-
-
- /**
- * Set the connection URL for this Realm.
- *
- * @param connectionURL The new connection URL
- */
- public void setConnectionURL(String connectionURL) {
-
- this.connectionURL = connectionURL;
-
- }
-
-
- /**
- * Return the JNDI context factory for this Realm.
- */
- public String getContextFactory() {
-
- return (this.contextFactory);
-
- }
-
-
- /**
- * Set the JNDI context factory for this Realm.
- *
- * @param contextFactory The new context factory
- */
- public void setContextFactory(String contextFactory) {
-
- this.contextFactory = contextFactory;
-
- }
-
- /**
- * Return the derefAliases setting to be used.
- */
- public java.lang.String getDerefAliases() {
- return derefAliases;
- }
-
- /**
- * Set the value for derefAliases to be used when searching the directory.
- *
- * @param derefAliases New value of property derefAliases.
- */
- public void setDerefAliases(java.lang.String derefAliases) {
- this.derefAliases = derefAliases;
- }
-
- /**
- * Return the protocol to be used.
- */
- public String getProtocol() {
-
- return protocol;
-
- }
-
- /**
- * Set the protocol for this Realm.
- *
- * @param protocol The new protocol.
- */
- public void setProtocol(String protocol) {
-
- this.protocol = protocol;
-
- }
-
-
- /**
- * Returns the current settings for handling PartialResultExceptions
- */
- public boolean getAdCompat () {
- return adCompat;
- }
-
-
- /**
- * How do we handle PartialResultExceptions?
- * True: ignore all PartialResultExceptions.
- */
- public void setAdCompat (boolean adCompat) {
- this.adCompat = adCompat;
- }
-
-
- /**
- * Returns the current settings for handling JNDI referrals.
- */
- public String getReferrals () {
- return referrals;
- }
-
-
- /**
- * How do we handle JNDI referrals? ignore, follow, or throw
- * (see javax.naming.Context.REFERRAL for more information).
- */
- public void setReferrals (String referrals) {
- this.referrals = referrals;
- }
-
-
- /**
- * Return the base element for user searches.
- */
- public String getUserBase() {
-
- return (this.userBase);
-
- }
-
-
- /**
- * Set the base element for user searches.
- *
- * @param userBase The new base element
- */
- public void setUserBase(String userBase) {
-
- this.userBase = userBase;
-
- }
-
-
- /**
- * Return the message format pattern for selecting users in this Realm.
- */
- public String getUserSearch() {
-
- return (this.userSearch);
-
- }
-
-
- /**
- * Set the message format pattern for selecting users in this Realm.
- *
- * @param userSearch The new user search pattern
- */
- public void setUserSearch(String userSearch) {
-
- this.userSearch = userSearch;
- if (userSearch == null)
- userSearchFormat = null;
- else
- userSearchFormat = new MessageFormat(userSearch);
-
- }
-
-
- /**
- * Return the "search subtree for users" flag.
- */
- public boolean getUserSubtree() {
-
- return (this.userSubtree);
-
- }
-
-
- /**
- * Set the "search subtree for users" flag.
- *
- * @param userSubtree The new search flag
- */
- public void setUserSubtree(boolean userSubtree) {
-
- this.userSubtree = userSubtree;
-
- }
-
-
- /**
- * Return the user role name attribute name for this Realm.
- */
- public String getUserRoleName() {
-
- return userRoleName;
- }
-
-
- /**
- * Set the user role name attribute name for this Realm.
- *
- * @param userRoleName The new userRole name attribute name
- */
- public void setUserRoleName(String userRoleName) {
-
- this.userRoleName = userRoleName;
-
- }
-
-
- /**
- * Return the base element for role searches.
- */
- public String getRoleBase() {
-
- return (this.roleBase);
-
- }
-
-
- /**
- * Set the base element for role searches.
- *
- * @param roleBase The new base element
- */
- public void setRoleBase(String roleBase) {
-
- this.roleBase = roleBase;
-
- }
-
-
- /**
- * Return the role name attribute name for this Realm.
- */
- public String getRoleName() {
-
- return (this.roleName);
-
- }
-
-
- /**
- * Set the role name attribute name for this Realm.
- *
- * @param roleName The new role name attribute name
- */
- public void setRoleName(String roleName) {
-
- this.roleName = roleName;
-
- }
-
-
- /**
- * Return the message format pattern for selecting roles in this Realm.
- */
- public String getRoleSearch() {
-
- return (this.roleSearch);
-
- }
-
-
- /**
- * Set the message format pattern for selecting roles in this Realm.
- *
- * @param roleSearch The new role search pattern
- */
- public void setRoleSearch(String roleSearch) {
-
- this.roleSearch = roleSearch;
- if (roleSearch == null)
- roleFormat = null;
- else
- roleFormat = new MessageFormat(roleSearch);
-
- }
-
-
- /**
- * Return the "search subtree for roles" flag.
- */
- public boolean getRoleSubtree() {
-
- return (this.roleSubtree);
-
- }
-
-
- /**
- * Set the "search subtree for roles" flag.
- *
- * @param roleSubtree The new search flag
- */
- public void setRoleSubtree(boolean roleSubtree) {
-
- this.roleSubtree = roleSubtree;
-
- }
-
- /**
- * Return the "The nested group search flag" flag.
- */
- public boolean getRoleNested() {
-
- return (this.roleNested);
-
- }
-
-
- /**
- * Set the "search subtree for roles" flag.
- *
- * @param roleNested The nested group search flag
- */
- public void setRoleNested(boolean roleNested) {
-
- this.roleNested = roleNested;
-
- }
-
-
-
- /**
- * Return the password attribute used to retrieve the user password.
- */
- public String getUserPassword() {
-
- return (this.userPassword);
-
- }
-
-
- /**
- * Set the password attribute used to retrieve the user password.
- *
- * @param userPassword The new password attribute
- */
- public void setUserPassword(String userPassword) {
-
- this.userPassword = userPassword;
-
- }
-
-
- /**
- * Return the message format pattern for selecting users in this Realm.
- */
- public String getUserPattern() {
-
- return (this.userPattern);
-
- }
-
-
- /**
- * Set the message format pattern for selecting users in this Realm.
- * This may be one simple pattern, or multiple patterns to be tried,
- * separated by parentheses. (for example, either "cn={0}", or
- * "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported,
- * but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is
- * also valid. Complex search strings with &, etc are NOT supported.
- *
- * @param userPattern The new user pattern
- */
- public void setUserPattern(String userPattern) {
-
- this.userPattern = userPattern;
- if (userPattern == null)
- userPatternArray = null;
- else {
- userPatternArray = parseUserPatternString(userPattern);
- int len = this.userPatternArray.length;
- userPatternFormatArray = new MessageFormat[len];
- for (int i=0; i < len; i++) {
- userPatternFormatArray[i] =
- new MessageFormat(userPatternArray[i]);
- }
- }
- }
-
-
- /**
- * Getter for property alternateURL.
- *
- * @return Value of property alternateURL.
- */
- public String getAlternateURL() {
-
- return this.alternateURL;
-
- }
-
-
- /**
- * Setter for property alternateURL.
- *
- * @param alternateURL New value of property alternateURL.
- */
- public void setAlternateURL(String alternateURL) {
-
- this.alternateURL = alternateURL;
-
- }
-
-
- /**
- * Return the common role
- */
- public String getCommonRole() {
-
- return commonRole;
-
- }
-
-
- /**
- * Set the common role
- *
- * @param commonRole The common role
- */
- public void setCommonRole(String commonRole) {
-
- this.commonRole = commonRole;
-
- }
-
-
- // ---------------------------------------------------------- Realm Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * If there are any errors with the JDBC connection, executing
- * the query or anything we return null (don't authenticate). This
- * event is also logged, and the connection will be closed so that
- * a subsequent request will automatically re-open it.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, String credentials) {
-
- DirContext context = null;
- Principal principal = null;
-
- try {
-
- // Ensure that we have a directory context available
- context = open();
-
- // Occassionally the directory context will timeout. Try one more
- // time before giving up.
- try {
-
- // Authenticate the specified username if possible
- principal = authenticate(context, username, credentials);
-
- } catch (NullPointerException e) {
- /* BZ 42449 - Kludge Sun's LDAP provider
- with broken SSL
- */
- // log the exception so we know it's there.
- containerLog.warn(sm.getString("jndiRealm.exception"), e);
-
- // close the connection so we know it will be reopened.
- if (context != null)
- close(context);
-
- // open a new directory context.
- context = open();
-
- // Try the authentication again.
- principal = authenticate(context, username, credentials);
-
- } catch (CommunicationException e) {
-
- // log the exception so we know it's there.
- containerLog.warn(sm.getString("jndiRealm.exception"), e);
-
- // close the connection so we know it will be reopened.
- if (context != null)
- close(context);
-
- // open a new directory context.
- context = open();
-
- // Try the authentication again.
- principal = authenticate(context, username, credentials);
-
- } catch (ServiceUnavailableException e) {
-
- // log the exception so we know it's there.
- containerLog.warn(sm.getString("jndiRealm.exception"), e);
-
- // close the connection so we know it will be reopened.
- if (context != null)
- close(context);
-
- // open a new directory context.
- context = open();
-
- // Try the authentication again.
- principal = authenticate(context, username, credentials);
-
- }
-
-
- // Release this context
- release(context);
-
- // Return the authenticated Principal (if any)
- return (principal);
-
- } catch (NamingException e) {
-
- // Log the problem for posterity
- containerLog.error(sm.getString("jndiRealm.exception"), e);
-
- // Close the connection so that it gets reopened next time
- if (context != null)
- close(context);
-
- // Return "not authenticated" for this request
- if (containerLog.isDebugEnabled())
- containerLog.debug("Returning null principal.");
- return (null);
-
- }
-
- }
-
-
- // -------------------------------------------------------- Package Methods
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param context The directory context
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- *
- * @exception NamingException if a directory server error occurs
- */
- public synchronized Principal authenticate(DirContext context,
- String username,
- String credentials)
- throws NamingException {
-
- if (username == null || username.equals("")
- || credentials == null || credentials.equals("")) {
- if (containerLog.isDebugEnabled())
- containerLog.debug("username null or empty: returning null principal.");
- return (null);
- }
-
- if (userPatternArray != null) {
- for (int curUserPattern = 0;
- curUserPattern < userPatternFormatArray.length;
- curUserPattern++) {
- // Retrieve user information
- User user = getUser(context, username, credentials, curUserPattern);
- if (user != null) {
- try {
- // Check the user's credentials
- if (checkCredentials(context, user, credentials)) {
- // Search for additional roles
- List<String> roles = getRoles(context, user);
- if (containerLog.isDebugEnabled()) {
- Iterator<String> it = roles.iterator();
- while (it.hasNext()) {
- containerLog.debug("Found role: " + it.next());
- }
- }
- return (new GenericPrincipal(this,
- username,
- credentials,
- roles));
- }
- } catch (InvalidNameException ine) {
- // Log the problem for posterity
- containerLog.warn(sm.getString("jndiRealm.exception"), ine);
- // ignore; this is probably due to a name not fitting
- // the search path format exactly, as in a fully-
- // qualified name being munged into a search path
- // that already contains cn= or vice-versa
- }
- }
- }
- return null;
- } else {
- // Retrieve user information
- User user = getUser(context, username, credentials);
- if (user == null)
- return (null);
-
- // Check the user's credentials
- if (!checkCredentials(context, user, credentials))
- return (null);
-
- // Search for additional roles
- List<String> roles = getRoles(context, user);
- if (containerLog.isDebugEnabled()) {
- Iterator<String> it = roles.iterator();
- while (it.hasNext()) {
- containerLog.debug("Found role: " + it.next());
- }
- }
-
- // Create and return a suitable Principal for this user
- return (new GenericPrincipal(this, username, credentials, roles));
- }
- }
-
-
- /**
- * Return a User object containing information about the user
- * with the specified username, if found in the directory;
- * otherwise return <code>null</code>.
- *
- * @param context The directory context
- * @param username Username to be looked up
- *
- * @exception NamingException if a directory server error occurs
- *
- * @see #getUser(DirContext, String, String, int)
- */
- protected User getUser(DirContext context, String username)
- throws NamingException {
-
- return getUser(context, username, null, -1);
- }
-
-
- /**
- * Return a User object containing information about the user
- * with the specified username, if found in the directory;
- * otherwise return <code>null</code>.
- *
- * @param context The directory context
- * @param username Username to be looked up
- * @param credentials User credentials (optional)
- *
- * @exception NamingException if a directory server error occurs
- *
- * @see #getUser(DirContext, String, int)
- */
- protected User getUser(DirContext context, String username, String credentials)
- throws NamingException {
-
- return getUser(context, username, credentials, -1);
- }
-
-
- /**
- * Return a User object containing information about the user
- * with the specified username, if found in the directory;
- * otherwise return <code>null</code>.
- *
- * If the <code>userPassword</code> configuration attribute is
- * specified, the value of that attribute is retrieved from the
- * user's directory entry. If the <code>userRoleName</code>
- * configuration attribute is specified, all values of that
- * attribute are retrieved from the directory entry.
- *
- * @param context The directory context
- * @param username Username to be looked up
- * @param credentials User credentials (optional)
- * @param curUserPattern Index into userPatternFormatArray
- *
- * @exception NamingException if a directory server error occurs
- */
- protected User getUser(DirContext context, String username,
- String credentials, int curUserPattern)
- throws NamingException {
-
- User user = null;
-
- // Get attributes to retrieve from user entry
- ArrayList<String> list = new ArrayList<String>();
- if (userPassword != null)
- list.add(userPassword);
- if (userRoleName != null)
- list.add(userRoleName);
- String[] attrIds = new String[list.size()];
- list.toArray(attrIds);
-
- // Use pattern or search for user entry
- if (userPatternFormatArray != null && curUserPattern >= 0) {
- user = getUserByPattern(context, username, credentials, attrIds, curUserPattern);
- } else {
- user = getUserBySearch(context, username, attrIds);
- }
-
- return user;
- }
-
-
- /**
- * Use the distinguished name to locate the directory
- * entry for the user with the specified username and
- * return a User object; otherwise return <code>null</code>.
- *
- * @param context The directory context
- * @param username The username
- * @param attrIds String[]containing names of attributes to
- * @param dn Distinguished name of the user
- * retrieve.
- *
- * @exception NamingException if a directory server error occurs
- */
- protected User getUserByPattern(DirContext context,
- String username,
- String[] attrIds,
- String dn)
- throws NamingException {
-
- // Get required attributes from user entry
- Attributes attrs = null;
- try {
- attrs = context.getAttributes(dn, attrIds);
- } catch (NameNotFoundException e) {
- return (null);
- }
- if (attrs == null)
- return (null);
-
- // Retrieve value of userPassword
- String password = null;
- if (userPassword != null)
- password = getAttributeValue(userPassword, attrs);
-
- // Retrieve values of userRoleName attribute
- ArrayList<String> roles = null;
- if (userRoleName != null)
- roles = addAttributeValues(userRoleName, attrs, roles);
-
- return new User(username, dn, password, roles);
- }
-
-
- /**
- * Use the <code>UserPattern</code> configuration attribute to
- * locate the directory entry for the user with the specified
- * username and return a User object; otherwise return
- * <code>null</code>.
- *
- * @param context The directory context
- * @param username The username
- * @param credentials User credentials (optional)
- * @param attrIds String[]containing names of attributes to
- * @param curUserPattern Index into userPatternFormatArray
- *
- * @exception NamingException if a directory server error occurs
- * @see #getUserByPattern(DirContext, String, String[], String)
- */
- protected User getUserByPattern(DirContext context,
- String username,
- String credentials,
- String[] attrIds,
- int curUserPattern)
- throws NamingException {
-
- User user = null;
-
- if (username == null || userPatternFormatArray[curUserPattern] == null)
- return (null);
-
- // Form the dn from the user pattern
- String dn = userPatternFormatArray[curUserPattern].format(new String[] { username });
-
- try {
- user = getUserByPattern(context, username, attrIds, dn);
- } catch (NameNotFoundException e) {
- return (null);
- } catch (NamingException e) {
- // If the getUserByPattern() call fails, try it again with the
- // credentials of the user that we're searching for
- try {
- // Set up security environment to bind as the user
- context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
- context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
-
- user = getUserByPattern(context, username, attrIds, dn);
- } finally {
- // Restore the original security environment
- if (connectionName != null) {
- context.addToEnvironment(Context.SECURITY_PRINCIPAL,
- connectionName);
- } else {
- context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
- }
-
- if (connectionPassword != null) {
- context.addToEnvironment(Context.SECURITY_CREDENTIALS,
- connectionPassword);
- }
- else {
- context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
- }
- }
- }
- return user;
- }
-
-
- /**
- * Search the directory to return a User object containing
- * information about the user with the specified username, if
- * found in the directory; otherwise return <code>null</code>.
- *
- * @param context The directory context
- * @param username The username
- * @param attrIds String[]containing names of attributes to retrieve.
- *
- * @exception NamingException if a directory server error occurs
- */
- protected User getUserBySearch(DirContext context,
- String username,
- String[] attrIds)
- throws NamingException {
-
- if (username == null || userSearchFormat == null)
- return (null);
-
- // Form the search filter
- String filter = userSearchFormat.format(new String[] { username });
-
- // Set up the search controls
- SearchControls constraints = new SearchControls();
-
- if (userSubtree) {
- constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
- }
- else {
- constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
- }
-
- // Specify the attributes to be retrieved
- if (attrIds == null)
- attrIds = new String[0];
- constraints.setReturningAttributes(attrIds);
-
- NamingEnumeration<SearchResult> results =
- context.search(userBase, filter, constraints);
-
-
- // Fail if no entries found
- try {
- if (results == null || !results.hasMore()) {
- return (null);
- }
- } catch (PartialResultException ex) {
- if (!adCompat)
- throw ex;
- else
- return (null);
- }
-
- // Get result for the first entry found
- SearchResult result = results.next();
-
- // Check no further entries were found
- try {
- if (results.hasMore()) {
- if(containerLog.isInfoEnabled())
- containerLog.info("username " + username + " has multiple entries");
- return (null);
- }
- } catch (PartialResultException ex) {
- if (!adCompat)
- throw ex;
- }
-
- String dn = getDistinguishedName(context, userBase, result);
-
- if (containerLog.isTraceEnabled())
- containerLog.trace(" entry found for " + username + " with dn " + dn);
-
- // Get the entry's attributes
- Attributes attrs = result.getAttributes();
- if (attrs == null)
- return null;
-
- // Retrieve value of userPassword
- String password = null;
- if (userPassword != null)
- password = getAttributeValue(userPassword, attrs);
-
- // Retrieve values of userRoleName attribute
- ArrayList<String> roles = null;
- if (userRoleName != null)
- roles = addAttributeValues(userRoleName, attrs, roles);
-
- return new User(username, dn, password, roles);
- }
-
-
- /**
- * Check whether the given User can be authenticated with the
- * given credentials. If the <code>userPassword</code>
- * configuration attribute is specified, the credentials
- * previously retrieved from the directory are compared explicitly
- * with those presented by the user. Otherwise the presented
- * credentials are checked by binding to the directory as the
- * user.
- *
- * @param context The directory context
- * @param user The User to be authenticated
- * @param credentials The credentials presented by the user
- *
- * @exception NamingException if a directory server error occurs
- */
- protected boolean checkCredentials(DirContext context,
- User user,
- String credentials)
- throws NamingException {
-
- boolean validated = false;
-
- if (userPassword == null) {
- validated = bindAsUser(context, user, credentials);
- } else {
- validated = compareCredentials(context, user, credentials);
- }
-
- if (containerLog.isTraceEnabled()) {
- if (validated) {
- containerLog.trace(sm.getString("jndiRealm.authenticateSuccess",
- user.username));
- } else {
- containerLog.trace(sm.getString("jndiRealm.authenticateFailure",
- user.username));
- }
- }
- return (validated);
- }
-
-
-
- /**
- * Check whether the credentials presented by the user match those
- * retrieved from the directory.
- *
- * @param context The directory context
- * @param info The User to be authenticated
- * @param credentials Authentication credentials
- *
- * @exception NamingException if a directory server error occurs
- */
- protected boolean compareCredentials(DirContext context,
- User info,
- String credentials)
- throws NamingException {
-
- if (info == null || credentials == null)
- return (false);
-
- String password = info.password;
- if (password == null)
- return (false);
-
- // Validate the credentials specified by the user
- if (containerLog.isTraceEnabled())
- containerLog.trace(" validating credentials");
-
- boolean validated = false;
- if (hasMessageDigest()) {
- // Some directories prefix the password with the hash type
- // The string is in a format compatible with Base64.encode not
- // the Hex encoding of the parent class.
- if (password.startsWith("{MD5}") || password.startsWith("{SHA}")) {
- /* sync since super.digest() does this same thing */
- synchronized (this) {
- password = password.substring(5);
- md.reset();
- md.update(credentials.getBytes());
- String digestedPassword =
- new String(Base64.encode(md.digest()));
- validated = password.equals(digestedPassword);
- }
- } else if (password.startsWith("{SSHA}")) {
- // Bugzilla 32938
- /* sync since super.digest() does this same thing */
- synchronized (this) {
- password = password.substring(6);
-
- md.reset();
- md.update(credentials.getBytes());
-
- // Decode stored password.
- ByteChunk pwbc = new ByteChunk(password.length());
- try {
- pwbc.append(password.getBytes(), 0, password.length());
- } catch (IOException e) {
- // Should never happen
- containerLog.error("Could not append password bytes to chunk: ", e);
- }
-
- CharChunk decoded = new CharChunk();
- Base64.decode(pwbc, decoded);
- char[] pwarray = decoded.getBuffer();
-
- // Split decoded password into hash and salt.
- final int saltpos = 20;
- byte[] hash = new byte[saltpos];
- for (int i=0; i< hash.length; i++) {
- hash[i] = (byte) pwarray[i];
- }
-
- byte[] salt = new byte[pwarray.length - saltpos];
- for (int i=0; i< salt.length; i++)
- salt[i] = (byte)pwarray[i+saltpos];
-
- md.update(salt);
- byte[] dp = md.digest();
-
- validated = Arrays.equals(dp, hash);
- } // End synchronized(this) block
- } else {
- // Hex hashes should be compared case-insensitive
- validated = (digest(credentials).equalsIgnoreCase(password));
- }
- } else
- validated = (digest(credentials).equals(password));
- return (validated);
-
- }
-
-
-
- /**
- * Check credentials by binding to the directory as the user
- *
- * @param context The directory context
- * @param user The User to be authenticated
- * @param credentials Authentication credentials
- *
- * @exception NamingException if a directory server error occurs
- */
- protected boolean bindAsUser(DirContext context,
- User user,
- String credentials)
- throws NamingException {
-
- if (credentials == null || user == null)
- return (false);
-
- String dn = user.dn;
- if (dn == null)
- return (false);
-
- // Validate the credentials specified by the user
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" validating credentials by binding as the user");
- }
-
- // Set up security environment to bind as the user
- context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
- context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
-
- // Elicit an LDAP bind operation
- boolean validated = false;
- try {
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" binding as " + dn);
- }
- context.getAttributes("", null);
- validated = true;
- }
- catch (AuthenticationException e) {
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" bind attempt failed");
- }
- }
-
- // Restore the original security environment
- if (connectionName != null) {
- context.addToEnvironment(Context.SECURITY_PRINCIPAL,
- connectionName);
- } else {
- context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
- }
-
- if (connectionPassword != null) {
- context.addToEnvironment(Context.SECURITY_CREDENTIALS,
- connectionPassword);
- }
- else {
- context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
- }
-
- return (validated);
- }
-
- /**
- * Return a List of roles associated with the given User. Any
- * roles present in the user's directory entry are supplemented by
- * a directory search. If no roles are associated with this user,
- * a zero-length List is returned.
- *
- * @param context The directory context we are searching
- * @param user The User to be checked
- *
- * @exception NamingException if a directory server error occurs
- */
- protected List<String> getRoles(DirContext context, User user)
- throws NamingException {
-
- if (user == null)
- return (null);
-
- String dn = user.dn;
- String username = user.username;
-
- if (dn == null || username == null)
- return (null);
-
- if (containerLog.isTraceEnabled())
- containerLog.trace(" getRoles(" + dn + ")");
-
- // Start with roles retrieved from the user entry
- ArrayList<String> list = user.roles;
- if (list == null) {
- list = new ArrayList<String>();
- }
- if (commonRole != null)
- list.add(commonRole);
-
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" Found " + list.size() + " user internal roles");
- for (int i=0; i<list.size(); i++)
- containerLog.trace( " Found user internal role " + list.get(i));
- }
-
- // Are we configured to do role searches?
- if ((roleFormat == null) || (roleName == null))
- return (list);
-
- // Set up parameters for an appropriate search
- String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username });
- SearchControls controls = new SearchControls();
- if (roleSubtree)
- controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
- else
- controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
- controls.setReturningAttributes(new String[] {roleName});
-
- // Perform the configured search and process the results
- NamingEnumeration<SearchResult> results =
- context.search(roleBase, filter, controls);
- if (results == null)
- return (list); // Should never happen, but just in case ...
-
- HashMap<String, String> groupMap = new HashMap<String, String>();
- try {
- while (results.hasMore()) {
- SearchResult result = results.next();
- Attributes attrs = result.getAttributes();
- if (attrs == null)
- continue;
- String dname = getDistinguishedName(context, roleBase, result);
- String name = getAttributeValue(roleName, attrs);
- if (name != null && dname != null) {
- groupMap.put(dname, name);
- }
- }
- } catch (PartialResultException ex) {
- if (!adCompat)
- throw ex;
- }
-
- Set<String> keys = groupMap.keySet();
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" Found " + keys.size() + " direct roles");
- for (String key: keys) {
- containerLog.trace( " Found direct role " + key + " -> " + groupMap.get(key));
- }
- }
-
- // if nested group search is enabled, perform searches for nested groups until no new group is found
- if (getRoleNested()) {
-
- // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in
- // Directory Groups". It avoids group slurping and handles cyclic group memberships as well.
- // See http://middleware.internet2.edu/dir/ for details
-
- Set<String> newGroupDNs = new HashSet<String>(groupMap.keySet());
- while (!newGroupDNs.isEmpty()) {
- Set<String> newThisRound = new HashSet<String>(); // Stores the groups we find in this iteration
-
- for (String groupDN : newGroupDNs) {
- filter = roleFormat.format(new String[] { groupDN });
-
- if (containerLog.isTraceEnabled()) {
- containerLog.trace("Perform a nested group search with base "+ roleBase + " and filter " + filter);
- }
-
- results = context.search(roleBase, filter, controls);
-
- try {
- while (results.hasMore()) {
- SearchResult result = results.next();
- Attributes attrs = result.getAttributes();
- if (attrs == null)
- continue;
- String dname = getDistinguishedName(context, roleBase, result);
- String name = getAttributeValue(roleName, attrs);
- if (name != null && dname != null && !groupMap.keySet().contains(dname)) {
- groupMap.put(dname, name);
- newThisRound.add(dname);
-
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" Found nested role " + dname + " -> " + name);
- }
-
- }
- }
- } catch (PartialResultException ex) {
- if (!adCompat)
- throw ex;
- }
- }
-
- newGroupDNs = newThisRound;
- }
- }
-
- return new ArrayList<String>(groupMap.values());
- }
-
-
- /**
- * Return a String representing the value of the specified attribute.
- *
- * @param attrId Attribute name
- * @param attrs Attributes containing the required value
- *
- * @exception NamingException if a directory server error occurs
- */
- private String getAttributeValue(String attrId, Attributes attrs)
- throws NamingException {
-
- if (containerLog.isTraceEnabled())
- containerLog.trace(" retrieving attribute " + attrId);
-
- if (attrId == null || attrs == null)
- return null;
-
- Attribute attr = attrs.get(attrId);
- if (attr == null)
- return (null);
- Object value = attr.get();
- if (value == null)
- return (null);
- String valueString = null;
- if (value instanceof byte[])
- valueString = new String((byte[]) value);
- else
- valueString = value.toString();
-
- return valueString;
- }
-
-
-
- /**
- * Add values of a specified attribute to a list
- *
- * @param attrId Attribute name
- * @param attrs Attributes containing the new values
- * @param values ArrayList containing values found so far
- *
- * @exception NamingException if a directory server error occurs
- */
- private ArrayList<String> addAttributeValues(String attrId,
- Attributes attrs,
- ArrayList<String> values)
- throws NamingException{
-
- if (containerLog.isTraceEnabled())
- containerLog.trace(" retrieving values for attribute " + attrId);
- if (attrId == null || attrs == null)
- return values;
- if (values == null)
- values = new ArrayList<String>();
- Attribute attr = attrs.get(attrId);
- if (attr == null)
- return (values);
- NamingEnumeration<?> e = attr.getAll();
- try {
- while(e.hasMore()) {
- String value = (String)e.next();
- values.add(value);
- }
- } catch (PartialResultException ex) {
- if (!adCompat)
- throw ex;
- }
- return values;
- }
-
-
- /**
- * Close any open connection to the directory server for this Realm.
- *
- * @param context The directory context to be closed
- */
- protected void close(DirContext context) {
-
- // Do nothing if there is no opened connection
- if (context == null)
- return;
-
- // Close our opened connection
- try {
- if (containerLog.isDebugEnabled())
- containerLog.debug("Closing directory context");
- context.close();
- } catch (NamingException e) {
- containerLog.error(sm.getString("jndiRealm.close"), e);
- }
- this.context = null;
-
- }
-
-
- /**
- * Return a short name for this Realm implementation.
- */
- protected String getName() {
-
- return (name);
-
- }
-
-
- /**
- * Return the password associated with the given principal's user name.
- */
- protected String getPassword(String username) {
-
- return (null);
-
- }
-
- /**
- * Return the Principal associated with the given user name.
- */
- protected Principal getPrincipal(String username) {
-
- DirContext context = null;
- Principal principal = null;
-
- try {
-
- // Ensure that we have a directory context available
- context = open();
-
- // Occassionally the directory context will timeout. Try one more
- // time before giving up.
- try {
-
- // Authenticate the specified username if possible
- principal = getPrincipal(context, username);
-
- } catch (CommunicationException e) {
-
- // log the exception so we know it's there.
- containerLog.warn(sm.getString("jndiRealm.exception"), e);
-
- // close the connection so we know it will be reopened.
- if (context != null)
- close(context);
-
- // open a new directory context.
- context = open();
-
- // Try the authentication again.
- principal = getPrincipal(context, username);
-
- } catch (ServiceUnavailableException e) {
-
- // log the exception so we know it's there.
- containerLog.warn(sm.getString("jndiRealm.exception"), e);
-
- // close the connection so we know it will be reopened.
- if (context != null)
- close(context);
-
- // open a new directory context.
- context = open();
-
- // Try the authentication again.
- principal = getPrincipal(context, username);
-
- }
-
-
- // Release this context
- release(context);
-
- // Return the authenticated Principal (if any)
- return (principal);
-
- } catch (NamingException e) {
-
- // Log the problem for posterity
- containerLog.error(sm.getString("jndiRealm.exception"), e);
-
- // Close the connection so that it gets reopened next time
- if (context != null)
- close(context);
-
- // Return "not authenticated" for this request
- return (null);
-
- }
-
-
- }
-
-
- /**
- * Return the Principal associated with the given user name.
- */
- protected synchronized Principal getPrincipal(DirContext context,
- String username)
- throws NamingException {
-
- User user = getUser(context, username);
-
- if (user != null) {
- return new GenericPrincipal(this, user.username, user.password ,
- getRoles(context, user));
- } else {
- return null;
- }
- }
-
- /**
- * Open (if necessary) and return a connection to the configured
- * directory server for this Realm.
- *
- * @exception NamingException if a directory server error occurs
- */
- protected DirContext open() throws NamingException {
-
- // Do nothing if there is a directory server connection already open
- if (context != null)
- return (context);
-
- try {
-
- // Ensure that we have a directory context available
- context = new InitialDirContext(getDirectoryContextEnvironment());
-
- } catch (Exception e) {
-
- connectionAttempt = 1;
-
- // log the first exception.
- containerLog.warn(sm.getString("jndiRealm.exception"), e);
-
- // Try connecting to the alternate url.
- context = new InitialDirContext(getDirectoryContextEnvironment());
-
- } finally {
-
- // reset it in case the connection times out.
- // the primary may come back.
- connectionAttempt = 0;
-
- }
-
- return (context);
-
- }
-
- /**
- * Create our directory context configuration.
- *
- * @return java.util.Hashtable the configuration for the directory context.
- */
- protected Hashtable<String,String> getDirectoryContextEnvironment() {
-
- Hashtable<String,String> env = new Hashtable<String,String>();
-
- // Configure our directory context environment.
- if (containerLog.isDebugEnabled() && connectionAttempt == 0)
- containerLog.debug("Connecting to URL " + connectionURL);
- else if (containerLog.isDebugEnabled() && connectionAttempt > 0)
- containerLog.debug("Connecting to URL " + alternateURL);
- env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
- if (connectionName != null)
- env.put(Context.SECURITY_PRINCIPAL, connectionName);
- if (connectionPassword != null)
- env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
- if (connectionURL != null && connectionAttempt == 0)
- env.put(Context.PROVIDER_URL, connectionURL);
- else if (alternateURL != null && connectionAttempt > 0)
- env.put(Context.PROVIDER_URL, alternateURL);
- if (authentication != null)
- env.put(Context.SECURITY_AUTHENTICATION, authentication);
- if (protocol != null)
- env.put(Context.SECURITY_PROTOCOL, protocol);
- if (referrals != null)
- env.put(Context.REFERRAL, referrals);
- if (derefAliases != null)
- env.put(JNDIRealm.DEREF_ALIASES, derefAliases);
- if (connectionTimeout != null)
- env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout);
-
- return env;
-
- }
-
-
- /**
- * Release our use of this connection so that it can be recycled.
- *
- * @param context The directory context to release
- */
- protected void release(DirContext context) {
-
- // NO-OP since we are not pooling anything
-
- }
-
-
- // ------------------------------------------------------ Lifecycle Methods
-
-
- /**
- * Prepare for active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents it from being started
- */
- public void start() throws LifecycleException {
-
- // Perform normal superclass initialization
- super.start();
-
- // Validate that we can open our connection
- try {
- open();
- } catch (NamingException e) {
- throw new LifecycleException(sm.getString("jndiRealm.open"), e);
- }
-
- }
-
-
- /**
- * Gracefully shut down active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
- */
- public void stop() throws LifecycleException {
-
- // Perform normal superclass finalization
- super.stop();
-
- // Close any open directory server connection
- close(this.context);
-
- }
-
- /**
- * Given a string containing LDAP patterns for user locations (separated by
- * parentheses in a pseudo-LDAP search string format -
- * "(location1)(location2)", returns an array of those paths. Real LDAP
- * search strings are supported as well (though only the "|" "OR" type).
- *
- * @param userPatternString - a string LDAP search paths surrounded by
- * parentheses
- */
- protected String[] parseUserPatternString(String userPatternString) {
-
- if (userPatternString != null) {
- ArrayList<String> pathList = new ArrayList<String>();
- int startParenLoc = userPatternString.indexOf('(');
- if (startParenLoc == -1) {
- // no parens here; return whole thing
- return new String[] {userPatternString};
- }
- int startingPoint = 0;
- while (startParenLoc > -1) {
- int endParenLoc = 0;
- // weed out escaped open parens and parens enclosing the
- // whole statement (in the case of valid LDAP search
- // strings: (|(something)(somethingelse))
- while ( (userPatternString.charAt(startParenLoc + 1) == '|') ||
- (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\') ) {
- startParenLoc = userPatternString.indexOf("(", startParenLoc+1);
- }
- endParenLoc = userPatternString.indexOf(")", startParenLoc+1);
- // weed out escaped end-parens
- while (userPatternString.charAt(endParenLoc - 1) == '\\') {
- endParenLoc = userPatternString.indexOf(")", endParenLoc+1);
- }
- String nextPathPart = userPatternString.substring
- (startParenLoc+1, endParenLoc);
- pathList.add(nextPathPart);
- startingPoint = endParenLoc+1;
- startParenLoc = userPatternString.indexOf('(', startingPoint);
- }
- return pathList.toArray(new String[] {});
- }
- return null;
-
- }
-
-
- /**
- * Given an LDAP search string, returns the string with certain characters
- * escaped according to RFC 2254 guidelines.
- * The character mapping is as follows:
- * char -> Replacement
- * ---------------------------
- * * -> \2a
- * ( -> \28
- * ) -> \29
- * \ -> \5c
- * \0 -> \00
- * @param inString string to escape according to RFC 2254 guidelines
- * @return String the escaped/encoded result
- */
- protected String doRFC2254Encoding(String inString) {
- StringBuilder buf = new StringBuilder(inString.length());
- for (int i = 0; i < inString.length(); i++) {
- char c = inString.charAt(i);
- switch (c) {
- case '\\':
- buf.append("\\5c");
- break;
- case '*':
- buf.append("\\2a");
- break;
- case '(':
- buf.append("\\28");
- break;
- case ')':
- buf.append("\\29");
- break;
- case '\0':
- buf.append("\\00");
- break;
- default:
- buf.append(c);
- break;
- }
- }
- return buf.toString();
- }
-
-
- /**
- * Returns the distinguished name of a search result.
- *
- * @param context Our DirContext
- * @param base The base DN
- * @param result The search result
- * @return String containing the distinguished name
- */
- protected String getDistinguishedName(DirContext context, String base,
- SearchResult result) throws NamingException {
- // Get the entry's distinguished name. For relative results, this means
- // we need to composite a name with the base name, the context name, and
- // the result name. For non-relative names, use the returned name.
- if (result.isRelative()) {
- if (containerLog.isTraceEnabled()) {
- containerLog.trace(" search returned relative name: " +
- result.getName());
- }
- NameParser parser = context.getNameParser("");
- Name contextName = parser.parse(context.getNameInNamespace());
- Name baseName = parser.parse(base);
-
- // Bugzilla 32269
- Name entryName =
- parser.parse(new CompositeName(result.getName()).get(0));
-
- Name name = contextName.addAll(baseName);
- name = name.addAll(entryName);
- return name.toString();
- } else {
- String absoluteName = result.getName();
- if (containerLog.isTraceEnabled())
- containerLog.trace(" search returned absolute name: " +
- result.getName());
- try {
- // Normalize the name by running it through the name parser.
- NameParser parser = context.getNameParser("");
- URI userNameUri = new URI(absoluteName);
- String pathComponent = userNameUri.getPath();
- // Should not ever have an empty path component, since that is /{DN}
- if (pathComponent.length() < 1 ) {
- throw new InvalidNameException(
- "Search returned unparseable absolute name: " +
- absoluteName );
- }
- Name name = parser.parse(pathComponent.substring(1));
- return name.toString();
- } catch ( URISyntaxException e ) {
- throw new InvalidNameException(
- "Search returned unparseable absolute name: " +
- absoluteName );
- }
- }
- }
-
-
- /**
- * A private class representing a User
- */
- protected static class User {
-
- private String username = null;
- private String dn = null;
- private String password = null;
- private ArrayList<String> roles = null;
-
- User(String username, String dn, String password,
- ArrayList<String> roles) {
- this.username = username;
- this.dn = dn;
- this.password = password;
- this.roles = roles;
- }
-
- public String getUserName() {
- return username;
- }
-
- public String getDN() {
- return dn;
- }
-
- public String getPassword() {
- return password;
- }
-
- public List<String> getRoles() {
- return Collections.unmodifiableList(roles);
- }
- }
-}
Deleted: trunk/java/org/apache/catalina/realm/LockOutRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/LockOutRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/LockOutRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,414 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-import java.security.Principal;
-import java.security.cert.X509Certificate;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.catalina.LifecycleException;
-import org.jboss.logging.Logger;
-
-/**
- * This class extends the CombinedRealm (hence it can wrap other Realms) to
- * provide a user lock out mechanism if there are too many failed
- * authentication attempts in a given period of time. To ensure correct
- * operation, there is a reasonable degree of synchronisation in this Realm.
- * This Realm does not require modification to the underlying Realms or the
- * associated user storage mecahisms. It achieves this by recording all failed
- * logins, including those for users that do not exist. To prevent a DOS by
- * deliberating making requests with invalid users (and hence causing this cache
- * to grow) the size of the list of users that have failed authentication is
- * limited.
- */
-public class LockOutRealm extends CombinedRealm {
-
- private static Logger log = Logger.getLogger(LockOutRealm.class);
-
- /**
- * The number of times in a row a user has to fail authentication to be
- * locked out. Defaults to 5.
- */
- protected int failureCount = 5;
-
- /**
- * The time (in seconds) a user is locked out for after too many
- * authentication failures. Defaults to 300 (5 minutes).
- */
- protected int lockOutTime = 300;
-
- /**
- * Number of users that have failed authentication to keep in cache. Over
- * time the cache will grow to this size and may not shrink. Defaults to
- * 1000.
- */
- protected int cacheSize = 1000;
-
- /**
- * If a failed user is removed from the cache because the cache is too big
- * before it has been in the cache for at least this period of time (in
- * seconds) a warning message will be logged. Defaults to 3600 (1 hour).
- */
- protected int cacheRemovalWarningTime = 3600;
-
- /**
- * Users whose last authentication attempt failed. Entries will be ordered
- * in access order from least recent to most recent.
- */
- protected Map<String,LockRecord> failedUsers = null;
-
-
- /**
- * Prepare for the beginning of active use of the public methods of this
- * component. This method should be called before any of the public
- * methods of this component are utilized. It should also send a
- * LifecycleEvent of type START_EVENT to any registered listeners.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
- */
- public void start() throws LifecycleException {
- // Configure the list of failed users to delete the oldest entry once it
- // exceeds the specified size
- failedUsers = new LinkedHashMap<String, LockRecord>(cacheSize, 0.75f,
- true) {
- protected boolean removeEldestEntry(
- Map.Entry<String, LockRecord> eldest) {
- if (size() > cacheSize) {
- // Check to see if this element has been removed too quickly
- long timeInCache = (System.currentTimeMillis() -
- eldest.getValue().getLastFailureTime())/1000;
-
- if (timeInCache < cacheRemovalWarningTime) {
- log.warn(sm.getString("lockOutRealm.removeWarning",
- eldest.getKey(), Long.valueOf(timeInCache)));
- }
- return true;
- }
- return false;
- }
- };
-
- super.start();
- }
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, byte[] credentials) {
- if (isLocked(username)) {
- // Trying to authenticate a locked user is an automatic failure
- registerAuthFailure(username);
-
- log.warn(sm.getString("lockOutRealm.authLockedUser", username));
- return null;
- }
-
- Principal authenticatedUser = super.authenticate(username, credentials);
-
- if (authenticatedUser == null) {
- registerAuthFailure(username);
- } else {
- registerAuthSuccess(username);
- }
- return authenticatedUser;
- }
-
-
- /**
- * Return the Principal associated with the specified username, which
- * matches the digest calculated using the given parameters using the
- * method described in RFC 2069; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param clientDigest Digest which has been submitted by the client
- * @param nOnce Unique (or supposedly unique) token which has been used
- * for this request
- * @param realm Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest :
- * MD5(Method + ":" + uri)
- */
- public Principal authenticate(String username, String clientDigest,
- String once, String nc, String cnonce, String qop,
- String realmName, String md5a2) {
-
- if (isLocked(username)) {
- // Trying to authenticate a locked user is an automatic failure
- registerAuthFailure(username);
-
- log.warn(sm.getString("lockOutRealm.authLockedUser", username));
- return null;
- }
-
- Principal authenticatedUser = super.authenticate(username, clientDigest,
- once, nc, cnonce, qop, realmName, md5a2);
-
- if (authenticatedUser == null) {
- registerAuthFailure(username);
- } else {
- registerAuthSuccess(username);
- }
- return authenticatedUser;
- }
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, String credentials) {
- if (isLocked(username)) {
- // Trying to authenticate a locked user is an automatic failure
- registerAuthFailure(username);
-
- log.warn(sm.getString("lockOutRealm.authLockedUser", username));
- return null;
- }
-
- Principal authenticatedUser = super.authenticate(username, credentials);
-
- if (authenticatedUser == null) {
- registerAuthFailure(username);
- } else {
- registerAuthSuccess(username);
- }
- return authenticatedUser;
- }
-
-
- /**
- * Return the Principal associated with the specified chain of X509
- * client certificates. If there is none, return <code>null</code>.
- *
- * @param certs Array of client certificates, with the first one in
- * the array being the certificate of the client itself.
- */
- public Principal authenticate(X509Certificate[] certs) {
- String username = null;
- if (certs != null && certs.length >0) {
- username = certs[0].getSubjectDN().getName();
- }
-
- if (isLocked(username)) {
- // Trying to authenticate a locked user is an automatic failure
- registerAuthFailure(username);
-
- log.warn(sm.getString("lockOutRealm.authLockedUser", username));
- return null;
- }
-
- Principal authenticatedUser = super.authenticate(certs);
-
- if (authenticatedUser == null) {
- registerAuthFailure(username);
- } else {
- registerAuthSuccess(username);
- }
- return authenticatedUser;
- }
-
-
- /**
- * Unlock the specified username. This will remove all records of
- * authentication failures for this user.
- *
- * @param username The user to unlock
- */
- public void unlock(String username) {
- // Auth success clears the lock record so...
- registerAuthSuccess(username);
- }
-
- /*
- * Checks to see if the current user is locked. If this is associated with
- * a login attempt, then the last access time will be recorded and any
- * attempt to authenticated a locked user will log a warning.
- */
- private boolean isLocked(String username) {
- LockRecord lockRecord = null;
- synchronized (this) {
- lockRecord = failedUsers.get(username);
- }
-
- // No lock record means user can't be locked
- if (lockRecord == null) {
- return false;
- }
-
- // Check to see if user is locked
- if (lockRecord.getFailures() >= failureCount &&
- (System.currentTimeMillis() -
- lockRecord.getLastFailureTime())/1000 < lockOutTime) {
- return true;
- }
-
- // User has not, yet, exceeded lock thresholds
- return false;
- }
-
-
- /*
- * After successful authentication, any record of previous authentication
- * failure is removed.
- */
- private synchronized void registerAuthSuccess(String username) {
- // Successful authentication means removal from the list of failed users
- failedUsers.remove(username);
- }
-
-
- /*
- * After a failed authentication, add the record of the failed
- * authentication.
- */
- private void registerAuthFailure(String username) {
- LockRecord lockRecord = null;
- synchronized (this) {
- if (!failedUsers.containsKey(username)) {
- lockRecord = new LockRecord();
- failedUsers.put(username, lockRecord);
- } else {
- lockRecord = failedUsers.get(username);
- if (lockRecord.getFailures() >= failureCount &&
- ((System.currentTimeMillis() -
- lockRecord.getLastFailureTime())/1000)
- > lockOutTime) {
- // User was previously locked out but lockout has now
- // expired so reset failure count
- lockRecord.setFailures(0);
- }
- }
- }
- lockRecord.registerFailure();
- }
-
-
- /**
- * Get the number of failed authentication attempts required to lock the
- * user account.
- * @return the failureCount
- */
- public int getFailureCount() {
- return failureCount;
- }
-
-
- /**
- * Set the number of failed authentication attempts required to lock the
- * user account.
- * @param failureCount the failureCount to set
- */
- public void setFailureCount(int failureCount) {
- this.failureCount = failureCount;
- }
-
-
- /**
- * Get the period for which an account will be locked.
- * @return the lockOutTime
- */
- public int getLockOutTime() {
- return lockOutTime;
- }
-
-
- /**
- * Set the period for which an account will be locked.
- * @param lockOutTime the lockOutTime to set
- */
- public void setLockOutTime(int lockOutTime) {
- this.lockOutTime = lockOutTime;
- }
-
-
- /**
- * Get the maximum number of users for which authentication failure will be
- * kept in the cache.
- * @return the cacheSize
- */
- public int getCacheSize() {
- return cacheSize;
- }
-
-
- /**
- * Set the maximum number of users for which authentication failure will be
- * kept in the cache.
- * @param cacheSize the cacheSize to set
- */
- public void setCacheSize(int cacheSize) {
- this.cacheSize = cacheSize;
- }
-
-
- /**
- * Get the minimum period a failed authentication must remain in the cache
- * to avoid generating a warning if it is removed from the cache to make
- * space for a new entry.
- * @return the cacheRemovalWarningTime
- */
- public int getCacheRemovalWarningTime() {
- return cacheRemovalWarningTime;
- }
-
-
- /**
- * Set the minimum period a failed authentication must remain in the cache
- * to avoid generating a warning if it is removed from the cache to make
- * space for a new entry.
- * @param cacheRemovalWarningTime the cacheRemovalWarningTime to set
- */
- public void setCacheRemovalWarningTime(int cacheRemovalWarningTime) {
- this.cacheRemovalWarningTime = cacheRemovalWarningTime;
- }
-
-
- protected class LockRecord {
- private AtomicInteger failures = new AtomicInteger(0);
- private long lastFailureTime = 0;
-
- public int getFailures() {
- return failures.get();
- }
-
- public void setFailures(int theFailures) {
- failures.set(theFailures);
- }
-
- public long getLastFailureTime() {
- return lastFailureTime;
- }
-
- public void registerFailure() {
- failures.incrementAndGet();
- lastFailureTime = System.currentTimeMillis();
- }
- }
-}
Deleted: trunk/java/org/apache/catalina/realm/MemoryRealm.java
===================================================================
--- trunk/java/org/apache/catalina/realm/MemoryRealm.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/MemoryRealm.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,336 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import java.security.Principal;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.util.StringManager;
-import org.apache.tomcat.util.digester.Digester;
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-
-
-/**
- * Simple implementation of <b>Realm</b> that reads an XML file to configure
- * the valid users, passwords, and roles. The file format (and default file
- * location) are identical to those currently supported by Tomcat 3.X.
- * <p>
- * <strong>IMPLEMENTATION NOTE</strong>: It is assumed that the in-memory
- * collection representing our defined users (and their roles) is initialized
- * at application startup and never modified again. Therefore, no thread
- * synchronization is performed around accesses to the principals collection.
- *
- * @author Craig R. McClanahan
- * @version $Revision$ $Date$
- */
-
-public class MemoryRealm extends RealmBase {
-
- private static Logger log = Logger.getLogger(MemoryRealm.class);
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The Digester we will use to process in-memory database files.
- */
- private static Digester digester = null;
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
- protected final String info =
- "org.apache.catalina.realm.MemoryRealm/1.0";
-
-
- /**
- * Descriptive information about this Realm implementation.
- */
-
- protected static final String name = "MemoryRealm";
-
-
- /**
- * The pathname (absolute or relative to Catalina's current working
- * directory) of the XML file containing our database information.
- */
- private String pathname = "conf/tomcat-users.xml";
-
-
- /**
- * The set of valid Principals for this Realm, keyed by user name.
- */
- private Map principals = new HashMap();
-
-
- /**
- * The string manager for this package.
- */
- private static StringManager sm =
- StringManager.getManager(Constants.Package);
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return descriptive information about this Realm implementation and
- * the corresponding version number, in the format
- * <code><description>/<version></code>.
- */
- public String getInfo() {
-
- return info;
-
- }
-
-
- /**
- * Return the pathname of our XML file containing user definitions.
- */
- public String getPathname() {
-
- return pathname;
-
- }
-
-
- /**
- * Set the pathname of our XML file containing user definitions. If a
- * relative pathname is specified, it is resolved against "catalina.base".
- *
- * @param pathname The new pathname
- */
- public void setPathname(String pathname) {
-
- this.pathname = pathname;
-
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
- *
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
- */
- public Principal authenticate(String username, String credentials) {
-
- GenericPrincipal principal =
- (GenericPrincipal) principals.get(username);
-
- boolean validated = false;
- if (principal != null && credentials != null) {
- if (hasMessageDigest()) {
- // Hex hashes should be compared case-insensitive
- validated = (digest(credentials)
- .equalsIgnoreCase(principal.getPassword()));
- } else {
- validated =
- (digest(credentials).equals(principal.getPassword()));
- }
- }
-
- if (validated) {
- if (log.isDebugEnabled())
- log.debug(sm.getString("memoryRealm.authenticateSuccess", username));
- return (principal);
- } else {
- if (log.isDebugEnabled())
- log.debug(sm.getString("memoryRealm.authenticateFailure", username));
- return (null);
- }
-
- }
-
-
- // -------------------------------------------------------- Package Methods
-
-
- /**
- * Add a new user to the in-memory database.
- *
- * @param username User's username
- * @param password User's password (clear text)
- * @param roles Comma-delimited set of roles associated with this user
- */
- void addUser(String username, String password, String roles) {
-
- // Accumulate the list of roles for this user
- ArrayList list = new ArrayList();
- roles += ",";
- while (true) {
- int comma = roles.indexOf(',');
- if (comma < 0)
- break;
- String role = roles.substring(0, comma).trim();
- list.add(role);
- roles = roles.substring(comma + 1);
- }
-
- // Construct and cache the Principal for this user
- GenericPrincipal principal =
- new GenericPrincipal(this, username, password, list);
- principals.put(username, principal);
-
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Return a configured <code>Digester</code> to use for processing
- * the XML input file, creating a new one if necessary.
- */
- protected synchronized Digester getDigester() {
-
- if (digester == null) {
- digester = new Digester();
- digester.setValidating(false);
- try {
- digester.setFeature(
- "http://apache.org/xml/features/allow-java-encodings",
- true);
- } catch (Exception e) {
- log.warn(sm.getString("memoryRealm.xmlFeatureEncoding"), e);
- }
- digester.addRuleSet(new MemoryRuleSet());
- }
- return (digester);
-
- }
-
-
- /**
- * Return a short name for this Realm implementation.
- */
- protected String getName() {
-
- return (name);
-
- }
-
-
- /**
- * Return the password associated with the given principal's user name.
- */
- protected String getPassword(String username) {
-
- GenericPrincipal principal =
- (GenericPrincipal) principals.get(username);
- if (principal != null) {
- return (principal.getPassword());
- } else {
- return (null);
- }
-
- }
-
-
- /**
- * Return the Principal associated with the given user name.
- */
- protected Principal getPrincipal(String username) {
-
- return (Principal) principals.get(username);
-
- }
-
- /**
- * Returns the principals for this realm.
- *
- * @return The principals, keyed by user name (a String)
- */
- protected Map getPrincipals() {
- return principals;
- }
-
-
- // ------------------------------------------------------ Lifecycle Methods
-
-
- /**
- * Prepare for active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that prevents it from being started
- */
- public synchronized void start() throws LifecycleException {
-
- // Perform normal superclass initialization
- super.start();
-
- // Validate the existence of our database file
- File file = new File(pathname);
- if (!file.isAbsolute())
- file = new File(System.getProperty("catalina.base"), pathname);
- if (!file.exists() || !file.canRead())
- throw new LifecycleException
- (sm.getString("memoryRealm.loadExist",
- file.getAbsolutePath()));
-
- // Load the contents of the database file
- if (log.isDebugEnabled())
- log.debug(sm.getString("memoryRealm.loadPath",
- file.getAbsolutePath()));
- Digester digester = getDigester();
- try {
- synchronized (digester) {
- digester.push(this);
- digester.parse(file);
- }
- } catch (Exception e) {
- throw new LifecycleException
- (sm.getString("memoryRealm.readXml"), e);
- } finally {
- digester.reset();
- }
-
- }
-
-
- /**
- * Gracefully shut down active use of the public methods of this Component.
- *
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
- */
- public synchronized void stop() throws LifecycleException {
-
- // Perform normal superclass finalization
- super.stop();
-
- // No shutdown activities required
-
- }
-
-
-}
Deleted: trunk/java/org/apache/catalina/realm/MemoryRuleSet.java
===================================================================
--- trunk/java/org/apache/catalina/realm/MemoryRuleSet.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/MemoryRuleSet.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,135 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.realm;
-
-
-import org.apache.tomcat.util.digester.Digester;
-import org.apache.tomcat.util.digester.Rule;
-import org.apache.tomcat.util.digester.RuleSetBase;
-import org.xml.sax.Attributes;
-
-
-/**
- * <p><strong>RuleSet</strong> for recognizing the users defined in the
- * XML file processed by <code>MemoryRealm</code>.</p>
- *
- * @author Craig R. McClanahan
- * @version $Revision$ $Date$
- */
-
-public class MemoryRuleSet extends RuleSetBase {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The matching pattern prefix to use for recognizing our elements.
- */
- protected String prefix = null;
-
-
- // ------------------------------------------------------------ Constructor
-
-
- /**
- * Construct an instance of this <code>RuleSet</code> with the default
- * matching pattern prefix.
- */
- public MemoryRuleSet() {
-
- this("tomcat-users/");
-
- }
-
-
- /**
- * Construct an instance of this <code>RuleSet</code> with the specified
- * matching pattern prefix.
- *
- * @param prefix Prefix for matching pattern rules (including the
- * trailing slash character)
- */
- public MemoryRuleSet(String prefix) {
-
- super();
- this.namespaceURI = null;
- this.prefix = prefix;
-
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * <p>Add the set of Rule instances defined in this RuleSet to the
- * specified <code>Digester</code> instance, associating them with
- * our namespace URI (if any). This method should only be called
- * by a Digester instance.</p>
- *
- * @param digester Digester instance to which the new Rule instances
- * should be added.
- */
- public void addRuleInstances(Digester digester) {
-
- digester.addRule(prefix + "user", new MemoryUserRule());
-
- }
-
-
-}
-
-
-/**
- * Private class used when parsing the XML database file.
- */
-final class MemoryUserRule extends Rule {
-
-
- /**
- * Construct a new instance of this <code>Rule</code>.
- */
- public MemoryUserRule() {
- }
-
-
- /**
- * Process a <code><user></code> element from the XML database file.
- *
- * @param attributes The attribute list for this element
- */
- public void begin(String namespace, String name, Attributes attributes)
- throws Exception {
-
- String username = attributes.getValue("name");
- if (username == null) {
- username = attributes.getValue("username");
- }
- String password = attributes.getValue("password");
- String roles = attributes.getValue("roles");
-
- MemoryRealm realm =
- (MemoryRealm) digester.peek(digester.getCount() - 1);
- realm.addUser(username, password, roles);
-
- }
-
-
-}
Deleted: trunk/java/org/apache/catalina/realm/mbeans-descriptors.xml
===================================================================
--- trunk/java/org/apache/catalina/realm/mbeans-descriptors.xml 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/realm/mbeans-descriptors.xml 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,385 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You 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.
--->
-<mbeans-descriptors>
-
- <mbean name="DataSourceRealm"
- className="org.apache.catalina.mbeans.ClassNameMBean"
- description="Implementation of Realm that works with any JNDI configured DataSource"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.DataSourceRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="dataSourceName"
- description="The JNDI named JDBC DataSource for your database"
- type="java.lang.String"/>
-
- <attribute name="digest"
- description="Digest algorithm used in storing passwords in a non-plaintext format"
- type="java.lang.String"/>
-
- <attribute name="localDataSource"
- description="Configures if the DataSource is local to the webapp"
- type="boolean"/>
-
- <attribute name="roleNameCol"
- description="The column in the user role table that names a role"
- type="java.lang.String"/>
-
- <attribute name="userCredCol"
- description="The column in the user table that holds the user's credentials"
- type="java.lang.String"/>
-
- <attribute name="userNameCol"
- description="The column in the user table that holds the user's username"
- type="java.lang.String"/>
-
- <attribute name="userRoleTable"
- description="The table that holds the relation between user's and roles"
- type="java.lang.String"/>
-
- <attribute name="userTable"
- description="The table that holds user data"
- type="java.lang.String"/>
-
-
- <operation name="start" description="Start" impact="ACTION" returnType="void" />
- <operation name="stop" description="Stop" impact="ACTION" returnType="void" />
- <operation name="init" description="Init" impact="ACTION" returnType="void" />
- <operation name="destroy" description="Destroy" impact="ACTION" returnType="void" />
-
- </mbean>
-
- <mbean name="JAASRealm"
- description="Implmentation of Realm that authenticates users via the Java Authentication and Authorization Service (JAAS)"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.JAASRealm">
-
- <attribute name="appName"
- description="The application name passed to the JAAS LoginContext, which uses it to select the set of relevant LoginModules"
- type="java.lang.String"/>
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="digest"
- description="Digest algorithm used in storing passwords in a non-plaintext format"
- type="java.lang.String"/>
-
- <attribute name="roleClassNames"
- description="Comma-delimited list of javax.security.Principal classes that represent security roles"
- type="java.lang.String"/>
-
- <attribute name="userClassNames"
- description="Comma-delimited list of javax.security.Principal classes that represent individual users"
- type="java.lang.String"/>
-
- <attribute name="validate"
- description="Should we validate client certificate chains when they are presented?"
- type="java.lang.String"/>
-
-
- <operation name="start" description="Start" impact="ACTION" returnType="void" />
- <operation name="stop" description="Stop" impact="ACTION" returnType="void" />
- <operation name="init" description="Init" impact="ACTION" returnType="void" />
- <operation name="destroy" description="Destroy" impact="ACTION" returnType="void" />
- </mbean>
-
-
- <mbean name="JDBCRealm"
- description="Implementation of Realm that works with any JDBC supported database"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.JDBCRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="connectionName"
- description="The connection username to use when trying to connect to the database"
- type="java.lang.String"/>
-
- <attribute name="connectionPassword"
- description="The connection URL to use when trying to connect to the database"
- type="java.lang.String"/>
-
- <attribute name="connectionURL"
- description="The connection URL to use when trying to connect to the database"
- type="java.lang.String"/>
-
- <attribute name="digest"
- description="Digest algorithm used in storing passwords in a non-plaintext format"
- type="java.lang.String"/>
-
- <attribute name="driverName"
- description="The JDBC driver to use"
- type="java.lang.String"/>
-
- <attribute name="roleNameCol"
- description="The column in the user role table that names a role"
- type="java.lang.String"/>
-
- <attribute name="userCredCol"
- description="The column in the user table that holds the user's credentials"
- type="java.lang.String"/>
-
- <attribute name="userNameCol"
- description="The column in the user table that holds the user's username"
- type="java.lang.String"/>
-
- <attribute name="userRoleTable"
- description="The table that holds the relation between user's and roles"
- type="java.lang.String"/>
-
- <attribute name="userTable"
- description="The table that holds user data"
- type="java.lang.String"/>
-
-
- <operation name="start" description="Start" impact="ACTION" returnType="void" />
- <operation name="stop" description="Stop" impact="ACTION" returnType="void" />
- <operation name="init" description="Init" impact="ACTION" returnType="void" />
- <operation name="destroy" description="Destroy" impact="ACTION" returnType="void" />
- </mbean>
-
- <mbean name="JNDIRealm"
- description="Implementation of Realm that works with a directory server accessed via the Java Naming and Directory Interface (JNDI) APIs"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.JNDIRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="connectionName"
- description="The connection username for the server we will contact"
- type="java.lang.String"/>
-
- <attribute name="connectionPassword"
- description="The connection password for the server we will contact"
- type="java.lang.String"/>
-
- <attribute name="connectionURL"
- description="The connection URL for the server we will contact"
- type="java.lang.String"/>
-
- <attribute name="contextFactory"
- description="The JNDI context factory for this Realm"
- type="java.lang.String"/>
-
- <attribute name="digest"
- description="Digest algorithm used in storing passwords in a non-plaintext format"
- type="java.lang.String"/>
-
- <attribute name="roleBase"
- description="The base element for role searches"
- type="java.lang.String"/>
-
- <attribute name="roleName"
- description="The name of the attribute containing roles held elsewhere"
- type="java.lang.String"/>
-
- <attribute name="roleSearch"
- description="The message format used to select roles for a user"
- type="java.lang.String"/>
-
- <attribute name="roleSubtree"
- description="Should we search the entire subtree for matching memberships?"
- type="boolean"/>
-
- <attribute name="userBase"
- description="The base element for user searches"
- type="java.lang.String"/>
-
- <attribute name="userPassword"
- description="The attribute name used to retrieve the user password"
- type="java.lang.String"/>
-
- <attribute name="userPattern"
- description="The message format used to select a user"
- type="java.lang.String"/>
-
- <attribute name="userRoleName"
- description="The name of the attribute in the user's entry containing roles for that user"
- type="java.lang.String"/>
-
- <attribute name="userSearch"
- description="The message format used to search for a user"
- type="java.lang.String"/>
-
- <attribute name="userSubtree"
- description="Should we search the entire subtree for matching users?"
- type="boolean"/>
-
-
- <operation name="start" description="Start" impact="ACTION" returnType="void" />
- <operation name="stop" description="Stop" impact="ACTION" returnType="void" />
- <operation name="init" description="Init" impact="ACTION" returnType="void" />
- <operation name="destroy" description="Destroy" impact="ACTION" returnType="void" />
- </mbean>
-
- <mbean name="MemoryRealm"
- description="Simple implementation of Realm that reads an XML file to configure the valid users, passwords, and roles"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.MemoryRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="pathname"
- description="The pathname of the XML file containing our database information"
- type="java.lang.String"/>
-
- <operation name="start" description="Start" impact="ACTION" returnType="void" />
- <operation name="stop" description="Stop" impact="ACTION" returnType="void" />
- <operation name="init" description="Init" impact="ACTION" returnType="void" />
- <operation name="destroy" description="Destroy" impact="ACTION" returnType="void" />
-
- </mbean>
-
- <mbean name="UserDatabaseRealm"
- description="Realm connected to a UserDatabase as a global JNDI resource"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.UserDatabaseRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="resourceName"
- description="The global JNDI name of the UserDatabase resource to use"
- type="java.lang.String"/>
-
- </mbean>
-
- <mbean name="CombinedRealm"
- description="Realm implementation that can be used to chain multiple realms"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.CombinedRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="realms"
- description="The set of realms that the combined realm is wrapping"
- type="[Ljavax.management.ObjectName;"
- writeable="false"/>
-
- <operation name="addRealm"
- description="Add a new Realm to the set of Realms wrapped by this realm"
- impact="ACTION"
- returnType="void">
- <parameter name="theRealm"
- description="New Realm to add"
- type="org.apache.catalina.Realm"/>
- </operation>
-
- <operation name="start"
- description="Start"
- impact="ACTION"
- returnType="void" />
-
- <operation name="stop"
- description="Stop"
- impact="ACTION"
- returnType="void" />
-
- </mbean>
-
- <mbean name="LockOutRealm"
- description="Realm implementation that can be used to wrap existing realms to provide a user lock-out capability"
- domain="Catalina"
- group="Realm"
- type="org.apache.catalina.realm.LockOutRealm">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="realms"
- description="The set of realms that the lockout realm is wrapping"
- type="[Ljavax.management.ObjectName;"
- writeable="false"/>
-
- <attribute name="cacheRemovalWarningTime"
- description="If a failed user is removed from the cache because the cache is too big before it has been in the cache for at least this period of time (in seconds) a warning message will be logged. Defaults to 3600 (1 hour)."
- type="int" />
-
- <attribute name="cacheSize"
- description="Number of users that have failed authentication to keep in cache. Over time the cache will grow to this size and may not shrink. Defaults to 1000."
- type="int" />
-
- <attribute name="failureCount"
- description="The number of times in a row a user has to fail authentication to be locked out. Defaults to 5."
- type="int" />
-
- <attribute name="lockOutTime"
- description="The time (in seconds) a user is locked out for after too many authentication failures. Defaults to 300 (5 minutes)."
- type="int" />
-
- <operation name="addRealm"
- description="Add a new Realm to the set of Realms wrapped by this realm"
- impact="ACTION"
- returnType="void">
- <parameter name="theRealm"
- description="New Realm to add"
- type="org.apache.catalina.Realm"/>
- </operation>
-
- <operation name="unlock"
- description="Unlock the specified user"
- impact="ACTION"
- returnType="void">
- <parameter name="username"
- description="User to unlock"
- type="java.lang.String"/>
- </operation>
-
- <operation name="start"
- description="Start"
- impact="ACTION"
- returnType="void" />
-
- <operation name="stop"
- description="Stop"
- impact="ACTION"
- returnType="void" />
-
- </mbean>
-
-</mbeans-descriptors>
Modified: trunk/java/org/apache/catalina/startup/Catalina.java
===================================================================
--- trunk/java/org/apache/catalina/startup/Catalina.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/startup/Catalina.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -24,12 +24,9 @@
import java.io.OutputStream;
import java.net.Socket;
-import org.apache.catalina.Container;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
-import org.apache.tomcat.util.digester.Rule;
-import org.xml.sax.Attributes;
/**
@@ -437,36 +434,3 @@
org.jboss.logging.Logger.getLogger( Catalina.class );
}
-
-
-// ------------------------------------------------------------ Private Classes
-
-
-/**
- * Rule that sets the parent class loader for the top object on the stack,
- * which must be a <code>Container</code>.
- */
-
-final class SetParentClassLoaderRule extends Rule {
-
- public SetParentClassLoaderRule(ClassLoader parentClassLoader) {
-
- this.parentClassLoader = parentClassLoader;
-
- }
-
- ClassLoader parentClassLoader = null;
-
- public void begin(String namespace, String name, Attributes attributes)
- throws Exception {
-
- if (digester.getLogger().isDebugEnabled())
- digester.getLogger().debug("Setting parent class loader");
-
- Container top = (Container) digester.peek();
- top.setParentClassLoader(parentClassLoader);
-
- }
-
-
-}
Deleted: trunk/java/org/apache/catalina/util/SchemaResolver.java
===================================================================
--- trunk/java/org/apache/catalina/util/SchemaResolver.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/catalina/util/SchemaResolver.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,134 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.util.HashMap;
-
-import org.apache.tomcat.util.digester.Digester;
-import org.xml.sax.InputSource;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.SAXException;
-
-/**
- * This class implements a local SAX's <code>EntityResolver</code>. All
- * DTDs and schemas used to validate the web.xml file will re-directed
- * to a local file stored in the servlet-api.jar and jsp-api.jar.
- *
- * @author Jean-Francois Arcand
- */
-public class SchemaResolver implements EntityResolver {
-
- /**
- * The disgester instance for which this class is the entity resolver.
- */
- protected Digester digester;
-
-
- /**
- * The URLs of dtds and schemas that have been registered, keyed by the
- * public identifier that corresponds.
- */
- protected HashMap entityValidator = new HashMap();
-
-
- /**
- * The public identifier of the DTD we are currently parsing under
- * (if any).
- */
- protected String publicId = null;
-
-
- /**
- * Extension to make the difference between DTD and Schema.
- */
- protected String schemaExtension = "xsd";
-
-
- /**
- * Create a new <code>EntityResolver</code> that will redirect
- * all remote dtds and schema to a locat destination.
- * @param digester The digester instance.
- */
- public SchemaResolver(Digester digester) {
- this.digester = digester;
- }
-
-
- /**
- * Register the specified DTD/Schema URL for the specified public
- * identifier. This must be called before the first call to
- * <code>parse()</code>.
- *
- * When adding a schema file (*.xsd), only the name of the file
- * will get added. If two schemas with the same name are added,
- * only the last one will be stored.
- *
- * @param publicId Public identifier of the DTD to be resolved
- * @param entityURL The URL to use for reading this DTD
- */
- public void register(String publicId, String entityURL) {
- String key = publicId;
- if (publicId.indexOf(schemaExtension) != -1)
- key = publicId.substring(publicId.lastIndexOf('/')+1);
- entityValidator.put(key, entityURL);
- }
-
-
- /**
- * Resolve the requested external entity.
- *
- * @param publicId The public identifier of the entity being referenced
- * @param systemId The system identifier of the entity being referenced
- *
- * @exception SAXException if a parsing exception occurs
- *
- */
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException {
-
- if (publicId != null) {
- this.publicId = publicId;
- digester.setPublicId(publicId);
- }
-
- // Has this system identifier been registered?
- String entityURL = null;
- if (publicId != null) {
- entityURL = (String) entityValidator.get(publicId);
- }
-
- // Redirect the schema location to a local destination
- String key = null;
- if (entityURL == null && systemId != null) {
- key = systemId.substring(systemId.lastIndexOf('/')+1);
- entityURL = (String)entityValidator.get(key);
- }
-
- if (entityURL == null) {
- return (null);
- }
-
- try {
- return (new InputSource(entityURL));
- } catch (Exception e) {
- throw new SAXException(e);
- }
-
- }
-
-}
Deleted: trunk/java/org/apache/juli/ClassLoaderLogManager.java
===================================================================
--- trunk/java/org/apache/juli/ClassLoaderLogManager.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/juli/ClassLoaderLogManager.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,581 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.juli;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URLClassLoader;
-import java.security.AccessControlException;
-import java.security.AccessController;
-import java.security.Permission;
-import java.security.PrivilegedAction;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.WeakHashMap;
-import java.util.logging.Handler;
-import java.util.logging.Level;
-import java.util.logging.LogManager;
-import java.util.logging.Logger;
-
-
-/**
- * Per classloader LogManager implementation.
- */
-public class ClassLoaderLogManager extends LogManager {
-
-
- // -------------------------------------------------------------- Variables
-
-
- /**
- * Map containing the classloader information, keyed per classloader. A
- * weak hashmap is used to ensure no classloader reference is leaked from
- * application redeployment.
- */
- protected final Map<ClassLoader, ClassLoaderLogInfo> classLoaderLoggers =
- new WeakHashMap<ClassLoader, ClassLoaderLogInfo>();
-
-
- /**
- * This prefix is used to allow using prefixes for the properties names
- * of handlers and their subcomponents.
- */
- protected ThreadLocal<String> prefix = new ThreadLocal<String>();
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Add the specified logger to the classloader local configuration.
- *
- * @param logger The logger to be added
- */
- public synchronized boolean addLogger(final Logger logger) {
-
- final String loggerName = logger.getName();
-
- ClassLoader classLoader =
- Thread.currentThread().getContextClassLoader();
- ClassLoaderLogInfo info = getClassLoaderInfo(classLoader);
- if (info.loggers.containsKey(loggerName)) {
- return false;
- }
- info.loggers.put(loggerName, logger);
-
- // Apply initial level for new logger
- final String levelString = getProperty(loggerName + ".level");
- if (levelString != null) {
- try {
- AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- logger.setLevel(Level.parse(levelString.trim()));
- return null;
- }
- });
- } catch (IllegalArgumentException e) {
- // Leave level set to null
- }
- }
-
- // Instantiate all parent loggers
- int dotIndex = loggerName.lastIndexOf('.');
- while (dotIndex >= 0) {
- final String parentName = loggerName.substring(0, dotIndex);
- Logger.getLogger(parentName);
- dotIndex = loggerName.lastIndexOf('.', dotIndex - 1);
- }
-
- // Find associated node
- LogNode node = info.rootNode.findNode(loggerName);
- node.logger = logger;
-
- // Set parent logger
- Logger parentLogger = node.findParentLogger();
- if (parentLogger != null) {
- doSetParentLogger(logger, parentLogger);
- }
-
- // Tell children we are their new parent
- node.setParentLogger(logger);
-
- // Add associated handlers, if any are defined using the .handlers property.
- // In this case, handlers of the parent logger(s) will not be used
- String handlers = getProperty(loggerName + ".handlers");
- if (handlers != null) {
- logger.setUseParentHandlers(false);
- StringTokenizer tok = new StringTokenizer(handlers, ",");
- while (tok.hasMoreTokens()) {
- String handlerName = (tok.nextToken().trim());
- Handler handler = null;
- ClassLoader current = classLoader;
- while (current != null) {
- info = classLoaderLoggers.get(current);
- if (info != null) {
- handler = info.handlers.get(handlerName);
- if (handler != null) {
- break;
- }
- }
- current = current.getParent();
- }
- if (handler != null) {
- logger.addHandler(handler);
- }
- }
- }
-
- // Parse useParentHandlers to set if the logger should delegate to its parent.
- // Unlike java.util.logging, the default is to not delegate if a list of handlers
- // has been specified for the logger.
- String useParentHandlersString = getProperty(loggerName + ".useParentHandlers");
- if (Boolean.valueOf(useParentHandlersString).booleanValue()) {
- logger.setUseParentHandlers(true);
- }
-
- return true;
- }
-
-
- /**
- * Get the logger associated with the specified name inside
- * the classloader local configuration. If this returns null,
- * and the call originated for Logger.getLogger, a new
- * logger with the specified name will be instantiated and
- * added using addLogger.
- *
- * @param name The name of the logger to retrieve
- */
- public synchronized Logger getLogger(final String name) {
- ClassLoader classLoader = Thread.currentThread()
- .getContextClassLoader();
- return getClassLoaderInfo(classLoader).loggers.get(name);
- }
-
-
- /**
- * Get an enumeration of the logger names currently defined in the
- * classloader local configuration.
- */
- public synchronized Enumeration<String> getLoggerNames() {
- ClassLoader classLoader = Thread.currentThread()
- .getContextClassLoader();
- return Collections.enumeration(getClassLoaderInfo(classLoader).loggers.keySet());
- }
-
-
- /**
- * Get the value of the specified property in the classloader local
- * configuration.
- *
- * @param name The property name
- */
- public String getProperty(String name) {
- ClassLoader classLoader = Thread.currentThread()
- .getContextClassLoader();
- String prefix = this.prefix.get();
- if (prefix != null) {
- name = prefix + name;
- }
- ClassLoaderLogInfo info = getClassLoaderInfo(classLoader);
- String result = info.props.getProperty(name);
- // If the property was not found, and the current classloader had no
- // configuration (property list is empty), look for the parent classloader
- // properties.
- if ((result == null) && (info.props.isEmpty())) {
- ClassLoader current = classLoader.getParent();
- while (current != null) {
- info = classLoaderLoggers.get(current);
- if (info != null) {
- result = info.props.getProperty(name);
- if ((result != null) || (!info.props.isEmpty())) {
- break;
- }
- }
- current = current.getParent();
- }
- if (result == null) {
- result = super.getProperty(name);
- }
- }
- // Simple property replacement (mostly for folder names)
- if (result != null) {
- result = replace(result);
- }
- return result;
- }
-
-
- public void readConfiguration()
- throws IOException, SecurityException {
-
- checkAccess();
-
- readConfiguration(Thread.currentThread().getContextClassLoader());
-
- }
-
- public void readConfiguration(InputStream is)
- throws IOException, SecurityException {
-
- checkAccess();
- reset();
-
- readConfiguration(is, Thread.currentThread().getContextClassLoader());
-
- }
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Retrieve the configuration associated with the specified classloader. If
- * it does not exist, it will be created.
- *
- * @param classLoader The classloader for which we will retrieve or build the
- * configuration
- */
- protected ClassLoaderLogInfo getClassLoaderInfo(ClassLoader classLoader) {
-
- if (classLoader == null) {
- classLoader = ClassLoader.getSystemClassLoader();
- }
- ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader);
- if (info == null) {
- final ClassLoader classLoaderParam = classLoader;
- AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- try {
- readConfiguration(classLoaderParam);
- } catch (IOException e) {
- // Ignore
- }
- return null;
- }
- });
- info = classLoaderLoggers.get(classLoader);
- }
- return info;
- }
-
-
- /**
- * Read configuration for the specified classloader.
- *
- * @param classLoader
- * @throws IOException Errot
- */
- protected void readConfiguration(ClassLoader classLoader)
- throws IOException {
-
- InputStream is = null;
- // Special case for URL classloaders which are used in containers:
- // only look in the local repositories to avoid redefining loggers 20 times
- try {
- if ((classLoader instanceof URLClassLoader)
- && (((URLClassLoader) classLoader).findResource("logging.properties") != null)) {
- is = classLoader.getResourceAsStream("logging.properties");
- }
- } catch (AccessControlException ace) {
- // No permission to configure logging in context
- // Log and carry on
- ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader());
- if (info != null) {
- Logger log = info.loggers.get("");
- if (log != null) {
- Permission perm = ace.getPermission();
- if (perm instanceof FilePermission && perm.getActions().equals("read")) {
- log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file.");
- }
- else {
- log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file.");
- log.warning("Original error was: " + ace.getMessage());
- }
- }
- }
- }
- if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) {
- String configFileStr = System.getProperty("java.util.logging.config.file");
- if (configFileStr != null) {
- try {
- is = new FileInputStream(replace(configFileStr));
- } catch (IOException e) {
- // Ignore
- }
- }
- // Try the default JVM configuration
- if (is == null) {
- File defaultFile = new File(new File(System.getProperty("java.home"), "lib"),
- "logging.properties");
- try {
- is = new FileInputStream(defaultFile);
- } catch (IOException e) {
- // Critical problem, do something ...
- }
- }
- }
-
- Logger localRootLogger = new RootLogger();
- if (is == null) {
- // Retrieve the root logger of the parent classloader instead
- ClassLoader current = classLoader.getParent();
- ClassLoaderLogInfo info = null;
- while (current != null && info == null) {
- info = getClassLoaderInfo(current);
- current = current.getParent();
- }
- if (info != null) {
- localRootLogger.setParent(info.rootNode.logger);
- }
- }
- ClassLoaderLogInfo info =
- new ClassLoaderLogInfo(new LogNode(null, localRootLogger));
- classLoaderLoggers.put(classLoader, info);
-
- if (is != null) {
- readConfiguration(is, classLoader);
- }
- addLogger(localRootLogger);
-
- }
-
-
- /**
- * Load specified configuration.
- *
- * @param is InputStream to the properties file
- * @param classLoader for which the configuration will be loaded
- * @throws IOException If something wrong happens during loading
- */
- protected void readConfiguration(InputStream is, ClassLoader classLoader)
- throws IOException {
-
- ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader);
-
- try {
- info.props.load(is);
- } catch (IOException e) {
- // Report error
- System.err.println("Configuration error");
- e.printStackTrace();
- } finally {
- try {
- is.close();
- } catch (Throwable t) {}
- }
-
- // Create handlers for the root logger of this classloader
- String rootHandlers = info.props.getProperty(".handlers");
- String handlers = info.props.getProperty("handlers");
- Logger localRootLogger = info.rootNode.logger;
- if (handlers != null) {
- StringTokenizer tok = new StringTokenizer(handlers, ",");
- while (tok.hasMoreTokens()) {
- String handlerName = (tok.nextToken().trim());
- String handlerClassName = handlerName;
- String prefix = "";
- if (handlerClassName.length() <= 0) {
- continue;
- }
- // Parse and remove a prefix (prefix start with a digit, such as
- // "10WebappFooHanlder.")
- if (Character.isDigit(handlerClassName.charAt(0))) {
- int pos = handlerClassName.indexOf('.');
- if (pos >= 0) {
- prefix = handlerClassName.substring(0, pos + 1);
- handlerClassName = handlerClassName.substring(pos + 1);
- }
- }
- try {
- this.prefix.set(prefix);
- Handler handler =
- (Handler) classLoader.loadClass(handlerClassName).newInstance();
- // The specification strongly implies all configuration should be done
- // during the creation of the handler object.
- // This includes setting level, filter, formatter and encoding.
- this.prefix.set(null);
- info.handlers.put(handlerName, handler);
- if (rootHandlers == null) {
- localRootLogger.addHandler(handler);
- }
- } catch (Exception e) {
- // Report error
- System.err.println("Handler error");
- e.printStackTrace();
- }
- }
-
- }
-
- }
-
-
- /**
- * Set parent child relationship between the two specified loggers.
- *
- * @param logger
- * @param parent
- */
- protected static void doSetParentLogger(final Logger logger,
- final Logger parent) {
- AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- logger.setParent(parent);
- return null;
- }
- });
- }
-
-
- /**
- * System property replacement in the given string.
- *
- * @param str The original string
- * @return the modified string
- */
- protected String replace(String str) {
- String result = str;
- int pos_start = result.indexOf("${");
- if (pos_start != -1) {
- int pos_end = result.indexOf('}');
- if (pos_end != -1) {
- String propName = result.substring(pos_start + 2, pos_end);
- String replacement = System.getProperty(propName);
- if (replacement != null) {
- if(pos_start >0) {
- result = result.substring(0,pos_start) +
- replacement + replace(result.substring(pos_end + 1));
- } else {
- result = replacement + replace(result.substring(pos_end + 1));
- }
- }
- }
- }
- return result;
- }
-
-
- // ---------------------------------------------------- LogNode Inner Class
-
-
- protected static final class LogNode {
- Logger logger;
-
- protected final Map<String, LogNode> children =
- new HashMap<String, LogNode>();
-
- protected final LogNode parent;
-
- LogNode(final LogNode parent, final Logger logger) {
- this.parent = parent;
- this.logger = logger;
- }
-
- LogNode(final LogNode parent) {
- this(parent, null);
- }
-
- LogNode findNode(String name) {
- LogNode currentNode = this;
- if (logger.getName().equals(name)) {
- return this;
- }
- while (name != null) {
- final int dotIndex = name.indexOf('.');
- final String nextName;
- if (dotIndex < 0) {
- nextName = name;
- name = null;
- } else {
- nextName = name.substring(0, dotIndex);
- name = name.substring(dotIndex + 1);
- }
- LogNode childNode = currentNode.children.get(nextName);
- if (childNode == null) {
- childNode = new LogNode(currentNode);
- currentNode.children.put(nextName, childNode);
- }
- currentNode = childNode;
- }
- return currentNode;
- }
-
- Logger findParentLogger() {
- Logger logger = null;
- LogNode node = parent;
- while (node != null && logger == null) {
- logger = node.logger;
- node = node.parent;
- }
- return logger;
- }
-
- void setParentLogger(final Logger parent) {
- for (final Iterator iter = children.values().iterator(); iter
- .hasNext();) {
- final LogNode childNode = (LogNode) iter.next();
- if (childNode.logger == null) {
- childNode.setParentLogger(parent);
- } else {
- doSetParentLogger(childNode.logger, parent);
- }
- }
- }
-
- }
-
-
- // -------------------------------------------- ClassLoaderInfo Inner Class
-
-
- protected static final class ClassLoaderLogInfo {
- final LogNode rootNode;
- final Map<String, Logger> loggers = new HashMap<String, Logger>();
- final Map<String, Handler> handlers = new HashMap<String, Handler>();
- final Properties props = new Properties();
-
- ClassLoaderLogInfo(final LogNode rootNode) {
- this.rootNode = rootNode;
- }
-
- }
-
-
- // ------------------------------------------------- RootLogger Inner Class
-
-
- /**
- * This class is needed to instantiate the root of each per classloader
- * hierarchy.
- */
- protected class RootLogger extends Logger {
- public RootLogger() {
- super("", null);
- }
- }
-
-
-}
Deleted: trunk/java/org/apache/juli/FileHandler.java
===================================================================
--- trunk/java/org/apache/juli/FileHandler.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/juli/FileHandler.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,273 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.juli;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.PrintWriter;
-import java.sql.Timestamp;
-import java.util.logging.ErrorManager;
-import java.util.logging.Filter;
-import java.util.logging.Formatter;
-import java.util.logging.Handler;
-import java.util.logging.Level;
-import java.util.logging.LogManager;
-import java.util.logging.LogRecord;
-import java.util.logging.SimpleFormatter;
-
-/**
- * Implementation of <b>Handler</b> that appends log messages to a file
- * named {prefix}.{date}.{suffix} in a configured directory, with an
- * optional preceding timestamp.
- *
- * @version $Revision$ $Date$
- */
-
-public class FileHandler
- extends Handler {
-
-
- // ------------------------------------------------------------ Constructor
-
-
- public FileHandler() {
- this(null, null, null);
- }
-
-
- public FileHandler(String directory, String prefix, String suffix) {
- this.directory = directory;
- this.prefix = prefix;
- this.suffix = suffix;
- configure();
- open();
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The as-of date for the currently open log file, or a zero-length
- * string if there is no open log file.
- */
- private String date = "";
-
-
- /**
- * The directory in which log files are created.
- */
- private String directory = null;
-
-
- /**
- * The prefix that is added to log file filenames.
- */
- private String prefix = null;
-
-
- /**
- * The suffix that is added to log file filenames.
- */
- private String suffix = null;
-
-
- /**
- * The PrintWriter to which we are currently logging, if any.
- */
- private PrintWriter writer = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Format and publish a <tt>LogRecord</tt>.
- *
- * @param record description of the log event
- */
- public void publish(LogRecord record) {
-
- if (!isLoggable(record)) {
- return;
- }
-
- // Construct the timestamp we will use, if requested
- Timestamp ts = new Timestamp(System.currentTimeMillis());
- String tsString = ts.toString().substring(0, 19);
- String tsDate = tsString.substring(0, 10);
-
- // If the date has changed, switch log files
- if (!date.equals(tsDate)) {
- synchronized (this) {
- if (!date.equals(tsDate)) {
- close();
- date = tsDate;
- open();
- }
- }
- }
-
- String result = null;
- try {
- result = getFormatter().format(record);
- } catch (Exception e) {
- reportError(null, e, ErrorManager.FORMAT_FAILURE);
- return;
- }
-
- try {
- if (writer != null) {
- writer.write(result);
- writer.flush();
- } else {
- reportError("FileHandler is closed or not yet initialized, unable to log ["+result+"]", null, ErrorManager.WRITE_FAILURE);
- }
- } catch (Exception e) {
- reportError(null, e, ErrorManager.WRITE_FAILURE);
- return;
- }
-
- }
-
-
- // -------------------------------------------------------- Private Methods
-
-
- /**
- * Close the currently open log file (if any).
- */
- public void close() {
-
- try {
- if (writer == null)
- return;
- writer.write(getFormatter().getTail(this));
- writer.flush();
- writer.close();
- writer = null;
- date = "";
- } catch (Exception e) {
- reportError(null, e, ErrorManager.CLOSE_FAILURE);
- }
-
- }
-
-
- /**
- * Flush the writer.
- */
- public void flush() {
-
- try {
- writer.flush();
- } catch (Exception e) {
- reportError(null, e, ErrorManager.FLUSH_FAILURE);
- }
-
- }
-
-
- /**
- * Configure from <code>LogManager</code> properties.
- */
- private void configure() {
-
- Timestamp ts = new Timestamp(System.currentTimeMillis());
- String tsString = ts.toString().substring(0, 19);
- date = tsString.substring(0, 10);
-
- String className = FileHandler.class.getName();
-
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
-
- // Retrieve configuration of logging file name
- if (directory == null)
- directory = getProperty(className + ".directory", "logs");
- if (prefix == null)
- prefix = getProperty(className + ".prefix", "juli.");
- if (suffix == null)
- suffix = getProperty(className + ".suffix", ".log");
-
- // Get logging level for the handler
- setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL)));
-
- // Get filter configuration
- String filterName = getProperty(className + ".filter", null);
- if (filterName != null) {
- try {
- setFilter((Filter) cl.loadClass(filterName).newInstance());
- } catch (Exception e) {
- // Ignore
- }
- }
-
- // Set formatter
- String formatterName = getProperty(className + ".formatter", null);
- if (formatterName != null) {
- try {
- setFormatter((Formatter) cl.loadClass(formatterName).newInstance());
- } catch (Exception e) {
- // Ignore
- }
- } else {
- setFormatter(new SimpleFormatter());
- }
-
- // Set error manager
- setErrorManager(new ErrorManager());
-
- }
-
-
- private String getProperty(String name, String defaultValue) {
- String value = LogManager.getLogManager().getProperty(name);
- if (value == null) {
- value = defaultValue;
- } else {
- value = value.trim();
- }
- return value;
- }
-
-
- /**
- * Open the new log file for the date specified by <code>date</code>.
- */
- private void open() {
-
- // Create the directory if necessary
- File dir = new File(directory);
- dir.mkdirs();
-
- // Open the current log file
- try {
- String pathname = dir.getAbsolutePath() + File.separator +
- prefix + date + suffix;
- writer = new PrintWriter(new FileWriter(pathname, true), true);
- writer.write(getFormatter().getHead(this));
- } catch (Exception e) {
- reportError(null, e, ErrorManager.OPEN_FAILURE);
- writer = null;
- }
-
- }
-
-
-}
Deleted: trunk/java/org/apache/juli/JdkLoggerFormatter.java
===================================================================
--- trunk/java/org/apache/juli/JdkLoggerFormatter.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/juli/JdkLoggerFormatter.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.juli;
-
-import java.util.logging.Formatter;
-import java.util.logging.LogRecord;
-
-
-
-/**
- * A more compact formatter.
- *
- * Equivalent log4j config:
- * <pre>
- * log4j.rootCategory=WARN, A1
- * log4j.appender.A1=org.apache.log4j.ConsoleAppender
- * log4j.appender.A1.layout=org.apache.log4j.PatternLayout
- * log4j.appender.A1.Target=System.err
- * log4j.appender.A1.layout.ConversionPattern=%r %-15.15c{2} %-1.1p %m %n
- * </pre>
- *
- * Example:
- * 1130122891846 Http11BaseProtocol I Initializing Coyote HTTP/1.1 on http-8800
- *
- *
- * @author Costin Manolache
- */
-public class JdkLoggerFormatter extends Formatter {
- // values from JDK Level
- public static final int LOG_LEVEL_TRACE = 400;
- public static final int LOG_LEVEL_DEBUG = 500;
- public static final int LOG_LEVEL_INFO = 800;
- public static final int LOG_LEVEL_WARN = 900;
- public static final int LOG_LEVEL_ERROR = 1000;
- public static final int LOG_LEVEL_FATAL = 1000;
-
- public String format(LogRecord record) {
- Throwable t=record.getThrown();
- int level=record.getLevel().intValue();
- String name=record.getLoggerName();
- long time=record.getMillis();
- String message=formatMessage(record);
-
-
- if( name.indexOf(".") >= 0 )
- name = name.substring(name.lastIndexOf(".") + 1);
-
- // Use a string buffer for better performance
- StringBuilder buf = new StringBuilder();
-
- buf.append(time);
- buf.append(" ");
-
- // pad to 8 to make it more readable
- for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
-
- // Append a readable representation of the log level.
- switch(level) {
- case LOG_LEVEL_TRACE: buf.append(" T "); break;
- case LOG_LEVEL_DEBUG: buf.append(" D "); break;
- case LOG_LEVEL_INFO: buf.append(" I "); break;
- case LOG_LEVEL_WARN: buf.append(" W "); break;
- case LOG_LEVEL_ERROR: buf.append(" E "); break;
- //case : buf.append(" F "); break;
- default: buf.append(" ");
- }
-
-
- // Append the name of the log instance if so configured
- buf.append(name);
-
- // pad to 20 chars
- for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
-
- // Append the message
- buf.append(message);
-
- // Append stack trace if not null
- if(t != null) {
- buf.append(" \n");
-
- java.io.StringWriter sw= new java.io.StringWriter(1024);
- java.io.PrintWriter pw= new java.io.PrintWriter(sw);
- t.printStackTrace(pw);
- pw.close();
- buf.append(sw.toString());
- }
-
- buf.append("\n");
- // Print to the appropriate destination
- return buf.toString();
- }
-
-}
Deleted: trunk/java/org/apache/juli/OneLineFormatter.java
===================================================================
--- trunk/java/org/apache/juli/OneLineFormatter.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/juli/OneLineFormatter.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.juli;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.logging.Formatter;
-import java.util.logging.LogRecord;
-
-/**
- * Provides same information as default log format but on a single line to make
- * it easier to grep the logs. The only exception is stack traces which are
- * always preceded by whitespace to make it simple to skip them.
- */
-/*
- * Date processing based on AccessLogValve.
- */
-public class OneLineFormatter extends Formatter {
-
- /**
- * The set of month abbreviations for log messages.
- */
- private static final String months[] = {"Jan", "Feb", "Mar", "Apr", "May",
- "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
-
- private static final String LINE_SEP = System.getProperty("line.separator");
- private static final String ST_SEP = LINE_SEP + " ";
-
- private final SimpleDateFormat dayFormatter = new SimpleDateFormat("dd");
- private final SimpleDateFormat monthFormatter = new SimpleDateFormat("MM");
- private final SimpleDateFormat yearFormatter = new SimpleDateFormat("yyyy");
- private final SimpleDateFormat timeFormatter =
- new SimpleDateFormat("HH:mm:ss.S");
-
- private Date currentDate;
- private String currentDateString;
-
- @Override
- public String format(LogRecord record) {
- StringBuilder sb = new StringBuilder();
-
- // Timestamp
- addTimestamp(sb, new Date(record.getMillis()));
-
- // Severity
- sb.append(' ');
- sb.append(record.getLevel());
-
- // Source
- sb.append(' ');
- sb.append(record.getSourceClassName());
- sb.append('.');
- sb.append(record.getSourceMethodName());
-
- // Message
- sb.append(' ');
- sb.append(record.getMessage());
-
- // Stack trace
- if (record.getThrown() != null) {
- sb.append(ST_SEP);
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- record.getThrown().printStackTrace(pw);
- pw.close();
- sb.append(sw.getBuffer());
- }
-
- // New line for next record
- sb.append(LINE_SEP);
-
- return sb.toString();
- }
-
- public void addTimestamp(StringBuilder buf, Date date) {
- if (currentDate != date) {
- synchronized (this) {
- if (currentDate != date) {
- StringBuilder current = new StringBuilder(32);
- current.append(dayFormatter.format(date)); // Day
- current.append('-');
- current.append(lookup(monthFormatter.format(date))); // Month
- current.append('-');
- current.append(yearFormatter.format(date)); // Year
- current.append(' ');
- current.append(timeFormatter.format(date)); // Time
- currentDateString = current.toString();
- currentDate = date;
- }
- }
- }
- buf.append(currentDateString);
- }
-
- /**
- * Return the month abbreviation for the specified month, which must
- * be a two-digit String.
- *
- * @param month Month number ("01" .. "12").
- */
- private String lookup(String month) {
- int index;
- try {
- index = Integer.parseInt(month) - 1;
- } catch (Throwable t) {
- index = 0; // Can not happen, in theory
- }
- return (months[index]);
- }
-}
Deleted: trunk/java/org/apache/naming/ContextAccessController.java
===================================================================
--- trunk/java/org/apache/naming/ContextAccessController.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/ContextAccessController.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.Hashtable;
-
-/**
- * Handles the access control on the JNDI contexts.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ContextAccessController {
-
-
- // -------------------------------------------------------------- Variables
-
-
- /**
- * Catalina context names on which writing is not allowed.
- */
- private static Hashtable readOnlyContexts = new Hashtable();
-
-
- /**
- * Security tokens repository.
- */
- private static Hashtable securityTokens = new Hashtable();
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Set a security token for a context. Can be set only once.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void setSecurityToken(Object name, Object token) {
- if ((!securityTokens.containsKey(name)) && (token != null)) {
- securityTokens.put(name, token);
- }
- }
-
-
- /**
- * Remove a security token for a context.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void unsetSecurityToken(Object name, Object token) {
- if (checkSecurityToken(name, token)) {
- securityTokens.remove(name);
- }
- }
-
-
- /**
- * Check a submitted security token. The submitted token must be equal to
- * the token present in the repository. If no token is present for the
- * context, then returns true.
- *
- * @param name Name of the context
- * @param token Submitted security token
- */
- public static boolean checkSecurityToken
- (Object name, Object token) {
- Object refToken = securityTokens.get(name);
- if (refToken == null)
- return (true);
- if ((refToken != null) && (refToken.equals(token)))
- return (true);
- return (false);
- }
-
-
- /**
- * Allow writing to a context.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void setWritable(Object name, Object token) {
- if (checkSecurityToken(name, token))
- readOnlyContexts.remove(name);
- }
-
-
- /**
- * Set whether or not a context is writable.
- *
- * @param name Name of the context
- */
- public static void setReadOnly(Object name) {
- readOnlyContexts.put(name, name);
- }
-
-
- /**
- * Returns if a context is writable.
- *
- * @param name Name of the context
- */
- public static boolean isWritable(Object name) {
- return !(readOnlyContexts.containsKey(name));
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/ContextBindings.java
===================================================================
--- trunk/java/org/apache/naming/ContextBindings.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/ContextBindings.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,363 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.Hashtable;
-import javax.naming.NamingException;
-import javax.naming.Context;
-
-/**
- * Handles the associations :
- * <ul>
- * <li>Catalina context name with the NamingContext</li>
- * <li>Calling thread with the NamingContext</li>
- * </ul>
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ContextBindings {
-
-
- // -------------------------------------------------------------- Variables
-
-
- /**
- * Bindings name - naming context. Keyed by name.
- */
- private static Hashtable contextNameBindings = new Hashtable();
-
-
- /**
- * Bindings thread - naming context. Keyed by thread id.
- */
- private static Hashtable threadBindings = new Hashtable();
-
-
- /**
- * Bindings thread - name. Keyed by thread id.
- */
- private static Hashtable threadNameBindings = new Hashtable();
-
-
- /**
- * Bindings class loader - naming context. Keyed by CL id.
- */
- private static Hashtable clBindings = new Hashtable();
-
-
- /**
- * Bindings class loader - name. Keyed by CL id.
- */
- private static Hashtable clNameBindings = new Hashtable();
-
-
- /**
- * The string manager for this package.
- */
- protected static StringManager sm =
- StringManager.getManager(Constants.Package);
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Binds a context name.
- *
- * @param name Name of the context
- * @param context Associated naming context instance
- */
- public static void bindContext(Object name, Context context) {
- bindContext(name, context, null);
- }
-
-
- /**
- * Binds a context name.
- *
- * @param name Name of the context
- * @param context Associated naming context instance
- * @param token Security token
- */
- public static void bindContext(Object name, Context context,
- Object token) {
- if (ContextAccessController.checkSecurityToken(name, token))
- contextNameBindings.put(name, context);
- }
-
-
- /**
- * Unbind context name.
- *
- * @param name Name of the context
- */
- public static void unbindContext(Object name) {
- unbindContext(name, null);
- }
-
-
- /**
- * Unbind context name.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void unbindContext(Object name, Object token) {
- if (ContextAccessController.checkSecurityToken(name, token))
- contextNameBindings.remove(name);
- }
-
-
- /**
- * Retrieve a naming context.
- *
- * @param name Name of the context
- */
- static Context getContext(Object name) {
- return (Context) contextNameBindings.get(name);
- }
-
-
- /**
- * Binds a naming context to a thread.
- *
- * @param name Name of the context
- */
- public static void bindThread(Object name)
- throws NamingException {
- bindThread(name, null);
- }
-
-
- /**
- * Binds a naming context to a thread.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void bindThread(Object name, Object token)
- throws NamingException {
- if (ContextAccessController.checkSecurityToken(name, token)) {
- Context context = (Context) contextNameBindings.get(name);
- if (context == null)
- throw new NamingException
- (sm.getString("contextBindings.unknownContext", name));
- threadBindings.put(Thread.currentThread(), context);
- threadNameBindings.put(Thread.currentThread(), name);
- }
- }
-
-
- /**
- * Unbinds a naming context to a thread.
- *
- * @param name Name of the context
- */
- public static void unbindThread(Object name) {
- unbindThread(name, null);
- }
-
-
- /**
- * Unbinds a naming context to a thread.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void unbindThread(Object name, Object token) {
- if (ContextAccessController.checkSecurityToken(name, token)) {
- threadBindings.remove(Thread.currentThread());
- threadNameBindings.remove(Thread.currentThread());
- }
- }
-
-
- /**
- * Retrieves the naming context bound to a thread.
- */
- public static Context getThread()
- throws NamingException {
- Context context =
- (Context) threadBindings.get(Thread.currentThread());
- if (context == null)
- throw new NamingException
- (sm.getString("contextBindings.noContextBoundToThread"));
- return context;
- }
-
-
- /**
- * Retrieves the naming context name bound to a thread.
- */
- static Object getThreadName()
- throws NamingException {
- Object name = threadNameBindings.get(Thread.currentThread());
- if (name == null)
- throw new NamingException
- (sm.getString("contextBindings.noContextBoundToThread"));
- return name;
- }
-
-
- /**
- * Tests if current thread is bound to a context.
- */
- public static boolean isThreadBound() {
- return (threadBindings.containsKey(Thread.currentThread()));
- }
-
-
- /**
- * Binds a naming context to a class loader.
- *
- * @param name Name of the context
- */
- public static void bindClassLoader(Object name)
- throws NamingException {
- bindClassLoader(name, null);
- }
-
-
- /**
- * Binds a naming context to a thread.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void bindClassLoader(Object name, Object token)
- throws NamingException {
- bindClassLoader
- (name, token, Thread.currentThread().getContextClassLoader());
- }
-
-
- /**
- * Binds a naming context to a thread.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void bindClassLoader(Object name, Object token,
- ClassLoader classLoader)
- throws NamingException {
- if (ContextAccessController.checkSecurityToken(name, token)) {
- Context context = (Context) contextNameBindings.get(name);
- if (context == null)
- throw new NamingException
- (sm.getString("contextBindings.unknownContext", name));
- clBindings.put(classLoader, context);
- clNameBindings.put(classLoader, name);
- }
- }
-
-
- /**
- * Unbinds a naming context to a class loader.
- *
- * @param name Name of the context
- */
- public static void unbindClassLoader(Object name) {
- unbindClassLoader(name, null);
- }
-
-
- /**
- * Unbinds a naming context to a class loader.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void unbindClassLoader(Object name, Object token) {
- unbindClassLoader(name, token,
- Thread.currentThread().getContextClassLoader());
- }
-
-
- /**
- * Unbinds a naming context to a class loader.
- *
- * @param name Name of the context
- * @param token Security token
- */
- public static void unbindClassLoader(Object name, Object token,
- ClassLoader classLoader) {
- if (ContextAccessController.checkSecurityToken(name, token)) {
- Object n = clNameBindings.get(classLoader);
- if ((n==null) || !(n.equals(name))) {
- return;
- }
- clBindings.remove(classLoader);
- clNameBindings.remove(classLoader);
- }
- }
-
-
- /**
- * Retrieves the naming context bound to a class loader.
- */
- public static Context getClassLoader()
- throws NamingException {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- Context context = null;
- do {
- context = (Context) clBindings.get(cl);
- if (context != null) {
- return context;
- }
- } while ((cl = cl.getParent()) != null);
- throw new NamingException
- (sm.getString("contextBindings.noContextBoundToCL"));
- }
-
-
- /**
- * Retrieves the naming context name bound to a class loader.
- */
- static Object getClassLoaderName()
- throws NamingException {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- Object name = null;
- do {
- name = clNameBindings.get(cl);
- if (name != null) {
- return name;
- }
- } while ((cl = cl.getParent()) != null);
- throw new NamingException
- (sm.getString("contextBindings.noContextBoundToCL"));
- }
-
-
- /**
- * Tests if current class loader is bound to a context.
- */
- public static boolean isClassLoaderBound() {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- do {
- if (clBindings.containsKey(cl)) {
- return true;
- }
- } while ((cl = cl.getParent()) != null);
- return false;
- }
-
-
-}
Deleted: trunk/java/org/apache/naming/EjbRef.java
===================================================================
--- trunk/java/org/apache/naming/EjbRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/EjbRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import javax.naming.Context;
-import javax.naming.Reference;
-import javax.naming.StringRefAddr;
-
-/**
- * Represents a reference address to an EJB.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class EjbRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_EJB_FACTORY;
-
-
- /**
- * EJB type address type.
- */
- public static final String TYPE = "type";
-
-
- /**
- * Remote interface classname address type.
- */
- public static final String REMOTE = "remote";
-
-
- /**
- * Link address type.
- */
- public static final String LINK = "link";
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * EJB Reference.
- *
- * @param ejbType EJB type
- * @param home Home interface classname
- * @param remote Remote interface classname
- * @param link EJB link
- */
- public EjbRef(String ejbType, String home, String remote, String link) {
- this(ejbType, home, remote, link, null, null);
- }
-
-
- /**
- * EJB Reference.
- *
- * @param ejbType EJB type
- * @param home Home interface classname
- * @param remote Remote interface classname
- * @param link EJB link
- */
- public EjbRef(String ejbType, String home, String remote, String link,
- String factory, String factoryLocation) {
- super(home, factory, factoryLocation);
- StringRefAddr refAddr = null;
- if (ejbType != null) {
- refAddr = new StringRefAddr(TYPE, ejbType);
- add(refAddr);
- }
- if (remote != null) {
- refAddr = new StringRefAddr(REMOTE, remote);
- add(refAddr);
- }
- if (link != null) {
- refAddr = new StringRefAddr(LINK, link);
- add(refAddr);
- }
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // -------------------------------------------------------- RefAddr Methods
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/HandlerRef.java
===================================================================
--- trunk/java/org/apache/naming/HandlerRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/HandlerRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,187 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.Enumeration;
-
-import javax.naming.Context;
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import javax.naming.StringRefAddr;
-
-/**
- * Represents a reference handler for a web service.
- *
- * @author Fabien Carrion
- */
-
-public class HandlerRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_HANDLER_FACTORY;
-
-
- /**
- * HandlerName address type.
- */
- public static final String HANDLER_NAME = "handlername";
-
-
- /**
- * Handler Classname address type.
- */
- public static final String HANDLER_CLASS = "handlerclass";
-
-
- /**
- * Handler Classname address type.
- */
- public static final String HANDLER_LOCALPART = "handlerlocalpart";
-
-
- /**
- * Handler Classname address type.
- */
- public static final String HANDLER_NAMESPACE = "handlernamespace";
-
-
- /**
- * Handler Classname address type.
- */
- public static final String HANDLER_PARAMNAME = "handlerparamname";
-
-
- /**
- * Handler Classname address type.
- */
- public static final String HANDLER_PARAMVALUE = "handlerparamvalue";
-
-
- /**
- * Handler SoapRole address type.
- */
- public static final String HANDLER_SOAPROLE = "handlersoaprole";
-
-
- /**
- * Handler PortName address type.
- */
- public static final String HANDLER_PORTNAME = "handlerportname";
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Service Reference.
- *
- * @param serviceClass Service class
- */
- public HandlerRef(String refname, String handlerClass) {
- this(refname, handlerClass, null, null);
- }
-
-
- /**
- * Service Reference.
- *
- * @param serviceClass Service class
- */
- public HandlerRef(String refname, String handlerClass,
- String factory, String factoryLocation) {
- super(refname, factory, factoryLocation);
- StringRefAddr refAddr = null;
- if (refname != null) {
- refAddr = new StringRefAddr(HANDLER_NAME, refname);
- add(refAddr);
- }
- if (handlerClass != null) {
- refAddr = new StringRefAddr(HANDLER_CLASS, handlerClass);
- add(refAddr);
- }
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return a String rendering of this object.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("HandlerRef[");
- sb.append("className=");
- sb.append(getClassName());
- sb.append(",factoryClassLocation=");
- sb.append(getFactoryClassLocation());
- sb.append(",factoryClassName=");
- sb.append(getFactoryClassName());
- Enumeration refAddrs = getAll();
- while (refAddrs.hasMoreElements()) {
- RefAddr refAddr = (RefAddr) refAddrs.nextElement();
- sb.append(",{type=");
- sb.append(refAddr.getType());
- sb.append(",content=");
- sb.append(refAddr.getContent());
- sb.append("}");
- }
- sb.append("]");
- return (sb.toString());
-
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/NamingContext.java
===================================================================
--- trunk/java/org/apache/naming/NamingContext.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/NamingContext.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,908 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Enumeration;
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.LinkRef;
-import javax.naming.CompositeName;
-import javax.naming.NameParser;
-import javax.naming.Referenceable;
-import javax.naming.Reference;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.NameAlreadyBoundException;
-import javax.naming.NameNotFoundException;
-import javax.naming.NotContextException;
-import javax.naming.InitialContext;
-import javax.naming.OperationNotSupportedException;
-import javax.naming.spi.NamingManager;
-
-/**
- * Catalina JNDI Context implementation.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-public class NamingContext implements Context {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Name parser for this context.
- */
- protected static final NameParser nameParser = new NameParserImpl();
-
-
- private static org.jboss.logging.Logger log =
- org.jboss.logging.Logger.getLogger(NamingContext.class);
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Builds a naming context using the given environment.
- */
- public NamingContext(Hashtable env, String name)
- throws NamingException {
- this.bindings = new HashMap();
- this.env = new Hashtable();
- // FIXME ? Could be put in the environment ?
- this.name = name;
- // Populating the environment hashtable
- if (env != null ) {
- Enumeration envEntries = env.keys();
- while (envEntries.hasMoreElements()) {
- String entryName = (String) envEntries.nextElement();
- addToEnvironment(entryName, env.get(entryName));
- }
- }
- }
-
-
- /**
- * Builds a naming context using the given environment.
- */
- public NamingContext(Hashtable env, String name, HashMap bindings)
- throws NamingException {
- this(env, name);
- this.bindings = bindings;
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Environment.
- */
- protected Hashtable env;
-
-
- /**
- * The string manager for this package.
- */
- protected StringManager sm = StringManager.getManager(Constants.Package);
-
-
- /**
- * Bindings in this Context.
- */
- protected HashMap bindings;
-
-
- /**
- * Name of the associated Catalina Context.
- */
- protected String name;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------------- Context Methods
-
-
- /**
- * Retrieves the named object. If name is empty, returns a new instance
- * of this context (which represents the same naming context as this
- * context, but its environment may be modified independently and it may
- * be accessed concurrently).
- *
- * @param name the name of the object to look up
- * @return the object bound to name
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookup(Name name)
- throws NamingException {
- return lookup(name, true);
- }
-
-
- /**
- * Retrieves the named object.
- *
- * @param name the name of the object to look up
- * @return the object bound to name
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookup(String name)
- throws NamingException {
- return lookup(new CompositeName(name), true);
- }
-
-
- /**
- * Binds a name to an object. All intermediate contexts and the target
- * context (that named by all but terminal atomic component of the name)
- * must already exist.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void bind(Name name, Object obj)
- throws NamingException {
- bind(name, obj, false);
- }
-
-
- /**
- * Binds a name to an object.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void bind(String name, Object obj)
- throws NamingException {
- bind(new CompositeName(name), obj);
- }
-
-
- /**
- * Binds a name to an object, overwriting any existing binding. All
- * intermediate contexts and the target context (that named by all but
- * terminal atomic component of the name) must already exist.
- * <p>
- * If the object is a DirContext, any existing attributes associated with
- * the name are replaced with those of the object. Otherwise, any
- * existing attributes associated with the name remain unchanged.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void rebind(Name name, Object obj)
- throws NamingException {
- bind(name, obj, true);
- }
-
-
- /**
- * Binds a name to an object, overwriting any existing binding.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void rebind(String name, Object obj)
- throws NamingException {
- rebind(new CompositeName(name), obj);
- }
-
-
- /**
- * Unbinds the named object. Removes the terminal atomic name in name
- * from the target context--that named by all but the terminal atomic
- * part of name.
- * <p>
- * This method is idempotent. It succeeds even if the terminal atomic
- * name is not bound in the target context, but throws
- * NameNotFoundException if any of the intermediate contexts do not exist.
- *
- * @param name the name to bind; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NamingException if a naming exception is encountered
- */
- public void unbind(Name name)
- throws NamingException {
- checkWritable();
-
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty())
- throw new NamingException
- (sm.getString("namingContext.invalidName"));
-
- NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
-
- if (entry == null) {
- throw new NameNotFoundException
- (sm.getString("namingContext.nameNotBound", name.get(0)));
- }
-
- if (name.size() > 1) {
- if (entry.type == NamingEntry.CONTEXT) {
- ((Context) entry.value).unbind(name.getSuffix(1));
- } else {
- throw new NamingException
- (sm.getString("namingContext.contextExpected"));
- }
- } else {
- bindings.remove(name.get(0));
- }
-
- }
-
-
- /**
- * Unbinds the named object.
- *
- * @param name the name to bind; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NamingException if a naming exception is encountered
- */
- public void unbind(String name)
- throws NamingException {
- unbind(new CompositeName(name));
- }
-
-
- /**
- * Binds a new name to the object bound to an old name, and unbinds the
- * old name. Both names are relative to this context. Any attributes
- * associated with the old name become associated with the new name.
- * Intermediate contexts of the old name are not changed.
- *
- * @param oldName the name of the existing binding; may not be empty
- * @param newName the name of the new binding; may not be empty
- * @exception NameAlreadyBoundException if newName is already bound
- * @exception NamingException if a naming exception is encountered
- */
- public void rename(Name oldName, Name newName)
- throws NamingException {
- Object value = lookup(oldName);
- bind(newName, value);
- unbind(oldName);
- }
-
-
- /**
- * Binds a new name to the object bound to an old name, and unbinds the
- * old name.
- *
- * @param oldName the name of the existing binding; may not be empty
- * @param newName the name of the new binding; may not be empty
- * @exception NameAlreadyBoundException if newName is already bound
- * @exception NamingException if a naming exception is encountered
- */
- public void rename(String oldName, String newName)
- throws NamingException {
- rename(new CompositeName(oldName), new CompositeName(newName));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the class
- * names of objects bound to them. The contents of any subcontexts are
- * not included.
- * <p>
- * If a binding is added to or removed from this context, its effect on
- * an enumeration previously returned is undefined.
- *
- * @param name the name of the context to list
- * @return an enumeration of the names and class names of the bindings in
- * this context. Each element of the enumeration is of type NameClassPair.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration list(Name name)
- throws NamingException {
- // Removing empty parts
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty()) {
- return new NamingContextEnumeration(bindings.values().iterator());
- }
-
- NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
-
- if (entry == null) {
- throw new NameNotFoundException
- (sm.getString("namingContext.nameNotBound", name.get(0)));
- }
-
- if (entry.type != NamingEntry.CONTEXT) {
- throw new NamingException
- (sm.getString("namingContext.contextExpected"));
- }
- return ((Context) entry.value).list(name.getSuffix(1));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the class
- * names of objects bound to them.
- *
- * @param name the name of the context to list
- * @return an enumeration of the names and class names of the bindings in
- * this context. Each element of the enumeration is of type NameClassPair.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration list(String name)
- throws NamingException {
- return list(new CompositeName(name));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the
- * objects bound to them. The contents of any subcontexts are not
- * included.
- * <p>
- * If a binding is added to or removed from this context, its effect on
- * an enumeration previously returned is undefined.
- *
- * @param name the name of the context to list
- * @return an enumeration of the bindings in this context.
- * Each element of the enumeration is of type Binding.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration listBindings(Name name)
- throws NamingException {
- // Removing empty parts
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty()) {
- return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
- }
-
- NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
-
- if (entry == null) {
- throw new NameNotFoundException
- (sm.getString("namingContext.nameNotBound", name.get(0)));
- }
-
- if (entry.type != NamingEntry.CONTEXT) {
- throw new NamingException
- (sm.getString("namingContext.contextExpected"));
- }
- return ((Context) entry.value).listBindings(name.getSuffix(1));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the
- * objects bound to them.
- *
- * @param name the name of the context to list
- * @return an enumeration of the bindings in this context.
- * Each element of the enumeration is of type Binding.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration listBindings(String name)
- throws NamingException {
- return listBindings(new CompositeName(name));
- }
-
-
- /**
- * Destroys the named context and removes it from the namespace. Any
- * attributes associated with the name are also removed. Intermediate
- * contexts are not destroyed.
- * <p>
- * This method is idempotent. It succeeds even if the terminal atomic
- * name is not bound in the target context, but throws
- * NameNotFoundException if any of the intermediate contexts do not exist.
- *
- * In a federated naming system, a context from one naming system may be
- * bound to a name in another. One can subsequently look up and perform
- * operations on the foreign context using a composite name. However, an
- * attempt destroy the context using this composite name will fail with
- * NotContextException, because the foreign context is not a "subcontext"
- * of the context in which it is bound. Instead, use unbind() to remove
- * the binding of the foreign context. Destroying the foreign context
- * requires that the destroySubcontext() be performed on a context from
- * the foreign context's "native" naming system.
- *
- * @param name the name of the context to be destroyed; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NotContextException if the name is bound but does not name
- * a context, or does not name a context of the appropriate type
- */
- public void destroySubcontext(Name name)
- throws NamingException {
-
- checkWritable();
-
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty())
- throw new NamingException
- (sm.getString("namingContext.invalidName"));
-
- NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
-
- if (entry == null) {
- throw new NameNotFoundException
- (sm.getString("namingContext.nameNotBound", name.get(0)));
- }
-
- if (name.size() > 1) {
- if (entry.type == NamingEntry.CONTEXT) {
- ((Context) entry.value).destroySubcontext(name.getSuffix(1));
- } else {
- throw new NamingException
- (sm.getString("namingContext.contextExpected"));
- }
- } else {
- if (entry.type == NamingEntry.CONTEXT) {
- ((Context) entry.value).close();
- bindings.remove(name.get(0));
- } else {
- throw new NotContextException
- (sm.getString("namingContext.contextExpected"));
- }
- }
-
- }
-
-
- /**
- * Destroys the named context and removes it from the namespace.
- *
- * @param name the name of the context to be destroyed; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NotContextException if the name is bound but does not name
- * a context, or does not name a context of the appropriate type
- */
- public void destroySubcontext(String name)
- throws NamingException {
- destroySubcontext(new CompositeName(name));
- }
-
-
- /**
- * Creates and binds a new context. Creates a new context with the given
- * name and binds it in the target context (that named by all but
- * terminal atomic component of the name). All intermediate contexts and
- * the target context must already exist.
- *
- * @param name the name of the context to create; may not be empty
- * @return the newly created context
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if creation of the subcontext
- * requires specification of mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public Context createSubcontext(Name name)
- throws NamingException {
- checkWritable();
-
- Context newContext = new NamingContext(env, this.name);
- bind(name, newContext);
-
- return newContext;
- }
-
-
- /**
- * Creates and binds a new context.
- *
- * @param name the name of the context to create; may not be empty
- * @return the newly created context
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if creation of the subcontext
- * requires specification of mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public Context createSubcontext(String name)
- throws NamingException {
- return createSubcontext(new CompositeName(name));
- }
-
-
- /**
- * Retrieves the named object, following links except for the terminal
- * atomic component of the name. If the object bound to name is not a
- * link, returns the object itself.
- *
- * @param name the name of the object to look up
- * @return the object bound to name, not following the terminal link
- * (if any).
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookupLink(Name name)
- throws NamingException {
- return lookup(name, false);
- }
-
-
- /**
- * Retrieves the named object, following links except for the terminal
- * atomic component of the name.
- *
- * @param name the name of the object to look up
- * @return the object bound to name, not following the terminal link
- * (if any).
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookupLink(String name)
- throws NamingException {
- return lookup(new CompositeName(name), false);
- }
-
-
- /**
- * Retrieves the parser associated with the named context. In a
- * federation of namespaces, different naming systems will parse names
- * differently. This method allows an application to get a parser for
- * parsing names into their atomic components using the naming convention
- * of a particular naming system. Within any single naming system,
- * NameParser objects returned by this method must be equal (using the
- * equals() test).
- *
- * @param name the name of the context from which to get the parser
- * @return a name parser that can parse compound names into their atomic
- * components
- * @exception NamingException if a naming exception is encountered
- */
- public NameParser getNameParser(Name name)
- throws NamingException {
-
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty())
- return nameParser;
-
- if (name.size() > 1) {
- Object obj = bindings.get(name.get(0));
- if (obj instanceof Context) {
- return ((Context) obj).getNameParser(name.getSuffix(1));
- } else {
- throw new NotContextException
- (sm.getString("namingContext.contextExpected"));
- }
- }
-
- return nameParser;
-
- }
-
-
- /**
- * Retrieves the parser associated with the named context.
- *
- * @param name the name of the context from which to get the parser
- * @return a name parser that can parse compound names into their atomic
- * components
- * @exception NamingException if a naming exception is encountered
- */
- public NameParser getNameParser(String name)
- throws NamingException {
- return getNameParser(new CompositeName(name));
- }
-
-
- /**
- * Composes the name of this context with a name relative to this context.
- * <p>
- * Given a name (name) relative to this context, and the name (prefix)
- * of this context relative to one of its ancestors, this method returns
- * the composition of the two names using the syntax appropriate for the
- * naming system(s) involved. That is, if name names an object relative
- * to this context, the result is the name of the same object, but
- * relative to the ancestor context. None of the names may be null.
- *
- * @param name a name relative to this context
- * @param prefix the name of this context relative to one of its ancestors
- * @return the composition of prefix and name
- * @exception NamingException if a naming exception is encountered
- */
- public Name composeName(Name name, Name prefix)
- throws NamingException {
- prefix = (Name) prefix.clone();
- return prefix.addAll(name);
- }
-
-
- /**
- * Composes the name of this context with a name relative to this context.
- *
- * @param name a name relative to this context
- * @param prefix the name of this context relative to one of its ancestors
- * @return the composition of prefix and name
- * @exception NamingException if a naming exception is encountered
- */
- public String composeName(String name, String prefix)
- throws NamingException {
- return prefix + "/" + name;
- }
-
-
- /**
- * Adds a new environment property to the environment of this context. If
- * the property already exists, its value is overwritten.
- *
- * @param propName the name of the environment property to add; may not
- * be null
- * @param propVal the value of the property to add; may not be null
- * @exception NamingException if a naming exception is encountered
- */
- public Object addToEnvironment(String propName, Object propVal)
- throws NamingException {
- return env.put(propName, propVal);
- }
-
-
- /**
- * Removes an environment property from the environment of this context.
- *
- * @param propName the name of the environment property to remove;
- * may not be null
- * @exception NamingException if a naming exception is encountered
- */
- public Object removeFromEnvironment(String propName)
- throws NamingException {
- return env.remove(propName);
- }
-
-
- /**
- * Retrieves the environment in effect for this context. See class
- * description for more details on environment properties.
- * The caller should not make any changes to the object returned: their
- * effect on the context is undefined. The environment of this context
- * may be changed using addToEnvironment() and removeFromEnvironment().
- *
- * @return the environment of this context; never null
- * @exception NamingException if a naming exception is encountered
- */
- public Hashtable getEnvironment()
- throws NamingException {
- return env;
- }
-
-
- /**
- * Closes this context. This method releases this context's resources
- * immediately, instead of waiting for them to be released automatically
- * by the garbage collector.
- * This method is idempotent: invoking it on a context that has already
- * been closed has no effect. Invoking any other method on a closed
- * context is not allowed, and results in undefined behaviour.
- *
- * @exception NamingException if a naming exception is encountered
- */
- public void close()
- throws NamingException {
- env.clear();
- }
-
-
- /**
- * Retrieves the full name of this context within its own namespace.
- * <p>
- * Many naming services have a notion of a "full name" for objects in
- * their respective namespaces. For example, an LDAP entry has a
- * distinguished name, and a DNS record has a fully qualified name. This
- * method allows the client application to retrieve this name. The string
- * returned by this method is not a JNDI composite name and should not be
- * passed directly to context methods. In naming systems for which the
- * notion of full name does not make sense,
- * OperationNotSupportedException is thrown.
- *
- * @return this context's name in its own namespace; never null
- * @exception OperationNotSupportedException if the naming system does
- * not have the notion of a full name
- * @exception NamingException if a naming exception is encountered
- */
- public String getNameInNamespace()
- throws NamingException {
- throw new OperationNotSupportedException
- (sm.getString("namingContext.noAbsoluteName"));
- //FIXME ?
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Retrieves the named object.
- *
- * @param name the name of the object to look up
- * @param resolveLinks If true, the links will be resolved
- * @return the object bound to name
- * @exception NamingException if a naming exception is encountered
- */
- protected Object lookup(Name name, boolean resolveLinks)
- throws NamingException {
-
- // Removing empty parts
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty()) {
- // If name is empty, a newly allocated naming context is returned
- return new NamingContext(env, this.name, bindings);
- }
-
- NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
-
- if (entry == null) {
- throw new NameNotFoundException
- (sm.getString("namingContext.nameNotBound", name.get(0)));
- }
-
- if (name.size() > 1) {
- // If the size of the name is greater that 1, then we go through a
- // number of subcontexts.
- if (entry.type != NamingEntry.CONTEXT) {
- throw new NamingException
- (sm.getString("namingContext.contextExpected"));
- }
- return ((Context) entry.value).lookup(name.getSuffix(1));
- } else {
- if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) {
- String link = ((LinkRef) entry.value).getLinkName();
- if (link.startsWith(".")) {
- // Link relative to this context
- return lookup(link.substring(1));
- } else {
- return (new InitialContext(env)).lookup(link);
- }
- } else if (entry.type == NamingEntry.REFERENCE) {
- try {
- Object obj = NamingManager.getObjectInstance
- (entry.value, name, this, env);
- if (obj != null) {
- entry.value = obj;
- entry.type = NamingEntry.ENTRY;
- }
- return obj;
- } catch (NamingException e) {
- throw e;
- } catch (Exception e) {
- log.warn(sm.getString
- ("namingContext.failResolvingReference"), e);
- throw new NamingException(e.getMessage());
- }
- } else {
- return entry.value;
- }
- }
-
- }
-
-
- /**
- * Binds a name to an object. All intermediate contexts and the target
- * context (that named by all but terminal atomic component of the name)
- * must already exist.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @param rebind if true, then perform a rebind (ie, overwrite)
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- protected void bind(Name name, Object obj, boolean rebind)
- throws NamingException {
-
- checkWritable();
-
- while ((!name.isEmpty()) && (name.get(0).length() == 0))
- name = name.getSuffix(1);
- if (name.isEmpty())
- throw new NamingException
- (sm.getString("namingContext.invalidName"));
-
- NamingEntry entry = (NamingEntry) bindings.get(name.get(0));
-
- if (name.size() > 1) {
- if (entry == null) {
- throw new NameNotFoundException
- (sm.getString("namingContext.nameNotBound", name.get(0)));
- }
- if (entry.type == NamingEntry.CONTEXT) {
- if (rebind) {
- ((Context) entry.value).rebind(name.getSuffix(1), obj);
- } else {
- ((Context) entry.value).bind(name.getSuffix(1), obj);
- }
- } else {
- throw new NamingException
- (sm.getString("namingContext.contextExpected"));
- }
- } else {
- if ((!rebind) && (entry != null)) {
- throw new NameAlreadyBoundException
- (sm.getString("namingContext.alreadyBound", name.get(0)));
- } else {
- // Getting the type of the object and wrapping it within a new
- // NamingEntry
- Object toBind =
- NamingManager.getStateToBind(obj, name, this, env);
- if (toBind instanceof Context) {
- entry = new NamingEntry(name.get(0), toBind,
- NamingEntry.CONTEXT);
- } else if (toBind instanceof LinkRef) {
- entry = new NamingEntry(name.get(0), toBind,
- NamingEntry.LINK_REF);
- } else if (toBind instanceof Reference) {
- entry = new NamingEntry(name.get(0), toBind,
- NamingEntry.REFERENCE);
- } else if (toBind instanceof Referenceable) {
- toBind = ((Referenceable) toBind).getReference();
- entry = new NamingEntry(name.get(0), toBind,
- NamingEntry.REFERENCE);
- } else {
- entry = new NamingEntry(name.get(0), toBind,
- NamingEntry.ENTRY);
- }
- bindings.put(name.get(0), entry);
- }
- }
-
- }
-
-
- /**
- * Returns true if writing is allowed on this context.
- */
- protected boolean isWritable() {
- return ContextAccessController.isWritable(name);
- }
-
-
- /**
- * Throws a naming exception is Context is not writable.
- */
- protected void checkWritable()
- throws NamingException {
- if (!isWritable())
- throw new NamingException(sm.getString("namingContext.readOnly"));
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/NamingService.java
===================================================================
--- trunk/java/org/apache/naming/NamingService.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/NamingService.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,230 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import javax.naming.Context;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
-import javax.management.MBeanServer;
-import javax.management.MBeanRegistration;
-import javax.management.AttributeChangeNotification;
-import javax.management.Notification;
-
-/**
- * Implementation of the NamingService JMX MBean.
- *
- * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
- * @version $Revision$
- */
-
-public final class NamingService
- extends NotificationBroadcasterSupport
- implements NamingServiceMBean, MBeanRegistration {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Status of the Slide domain.
- */
- private int state = STOPPED;
-
-
- /**
- * Notification sequence number.
- */
- private long sequenceNumber = 0;
-
-
- /**
- * Old URL packages value.
- */
- private String oldUrlValue = "";
-
-
- /**
- * Old initial context value.
- */
- private String oldIcValue = "";
-
-
- // ---------------------------------------------- MBeanRegistration Methods
-
-
- public ObjectName preRegister(MBeanServer server, ObjectName name)
- throws Exception {
- return new ObjectName(OBJECT_NAME);
- }
-
-
- public void postRegister(Boolean registrationDone) {
- if (!registrationDone.booleanValue())
- destroy();
- }
-
-
- public void preDeregister()
- throws Exception {
- }
-
-
- public void postDeregister() {
- destroy();
- }
-
-
- // ----------------------------------------------------- SlideMBean Methods
-
-
- /**
- * Retruns the Catalina component name.
- */
- public String getName() {
- return NAME;
- }
-
-
- /**
- * Returns the state.
- */
- public int getState() {
- return state;
- }
-
-
- /**
- * Returns a String representation of the state.
- */
- public String getStateString() {
- return states[state];
- }
-
-
- /**
- * Start the servlet container.
- */
- public void start()
- throws Exception {
-
- Notification notification = null;
-
- if (state != STOPPED)
- return;
-
- state = STARTING;
-
- // Notifying the MBEan server that we're starting
-
- notification = new AttributeChangeNotification
- (this, sequenceNumber++, System.currentTimeMillis(),
- "Starting " + NAME, "State", "java.lang.Integer",
- new Integer(STOPPED), new Integer(STARTING));
- sendNotification(notification);
-
- try {
-
- String value = "org.apache.naming";
- String oldValue = System.getProperty(Context.URL_PKG_PREFIXES);
- if (oldValue != null) {
- oldUrlValue = oldValue;
- value = oldValue + ":" + value;
- }
- System.setProperty(Context.URL_PKG_PREFIXES, value);
-
- oldValue = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
- if ((oldValue != null) && (oldValue.length() > 0)) {
- oldIcValue = oldValue;
- } else {
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
- Constants.Package
- + ".java.javaURLContextFactory");
- }
-
- } catch (Throwable t) {
- state = STOPPED;
- notification = new AttributeChangeNotification
- (this, sequenceNumber++, System.currentTimeMillis(),
- "Stopped " + NAME, "State", "java.lang.Integer",
- new Integer(STARTING), new Integer(STOPPED));
- sendNotification(notification);
- }
-
- state = STARTED;
- notification = new AttributeChangeNotification
- (this, sequenceNumber++, System.currentTimeMillis(),
- "Started " + NAME, "State", "java.lang.Integer",
- new Integer(STARTING), new Integer(STARTED));
- sendNotification(notification);
-
- }
-
-
- /**
- * Stop the servlet container.
- */
- public void stop() {
-
- Notification notification = null;
-
- if (state != STARTED)
- return;
-
- state = STOPPING;
-
- notification = new AttributeChangeNotification
- (this, sequenceNumber++, System.currentTimeMillis(),
- "Stopping " + NAME, "State", "java.lang.Integer",
- new Integer(STARTED), new Integer(STOPPING));
- sendNotification(notification);
-
- try {
-
- System.setProperty(Context.URL_PKG_PREFIXES, oldUrlValue);
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY, oldIcValue);
-
- } catch (Throwable t) {
-
- // FIXME
- t.printStackTrace();
-
- }
-
- state = STOPPED;
-
- notification = new AttributeChangeNotification
- (this, sequenceNumber++, System.currentTimeMillis(),
- "Stopped " + NAME, "State", "java.lang.Integer",
- new Integer(STOPPING), new Integer(STOPPED));
- sendNotification(notification);
-
- }
-
-
- /**
- * Destroy servlet container (if any is running).
- */
- public void destroy() {
-
- if (getState() != STOPPED)
- stop();
-
- }
-
-
-}
Deleted: trunk/java/org/apache/naming/NamingServiceMBean.java
===================================================================
--- trunk/java/org/apache/naming/NamingServiceMBean.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/NamingServiceMBean.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-/**
- * Naming MBean interface.
- *
- * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
- * @version $Revision$
- */
-
-public interface NamingServiceMBean {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Status constants.
- */
- public static final String[] states =
- {"Stopped", "Stopping", "Starting", "Started"};
-
-
- public static final int STOPPED = 0;
- public static final int STOPPING = 1;
- public static final int STARTING = 2;
- public static final int STARTED = 3;
-
-
- /**
- * Component name.
- */
- public static final String NAME = "Apache JNDI Naming Service";
-
-
- /**
- * Object name.
- */
- public static final String OBJECT_NAME = ":service=Naming";
-
-
- // ------------------------------------------------------ Interface Methods
-
-
- /**
- * Retruns the JNDI component name.
- */
- public String getName();
-
-
- /**
- * Returns the state.
- */
- public int getState();
-
-
- /**
- * Returns a String representation of the state.
- */
- public String getStateString();
-
-
- /**
- * Start the servlet container.
- */
- public void start()
- throws Exception;
-
-
- /**
- * Stop the servlet container.
- */
- public void stop();
-
-
- /**
- * Destroy servlet container (if any is running).
- */
- public void destroy();
-
-
-}
Deleted: trunk/java/org/apache/naming/ResourceEnvRef.java
===================================================================
--- trunk/java/org/apache/naming/ResourceEnvRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/ResourceEnvRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import javax.naming.Context;
-import javax.naming.Reference;
-
-/**
- * Represents a reference address to a resource environment.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ResourceEnvRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_RESOURCE_ENV_FACTORY;
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Resource env reference.
- *
- * @param resourceType Type
- */
- public ResourceEnvRef(String resourceType) {
- super(resourceType);
- }
-
-
- /**
- * Resource env reference.
- *
- * @param resourceType Type
- * @param factory The factory class
- * @param factoryLocation The factory location
- */
- public ResourceEnvRef(String resourceType, String factory,
- String factoryLocation) {
- super(resourceType, factory, factoryLocation);
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/ResourceLinkRef.java
===================================================================
--- trunk/java/org/apache/naming/ResourceLinkRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/ResourceLinkRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import javax.naming.Context;
-import javax.naming.Reference;
-import javax.naming.StringRefAddr;
-
-/**
- * Represents a reference address to a resource.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ResourceLinkRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_RESOURCE_LINK_FACTORY;
-
-
- /**
- * Description address type.
- */
- public static final String GLOBALNAME = "globalName";
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * ResourceLink Reference.
- *
- * @param resourceClass Resource class
- * @param globalName Global name
- */
- public ResourceLinkRef(String resourceClass, String globalName) {
- this(resourceClass, globalName, null, null);
- }
-
-
- /**
- * ResourceLink Reference.
- *
- * @param resourceClass Resource class
- * @param globalName Global name
- */
- public ResourceLinkRef(String resourceClass, String globalName,
- String factory, String factoryLocation) {
- super(resourceClass, factory, factoryLocation);
- StringRefAddr refAddr = null;
- if (globalName != null) {
- refAddr = new StringRefAddr(GLOBALNAME, globalName);
- add(refAddr);
- }
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/ResourceRef.java
===================================================================
--- trunk/java/org/apache/naming/ResourceRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/ResourceRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,168 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.Enumeration;
-
-import javax.naming.Context;
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import javax.naming.StringRefAddr;
-
-/**
- * Represents a reference address to a resource.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ResourceRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_RESOURCE_FACTORY;
-
-
- /**
- * Description address type.
- */
- public static final String DESCRIPTION = "description";
-
-
- /**
- * Scope address type.
- */
- public static final String SCOPE = "scope";
-
-
- /**
- * Auth address type.
- */
- public static final String AUTH = "auth";
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Resource Reference.
- *
- * @param resourceClass Resource class
- * @param scope Resource scope
- * @param auth Resource authetication
- */
- public ResourceRef(String resourceClass, String description,
- String scope, String auth) {
- this(resourceClass, description, scope, auth, null, null);
- }
-
-
- /**
- * Resource Reference.
- *
- * @param resourceClass Resource class
- * @param scope Resource scope
- * @param auth Resource authetication
- */
- public ResourceRef(String resourceClass, String description,
- String scope, String auth, String factory,
- String factoryLocation) {
- super(resourceClass, factory, factoryLocation);
- StringRefAddr refAddr = null;
- if (description != null) {
- refAddr = new StringRefAddr(DESCRIPTION, description);
- add(refAddr);
- }
- if (scope != null) {
- refAddr = new StringRefAddr(SCOPE, scope);
- add(refAddr);
- }
- if (auth != null) {
- refAddr = new StringRefAddr(AUTH, auth);
- add(refAddr);
- }
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return a String rendering of this object.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("ResourceRef[");
- sb.append("className=");
- sb.append(getClassName());
- sb.append(",factoryClassLocation=");
- sb.append(getFactoryClassLocation());
- sb.append(",factoryClassName=");
- sb.append(getFactoryClassName());
- Enumeration refAddrs = getAll();
- while (refAddrs.hasMoreElements()) {
- RefAddr refAddr = (RefAddr) refAddrs.nextElement();
- sb.append(",{type=");
- sb.append(refAddr.getType());
- sb.append(",content=");
- sb.append(refAddr.getContent());
- sb.append("}");
- }
- sb.append("]");
- return (sb.toString());
-
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/SelectorContext.java
===================================================================
--- trunk/java/org/apache/naming/SelectorContext.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/SelectorContext.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,695 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.Hashtable;
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.NameParser;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-
-/**
- * Catalina JNDI Context implementation.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class SelectorContext implements Context {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Namespace URL.
- */
- public static final String prefix = "java:";
-
-
- /**
- * Namespace URL length.
- */
- public static final int prefixLength = prefix.length();
-
-
- /**
- * Initial context prefix.
- */
- public static final String IC_PREFIX = "IC_";
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Builds a Catalina selector context using the given environment.
- */
- public SelectorContext(Hashtable env) {
- this.env = env;
- }
-
-
- /**
- * Builds a Catalina selector context using the given environment.
- */
- public SelectorContext(Hashtable env, boolean initialContext) {
- this(env);
- this.initialContext = initialContext;
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Environment.
- */
- protected Hashtable env;
-
-
- /**
- * The string manager for this package.
- */
- protected StringManager sm = StringManager.getManager(Constants.Package);
-
-
- /**
- * Request for an initial context.
- */
- protected boolean initialContext = false;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------------- Context Methods
-
-
- /**
- * Retrieves the named object. If name is empty, returns a new instance
- * of this context (which represents the same naming context as this
- * context, but its environment may be modified independently and it may
- * be accessed concurrently).
- *
- * @param name the name of the object to look up
- * @return the object bound to name
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookup(Name name)
- throws NamingException {
- // Strip the URL header
- // Find the appropriate NamingContext according to the current bindings
- // Execute the lookup on that context
- return getBoundContext().lookup(parseName(name));
- }
-
-
- /**
- * Retrieves the named object.
- *
- * @param name the name of the object to look up
- * @return the object bound to name
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookup(String name)
- throws NamingException {
- // Strip the URL header
- // Find the appropriate NamingContext according to the current bindings
- // Execute the lookup on that context
- return getBoundContext().lookup(parseName(name));
- }
-
-
- /**
- * Binds a name to an object. All intermediate contexts and the target
- * context (that named by all but terminal atomic component of the name)
- * must already exist.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void bind(Name name, Object obj)
- throws NamingException {
- getBoundContext().bind(parseName(name), obj);
- }
-
-
- /**
- * Binds a name to an object.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void bind(String name, Object obj)
- throws NamingException {
- getBoundContext().bind(parseName(name), obj);
- }
-
-
- /**
- * Binds a name to an object, overwriting any existing binding. All
- * intermediate contexts and the target context (that named by all but
- * terminal atomic component of the name) must already exist.
- * <p>
- * If the object is a DirContext, any existing attributes associated with
- * the name are replaced with those of the object. Otherwise, any
- * existing attributes associated with the name remain unchanged.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void rebind(Name name, Object obj)
- throws NamingException {
- getBoundContext().rebind(parseName(name), obj);
- }
-
-
- /**
- * Binds a name to an object, overwriting any existing binding.
- *
- * @param name the name to bind; may not be empty
- * @param obj the object to bind; possibly null
- * @exception InvalidAttributesException if object did not supply all
- * mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public void rebind(String name, Object obj)
- throws NamingException {
- getBoundContext().rebind(parseName(name), obj);
- }
-
-
- /**
- * Unbinds the named object. Removes the terminal atomic name in name
- * from the target context--that named by all but the terminal atomic
- * part of name.
- * <p>
- * This method is idempotent. It succeeds even if the terminal atomic
- * name is not bound in the target context, but throws
- * NameNotFoundException if any of the intermediate contexts do not exist.
- *
- * @param name the name to bind; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NamingException if a naming exception is encountered
- */
- public void unbind(Name name)
- throws NamingException {
- getBoundContext().unbind(parseName(name));
- }
-
-
- /**
- * Unbinds the named object.
- *
- * @param name the name to bind; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NamingException if a naming exception is encountered
- */
- public void unbind(String name)
- throws NamingException {
- getBoundContext().unbind(parseName(name));
- }
-
-
- /**
- * Binds a new name to the object bound to an old name, and unbinds the
- * old name. Both names are relative to this context. Any attributes
- * associated with the old name become associated with the new name.
- * Intermediate contexts of the old name are not changed.
- *
- * @param oldName the name of the existing binding; may not be empty
- * @param newName the name of the new binding; may not be empty
- * @exception NameAlreadyBoundException if newName is already bound
- * @exception NamingException if a naming exception is encountered
- */
- public void rename(Name oldName, Name newName)
- throws NamingException {
- getBoundContext().rename(parseName(oldName), parseName(newName));
- }
-
-
- /**
- * Binds a new name to the object bound to an old name, and unbinds the
- * old name.
- *
- * @param oldName the name of the existing binding; may not be empty
- * @param newName the name of the new binding; may not be empty
- * @exception NameAlreadyBoundException if newName is already bound
- * @exception NamingException if a naming exception is encountered
- */
- public void rename(String oldName, String newName)
- throws NamingException {
- getBoundContext().rename(parseName(oldName), parseName(newName));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the class
- * names of objects bound to them. The contents of any subcontexts are
- * not included.
- * <p>
- * If a binding is added to or removed from this context, its effect on
- * an enumeration previously returned is undefined.
- *
- * @param name the name of the context to list
- * @return an enumeration of the names and class names of the bindings in
- * this context. Each element of the enumeration is of type NameClassPair.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration list(Name name)
- throws NamingException {
- return getBoundContext().list(parseName(name));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the class
- * names of objects bound to them.
- *
- * @param name the name of the context to list
- * @return an enumeration of the names and class names of the bindings in
- * this context. Each element of the enumeration is of type NameClassPair.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration list(String name)
- throws NamingException {
- return getBoundContext().list(parseName(name));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the
- * objects bound to them. The contents of any subcontexts are not
- * included.
- * <p>
- * If a binding is added to or removed from this context, its effect on
- * an enumeration previously returned is undefined.
- *
- * @param name the name of the context to list
- * @return an enumeration of the bindings in this context.
- * Each element of the enumeration is of type Binding.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration listBindings(Name name)
- throws NamingException {
- return getBoundContext().listBindings(parseName(name));
- }
-
-
- /**
- * Enumerates the names bound in the named context, along with the
- * objects bound to them.
- *
- * @param name the name of the context to list
- * @return an enumeration of the bindings in this context.
- * Each element of the enumeration is of type Binding.
- * @exception NamingException if a naming exception is encountered
- */
- public NamingEnumeration listBindings(String name)
- throws NamingException {
- return getBoundContext().listBindings(parseName(name));
- }
-
-
- /**
- * Destroys the named context and removes it from the namespace. Any
- * attributes associated with the name are also removed. Intermediate
- * contexts are not destroyed.
- * <p>
- * This method is idempotent. It succeeds even if the terminal atomic
- * name is not bound in the target context, but throws
- * NameNotFoundException if any of the intermediate contexts do not exist.
- *
- * In a federated naming system, a context from one naming system may be
- * bound to a name in another. One can subsequently look up and perform
- * operations on the foreign context using a composite name. However, an
- * attempt destroy the context using this composite name will fail with
- * NotContextException, because the foreign context is not a "subcontext"
- * of the context in which it is bound. Instead, use unbind() to remove
- * the binding of the foreign context. Destroying the foreign context
- * requires that the destroySubcontext() be performed on a context from
- * the foreign context's "native" naming system.
- *
- * @param name the name of the context to be destroyed; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NotContextException if the name is bound but does not name
- * a context, or does not name a context of the appropriate type
- */
- public void destroySubcontext(Name name)
- throws NamingException {
- getBoundContext().destroySubcontext(parseName(name));
- }
-
-
- /**
- * Destroys the named context and removes it from the namespace.
- *
- * @param name the name of the context to be destroyed; may not be empty
- * @exception NameNotFoundException if an intermediate context does not
- * exist
- * @exception NotContextException if the name is bound but does not name
- * a context, or does not name a context of the appropriate type
- */
- public void destroySubcontext(String name)
- throws NamingException {
- getBoundContext().destroySubcontext(parseName(name));
- }
-
-
- /**
- * Creates and binds a new context. Creates a new context with the given
- * name and binds it in the target context (that named by all but
- * terminal atomic component of the name). All intermediate contexts and
- * the target context must already exist.
- *
- * @param name the name of the context to create; may not be empty
- * @return the newly created context
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if creation of the subcontext
- * requires specification of mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public Context createSubcontext(Name name)
- throws NamingException {
- return getBoundContext().createSubcontext(parseName(name));
- }
-
-
- /**
- * Creates and binds a new context.
- *
- * @param name the name of the context to create; may not be empty
- * @return the newly created context
- * @exception NameAlreadyBoundException if name is already bound
- * @exception InvalidAttributesException if creation of the subcontext
- * requires specification of mandatory attributes
- * @exception NamingException if a naming exception is encountered
- */
- public Context createSubcontext(String name)
- throws NamingException {
- return getBoundContext().createSubcontext(parseName(name));
- }
-
-
- /**
- * Retrieves the named object, following links except for the terminal
- * atomic component of the name. If the object bound to name is not a
- * link, returns the object itself.
- *
- * @param name the name of the object to look up
- * @return the object bound to name, not following the terminal link
- * (if any).
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookupLink(Name name)
- throws NamingException {
- return getBoundContext().lookupLink(parseName(name));
- }
-
-
- /**
- * Retrieves the named object, following links except for the terminal
- * atomic component of the name.
- *
- * @param name the name of the object to look up
- * @return the object bound to name, not following the terminal link
- * (if any).
- * @exception NamingException if a naming exception is encountered
- */
- public Object lookupLink(String name)
- throws NamingException {
- return getBoundContext().lookupLink(parseName(name));
- }
-
-
- /**
- * Retrieves the parser associated with the named context. In a
- * federation of namespaces, different naming systems will parse names
- * differently. This method allows an application to get a parser for
- * parsing names into their atomic components using the naming convention
- * of a particular naming system. Within any single naming system,
- * NameParser objects returned by this method must be equal (using the
- * equals() test).
- *
- * @param name the name of the context from which to get the parser
- * @return a name parser that can parse compound names into their atomic
- * components
- * @exception NamingException if a naming exception is encountered
- */
- public NameParser getNameParser(Name name)
- throws NamingException {
- return getBoundContext().getNameParser(parseName(name));
- }
-
-
- /**
- * Retrieves the parser associated with the named context.
- *
- * @param name the name of the context from which to get the parser
- * @return a name parser that can parse compound names into their atomic
- * components
- * @exception NamingException if a naming exception is encountered
- */
- public NameParser getNameParser(String name)
- throws NamingException {
- return getBoundContext().getNameParser(parseName(name));
- }
-
-
- /**
- * Composes the name of this context with a name relative to this context.
- * <p>
- * Given a name (name) relative to this context, and the name (prefix)
- * of this context relative to one of its ancestors, this method returns
- * the composition of the two names using the syntax appropriate for the
- * naming system(s) involved. That is, if name names an object relative
- * to this context, the result is the name of the same object, but
- * relative to the ancestor context. None of the names may be null.
- *
- * @param name a name relative to this context
- * @param prefix the name of this context relative to one of its ancestors
- * @return the composition of prefix and name
- * @exception NamingException if a naming exception is encountered
- */
- public Name composeName(Name name, Name prefix)
- throws NamingException {
- prefix = (Name) prefix.clone();
- return prefix.addAll(name);
- }
-
-
- /**
- * Composes the name of this context with a name relative to this context.
- *
- * @param name a name relative to this context
- * @param prefix the name of this context relative to one of its ancestors
- * @return the composition of prefix and name
- * @exception NamingException if a naming exception is encountered
- */
- public String composeName(String name, String prefix)
- throws NamingException {
- return prefix + "/" + name;
- }
-
-
- /**
- * Adds a new environment property to the environment of this context. If
- * the property already exists, its value is overwritten.
- *
- * @param propName the name of the environment property to add; may not
- * be null
- * @param propVal the value of the property to add; may not be null
- * @exception NamingException if a naming exception is encountered
- */
- public Object addToEnvironment(String propName, Object propVal)
- throws NamingException {
- return getBoundContext().addToEnvironment(propName, propVal);
- }
-
-
- /**
- * Removes an environment property from the environment of this context.
- *
- * @param propName the name of the environment property to remove;
- * may not be null
- * @exception NamingException if a naming exception is encountered
- */
- public Object removeFromEnvironment(String propName)
- throws NamingException {
- return getBoundContext().removeFromEnvironment(propName);
- }
-
-
- /**
- * Retrieves the environment in effect for this context. See class
- * description for more details on environment properties.
- * The caller should not make any changes to the object returned: their
- * effect on the context is undefined. The environment of this context
- * may be changed using addToEnvironment() and removeFromEnvironment().
- *
- * @return the environment of this context; never null
- * @exception NamingException if a naming exception is encountered
- */
- public Hashtable getEnvironment()
- throws NamingException {
- return getBoundContext().getEnvironment();
- }
-
-
- /**
- * Closes this context. This method releases this context's resources
- * immediately, instead of waiting for them to be released automatically
- * by the garbage collector.
- * This method is idempotent: invoking it on a context that has already
- * been closed has no effect. Invoking any other method on a closed
- * context is not allowed, and results in undefined behaviour.
- *
- * @exception NamingException if a naming exception is encountered
- */
- public void close()
- throws NamingException {
- getBoundContext().close();
- }
-
-
- /**
- * Retrieves the full name of this context within its own namespace.
- * <p>
- * Many naming services have a notion of a "full name" for objects in
- * their respective namespaces. For example, an LDAP entry has a
- * distinguished name, and a DNS record has a fully qualified name. This
- * method allows the client application to retrieve this name. The string
- * returned by this method is not a JNDI composite name and should not be
- * passed directly to context methods. In naming systems for which the
- * notion of full name does not make sense,
- * OperationNotSupportedException is thrown.
- *
- * @return this context's name in its own namespace; never null
- * @exception OperationNotSupportedException if the naming system does
- * not have the notion of a full name
- * @exception NamingException if a naming exception is encountered
- */
- public String getNameInNamespace()
- throws NamingException {
- return prefix;
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Get the bound context.
- */
- protected Context getBoundContext()
- throws NamingException {
-
- if (initialContext) {
- String ICName = IC_PREFIX;
- if (ContextBindings.isThreadBound()) {
- ICName += ContextBindings.getThreadName();
- } else if (ContextBindings.isClassLoaderBound()) {
- ICName += ContextBindings.getClassLoaderName();
- }
- Context initialContext = ContextBindings.getContext(ICName);
- if (initialContext == null) {
- // Allocating a new context and binding it to the appropriate
- // name
- initialContext = new NamingContext(env, ICName);
- ContextBindings.bindContext(ICName, initialContext);
- }
- return initialContext;
- } else {
- if (ContextBindings.isThreadBound()) {
- return ContextBindings.getThread();
- } else {
- return ContextBindings.getClassLoader();
- }
- }
-
- }
-
-
- /**
- * Strips the URL header.
- *
- * @return the parsed name
- * @exception NamingException if there is no "java:" header or if no
- * naming context has been bound to this thread
- */
- protected String parseName(String name)
- throws NamingException {
-
- if ((!initialContext) && (name.startsWith(prefix))) {
- return (name.substring(prefixLength));
- } else {
- if (initialContext) {
- return (name);
- } else {
- throw new NamingException
- (sm.getString("selectorContext.noJavaUrl"));
- }
- }
-
- }
-
-
- /**
- * Strips the URL header.
- *
- * @return the parsed name
- * @exception NamingException if there is no "java:" header or if no
- * naming context has been bound to this thread
- */
- protected Name parseName(Name name)
- throws NamingException {
-
- if ((!initialContext) && (!name.isEmpty())
- && (name.get(0).equals(prefix))) {
- return (name.getSuffix(1));
- } else {
- if (initialContext) {
- return (name);
- } else {
- throw new NamingException
- (sm.getString("selectorContext.noJavaUrl"));
- }
- }
-
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/ServiceRef.java
===================================================================
--- trunk/java/org/apache/naming/ServiceRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/ServiceRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,216 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import java.util.Enumeration;
-import java.util.Vector;
-
-import javax.naming.Context;
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import javax.naming.StringRefAddr;
-
-/**
- * Represents a reference web service.
- *
- * @author Fabien Carrion
- */
-
-public class ServiceRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_SERVICE_FACTORY;
-
-
- /**
- * Service Classname address type.
- */
- public static final String SERVICE_INTERFACE = "serviceInterface";
-
-
- /**
- * ServiceQname address type.
- */
- public static final String SERVICE_NAMESPACE = "service namespace";
- public static final String SERVICE_LOCAL_PART = "service local part";
-
-
- /**
- * Wsdl Location address type.
- */
- public static final String WSDL = "wsdl";
-
-
- /**
- * Jaxrpcmapping address type.
- */
- public static final String JAXRPCMAPPING = "jaxrpcmapping";
-
-
- /**
- * port-component-ref/port-component-link address type.
- */
- public static final String PORTCOMPONENTLINK = "portcomponentlink";
-
-
- /**
- * port-component-ref/service-endpoint-interface address type.
- */
- public static final String SERVICEENDPOINTINTERFACE = "serviceendpointinterface";
-
-
- /**
- * The vector to save the handler Reference objects, because they can't be saved in the addrs vector.
- */
- private Vector<HandlerRef> handlers = new Vector<HandlerRef>();
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Service Reference.
- *
- * @param serviceClass Service class
- */
- public ServiceRef(String refname, String serviceInterface, String[] serviceQname,
- String wsdl, String jaxrpcmapping) {
- this(refname, serviceInterface, serviceQname, wsdl, jaxrpcmapping,
- null, null);
- }
-
-
- /**
- * Service Reference.
- *
- * @param serviceClass Service class
- */
- public ServiceRef(String refname, String serviceInterface, String[] serviceQname,
- String wsdl, String jaxrpcmapping,
- String factory, String factoryLocation) {
- super(serviceInterface, factory, factoryLocation);
- StringRefAddr refAddr = null;
- if (serviceInterface != null) {
- refAddr = new StringRefAddr(SERVICE_INTERFACE, serviceInterface);
- add(refAddr);
- }
- if (serviceQname[0] != null) {
- refAddr = new StringRefAddr(SERVICE_NAMESPACE, serviceQname[0]);
- add(refAddr);
- }
- if (serviceQname[1] != null) {
- refAddr = new StringRefAddr(SERVICE_LOCAL_PART, serviceQname[1]);
- add(refAddr);
- }
- if (wsdl != null) {
- refAddr = new StringRefAddr(WSDL, wsdl);
- add(refAddr);
- }
- if (jaxrpcmapping != null) {
- refAddr = new StringRefAddr(JAXRPCMAPPING, jaxrpcmapping);
- add(refAddr);
- }
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Add and Get Handlers classes.
- */
- public HandlerRef getHandler() {
- return handlers.remove(0);
- }
-
-
- public int getHandlersSize() {
- return handlers.size();
- }
-
-
- public void addHandler(HandlerRef handler) {
- handlers.add(handler);
- }
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Return a String rendering of this object.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("ServiceRef[");
- sb.append("className=");
- sb.append(getClassName());
- sb.append(",factoryClassLocation=");
- sb.append(getFactoryClassLocation());
- sb.append(",factoryClassName=");
- sb.append(getFactoryClassName());
- Enumeration refAddrs = getAll();
- while (refAddrs.hasMoreElements()) {
- RefAddr refAddr = (RefAddr) refAddrs.nextElement();
- sb.append(",{type=");
- sb.append(refAddr.getType());
- sb.append(",content=");
- sb.append(refAddr.getContent());
- sb.append("}");
- }
- sb.append("]");
- return (sb.toString());
-
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/TransactionRef.java
===================================================================
--- trunk/java/org/apache/naming/TransactionRef.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/TransactionRef.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming;
-
-import javax.naming.Context;
-import javax.naming.Reference;
-
-/**
- * Represents a reference address to a transaction.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class TransactionRef
- extends Reference {
-
-
- // -------------------------------------------------------------- Constants
-
-
- /**
- * Default factory for this reference.
- */
- public static final String DEFAULT_FACTORY =
- org.apache.naming.factory.Constants.DEFAULT_TRANSACTION_FACTORY;
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Resource Reference.
- */
- public TransactionRef() {
- this(null, null);
- }
-
-
- /**
- * Resource Reference.
- *
- * @param factory The factory class
- * @param factoryLocation The factory location
- */
- public TransactionRef(String factory, String factoryLocation) {
- super("javax.transaction.UserTransaction", factory, factoryLocation);
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // ------------------------------------------------------ Reference Methods
-
-
- /**
- * Retrieves the class name of the factory of the object to which this
- * reference refers.
- */
- public String getFactoryClassName() {
- String factory = super.getFactoryClassName();
- if (factory != null) {
- return factory;
- } else {
- factory = System.getProperty(Context.OBJECT_FACTORIES);
- if (factory != null) {
- return null;
- } else {
- return DEFAULT_FACTORY;
- }
- }
- }
-
-
- // ------------------------------------------------------------- Properties
-
-
-}
Deleted: trunk/java/org/apache/naming/factory/BeanFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/BeanFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/BeanFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,246 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import java.util.Hashtable;
-import java.util.Enumeration;
-import javax.naming.Name;
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import javax.naming.spi.ObjectFactory;
-import org.apache.naming.ResourceRef;
-
-import java.beans.Introspector;
-import java.beans.BeanInfo;
-import java.beans.PropertyDescriptor;
-
-import java.lang.reflect.Method;
-
-/**
- * Object factory for any Resource conforming to the JavaBean spec.
- *
- * <p>This factory can be configured in a <code><DefaultContext></code>
- * or <code><Context></code> element in your <code>conf/server.xml</code>
- * configuration file. An example of factory configuration is:</p>
- * <pre>
- * <Resource name="jdbc/myDataSource" auth="SERVLET"
- * type="oracle.jdbc.pool.OracleConnectionCacheImpl"/>
- * <ResourceParams name="jdbc/myDataSource">
- * <parameter>
- * <name>factory</name>
- * <value>org.apache.naming.factory.BeanFactory</value>
- * </parameter>
- * <parameter>
- * <name>driverType</name>
- * <value>thin</value>
- * </parameter>
- * <parameter>
- * <name>serverName</name>
- * <value>hue</value>
- * </parameter>
- * <parameter>
- * <name>networkProtocol</name>
- * <value>tcp</value>
- * </parameter>
- * <parameter>
- * <name>databaseName</name>
- * <value>XXXX</value>
- * </parameter>
- * <parameter>
- * <name>portNumber</name>
- * <value>NNNN</value>
- * </parameter>
- * <parameter>
- * <name>user</name>
- * <value>XXXX</value>
- * </parameter>
- * <parameter>
- * <name>password</name>
- * <value>XXXX</value>
- * </parameter>
- * <parameter>
- * <name>maxLimit</name>
- * <value>5</value>
- * </parameter>
- * </ResourceParams>
- * </pre>
- *
- * @author <a href="mailto:aner at ncstech.com">Aner Perez</a>
- */
-public class BeanFactory
- implements ObjectFactory {
-
- // ----------------------------------------------------------- Constructors
-
-
- // -------------------------------------------------------------- Constants
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Create a new Bean instance.
- *
- * @param obj The reference object describing the Bean
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws NamingException {
-
- if (obj instanceof ResourceRef) {
-
- try {
-
- Reference ref = (Reference) obj;
- String beanClassName = ref.getClassName();
- Class beanClass = null;
- ClassLoader tcl =
- Thread.currentThread().getContextClassLoader();
- if (tcl != null) {
- try {
- beanClass = tcl.loadClass(beanClassName);
- } catch(ClassNotFoundException e) {
- }
- } else {
- try {
- beanClass = Class.forName(beanClassName);
- } catch(ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- if (beanClass == null) {
- throw new NamingException
- ("Class not found: " + beanClassName);
- }
-
- BeanInfo bi = Introspector.getBeanInfo(beanClass);
- PropertyDescriptor[] pda = bi.getPropertyDescriptors();
-
- Object bean = beanClass.newInstance();
-
- Enumeration e = ref.getAll();
- while (e.hasMoreElements()) {
-
- RefAddr ra = (RefAddr) e.nextElement();
- String propName = ra.getType();
-
- if (propName.equals(Constants.FACTORY) ||
- propName.equals("scope") || propName.equals("auth")) {
- continue;
- }
-
- String value = (String)ra.getContent();
-
- Object[] valueArray = new Object[1];
-
- int i = 0;
- for (i = 0; i<pda.length; i++) {
-
- if (pda[i].getName().equals(propName)) {
-
- Class propType = pda[i].getPropertyType();
-
- if (propType.equals(String.class)) {
- valueArray[0] = value;
- } else if (propType.equals(Character.class)
- || propType.equals(char.class)) {
- valueArray[0] = new Character(value.charAt(0));
- } else if (propType.equals(Byte.class)
- || propType.equals(byte.class)) {
- valueArray[0] = new Byte(value);
- } else if (propType.equals(Short.class)
- || propType.equals(short.class)) {
- valueArray[0] = new Short(value);
- } else if (propType.equals(Integer.class)
- || propType.equals(int.class)) {
- valueArray[0] = new Integer(value);
- } else if (propType.equals(Long.class)
- || propType.equals(long.class)) {
- valueArray[0] = new Long(value);
- } else if (propType.equals(Float.class)
- || propType.equals(float.class)) {
- valueArray[0] = new Float(value);
- } else if (propType.equals(Double.class)
- || propType.equals(double.class)) {
- valueArray[0] = new Double(value);
- } else if (propType.equals(Boolean.class)
- || propType.equals(boolean.class)) {
- valueArray[0] = new Boolean(value);
- } else {
- throw new NamingException
- ("String conversion for property type '"
- + propType.getName() + "' not available");
- }
-
- Method setProp = pda[i].getWriteMethod();
- if (setProp != null) {
- setProp.invoke(bean, valueArray);
- } else {
- throw new NamingException
- ("Write not allowed for property: "
- + propName);
- }
-
- break;
-
- }
-
- }
-
- if (i == pda.length) {
- throw new NamingException
- ("No set method found for property: " + propName);
- }
-
- }
-
- return bean;
-
- } catch (java.beans.IntrospectionException ie) {
- NamingException ne = new NamingException(ie.getMessage());
- ne.setRootCause(ie);
- throw ne;
- } catch (java.lang.IllegalAccessException iae) {
- NamingException ne = new NamingException(iae.getMessage());
- ne.setRootCause(iae);
- throw ne;
- } catch (java.lang.InstantiationException ie2) {
- NamingException ne = new NamingException(ie2.getMessage());
- ne.setRootCause(ie2);
- throw ne;
- } catch (java.lang.reflect.InvocationTargetException ite) {
- NamingException ne = new NamingException(ite.getMessage());
- ne.setRootCause(ite);
- throw ne;
- }
-
- } else {
- return null;
- }
-
- }
-}
Deleted: trunk/java/org/apache/naming/factory/Constants.java
===================================================================
--- trunk/java/org/apache/naming/factory/Constants.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/Constants.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-
-/**
- * Static constants for this package.
- */
-
-public final class Constants {
-
- public static final String Package = "org.apache.naming.factory";
-
- public static final String DEFAULT_RESOURCE_FACTORY =
- Package + ".ResourceFactory";
-
- public static final String DEFAULT_RESOURCE_LINK_FACTORY =
- Package + ".ResourceLinkFactory";
-
- public static final String DEFAULT_TRANSACTION_FACTORY =
- Package + ".TransactionFactory";
-
- public static final String DEFAULT_RESOURCE_ENV_FACTORY =
- Package + ".ResourceEnvFactory";
-
- public static final String DEFAULT_EJB_FACTORY =
- Package + ".EjbFactory";
-
- public static final String DEFAULT_SERVICE_FACTORY =
- Package + ".webservices.ServiceRefFactory";
-
- public static final String DEFAULT_HANDLER_FACTORY =
- Package + ".HandlerFactory";
-
- public static final String DBCP_DATASOURCE_FACTORY =
- "org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory";
-
- public static final String OPENEJB_EJB_FACTORY =
- Package + ".OpenEjbFactory";
-
- public static final String OBJECT_FACTORIES = "";
-
- public static final String FACTORY = "factory";
-
-}
Deleted: trunk/java/org/apache/naming/factory/EjbFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/EjbFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/EjbFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,176 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import java.util.Hashtable;
-import javax.naming.Name;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import javax.naming.spi.ObjectFactory;
-import org.apache.naming.EjbRef;
-
-/**
- * Object factory for EJBs.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class EjbFactory
- implements ObjectFactory {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- // -------------------------------------------------------------- Constants
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Crete a new EJB instance.
- *
- * @param obj The reference object describing the DataSource
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws Exception {
-
- if (obj instanceof EjbRef) {
- Reference ref = (Reference) obj;
-
- // If ejb-link has been specified, resolving the link using JNDI
- RefAddr linkRefAddr = ref.get(EjbRef.LINK);
- if (linkRefAddr != null) {
- // Retrieving the EJB link
- String ejbLink = linkRefAddr.getContent().toString();
- Object beanObj = (new InitialContext()).lookup(ejbLink);
- // Load home interface and checking if bean correctly
- // implements specified home interface
- /*
- String homeClassName = ref.getClassName();
- try {
- Class home = Class.forName(homeClassName);
- if (home.isInstance(beanObj)) {
- System.out.println("Bean of type "
- + beanObj.getClass().getName()
- + " implements home interface "
- + home.getName());
- } else {
- System.out.println("Bean of type "
- + beanObj.getClass().getName()
- + " doesn't implement home interface "
- + home.getName());
- throw new NamingException
- ("Bean of type " + beanObj.getClass().getName()
- + " doesn't implement home interface "
- + home.getName());
- }
- } catch (ClassNotFoundException e) {
- System.out.println("Couldn't load home interface "
- + homeClassName);
- }
- */
- return beanObj;
- }
-
- ObjectFactory factory = null;
- RefAddr factoryRefAddr = ref.get(Constants.FACTORY);
- if (factoryRefAddr != null) {
- // Using the specified factory
- String factoryClassName =
- factoryRefAddr.getContent().toString();
- // Loading factory
- ClassLoader tcl =
- Thread.currentThread().getContextClassLoader();
- Class factoryClass = null;
- if (tcl != null) {
- try {
- factoryClass = tcl.loadClass(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- } else {
- try {
- factoryClass = Class.forName(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- }
- if (factoryClass != null) {
- try {
- factory = (ObjectFactory) factoryClass.newInstance();
- } catch(Throwable t) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(t);
- throw ex;
- }
- }
- } else {
- String javaxEjbFactoryClassName =
- System.getProperty("javax.ejb.Factory",
- Constants.OPENEJB_EJB_FACTORY);
- try {
- factory = (ObjectFactory)
- Class.forName(javaxEjbFactoryClassName).newInstance();
- } catch(Throwable t) {
- if (t instanceof NamingException)
- throw (NamingException) t;
- NamingException ex = new NamingException
- ("Could not create resource factory instance");
- ex.initCause(t);
- throw ex;
- }
- }
-
- if (factory != null) {
- return factory.getObjectInstance
- (obj, name, nameCtx, environment);
- } else {
- throw new NamingException
- ("Cannot create resource instance");
- }
-
- }
-
- return null;
-
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/factory/OpenEjbFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/OpenEjbFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/OpenEjbFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,90 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import org.apache.naming.EjbRef;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.Name;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import javax.naming.spi.ObjectFactory;
-import java.util.Hashtable;
-import java.util.Properties;
-
-/**
- * Object factory for EJBs.
- *
- * @author Jacek Laskowski
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-public class OpenEjbFactory implements ObjectFactory {
-
-
- // -------------------------------------------------------------- Constants
-
-
- protected static final String DEFAULT_OPENEJB_FACTORY =
- "org.openejb.client.LocalInitialContextFactory";
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Crete a new EJB instance using OpenEJB.
- *
- * @param obj The reference object describing the DataSource
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws Exception {
-
- Object beanObj = null;
-
- if (obj instanceof EjbRef) {
-
- Reference ref = (Reference) obj;
-
- String factory = DEFAULT_OPENEJB_FACTORY;
- RefAddr factoryRefAddr = ref.get("openejb.factory");
- if (factoryRefAddr != null) {
- // Retrieving the OpenEJB factory
- factory = factoryRefAddr.getContent().toString();
- }
-
- Properties env = new Properties();
- env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
-
- RefAddr linkRefAddr = ref.get("openejb.link");
- if (linkRefAddr != null) {
- String ejbLink = linkRefAddr.getContent().toString();
- beanObj = (new InitialContext(env)).lookup(ejbLink);
- }
-
- }
-
- return beanObj;
-
- }
-
-
-}
Deleted: trunk/java/org/apache/naming/factory/ResourceEnvFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/ResourceEnvFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/ResourceEnvFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import java.util.Hashtable;
-import javax.naming.Name;
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import javax.naming.spi.ObjectFactory;
-import org.apache.naming.ResourceEnvRef;
-
-/**
- * Object factory for Resources env.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ResourceEnvFactory
- implements ObjectFactory {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- // -------------------------------------------------------------- Constants
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Crete a new Resource env instance.
- *
- * @param obj The reference object describing the DataSource
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws Exception {
-
- if (obj instanceof ResourceEnvRef) {
- Reference ref = (Reference) obj;
- ObjectFactory factory = null;
- RefAddr factoryRefAddr = ref.get(Constants.FACTORY);
- if (factoryRefAddr != null) {
- // Using the specified factory
- String factoryClassName =
- factoryRefAddr.getContent().toString();
- // Loading factory
- ClassLoader tcl =
- Thread.currentThread().getContextClassLoader();
- Class factoryClass = null;
- if (tcl != null) {
- try {
- factoryClass = tcl.loadClass(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- } else {
- try {
- factoryClass = Class.forName(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- }
- if (factoryClass != null) {
- try {
- factory = (ObjectFactory) factoryClass.newInstance();
- } catch(Throwable t) {
- if (t instanceof NamingException)
- throw (NamingException) t;
- NamingException ex = new NamingException
- ("Could not create resource factory instance");
- ex.initCause(t);
- throw ex;
- }
- }
- }
- // Note: No defaults here
- if (factory != null) {
- return factory.getObjectInstance
- (obj, name, nameCtx, environment);
- } else {
- throw new NamingException
- ("Cannot create resource instance");
- }
- }
-
- return null;
-
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/factory/ResourceFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/ResourceFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/ResourceFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import java.util.Hashtable;
-import javax.naming.Name;
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import javax.naming.spi.ObjectFactory;
-import org.apache.naming.ResourceRef;
-
-/**
- * Object factory for Resources.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ResourceFactory
- implements ObjectFactory {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- // -------------------------------------------------------------- Constants
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Crete a new DataSource instance.
- *
- * @param obj The reference object describing the DataSource
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws Exception {
-
- if (obj instanceof ResourceRef) {
- Reference ref = (Reference) obj;
- ObjectFactory factory = null;
- RefAddr factoryRefAddr = ref.get(Constants.FACTORY);
- if (factoryRefAddr != null) {
- // Using the specified factory
- String factoryClassName =
- factoryRefAddr.getContent().toString();
- // Loading factory
- ClassLoader tcl =
- Thread.currentThread().getContextClassLoader();
- Class factoryClass = null;
- if (tcl != null) {
- try {
- factoryClass = tcl.loadClass(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- } else {
- try {
- factoryClass = Class.forName(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- }
- if (factoryClass != null) {
- try {
- factory = (ObjectFactory) factoryClass.newInstance();
- } catch (Throwable t) {
- if (t instanceof NamingException)
- throw (NamingException) t;
- NamingException ex = new NamingException
- ("Could not create resource factory instance");
- ex.initCause(t);
- throw ex;
- }
- }
- } else {
- if (ref.getClassName().equals("javax.sql.DataSource")) {
- String javaxSqlDataSourceFactoryClassName =
- System.getProperty("javax.sql.DataSource.Factory",
- Constants.DBCP_DATASOURCE_FACTORY);
- try {
- factory = (ObjectFactory)
- Class.forName(javaxSqlDataSourceFactoryClassName)
- .newInstance();
- } catch (Throwable t) {
- NamingException ex = new NamingException
- ("Could not create resource factory instance");
- ex.initCause(t);
- throw ex;
- }
- } else if (ref.getClassName().equals("javax.mail.Session")) {
- String javaxMailSessionFactoryClassName =
- System.getProperty("javax.mail.Session.Factory",
- "org.apache.naming.factory.MailSessionFactory");
- try {
- factory = (ObjectFactory)
- Class.forName(javaxMailSessionFactoryClassName)
- .newInstance();
- } catch(Throwable t) {
- NamingException ex = new NamingException
- ("Could not create resource factory instance");
- ex.initCause(t);
- throw ex;
- }
- }
- }
- if (factory != null) {
- return factory.getObjectInstance
- (obj, name, nameCtx, environment);
- } else {
- throw new NamingException
- ("Cannot create resource instance");
- }
- }
-
- return null;
-
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/factory/ResourceLinkFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/ResourceLinkFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/ResourceLinkFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import java.util.Hashtable;
-
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.NamingException;
-import javax.naming.RefAddr;
-import javax.naming.Reference;
-import javax.naming.spi.ObjectFactory;
-
-import org.apache.naming.ResourceLinkRef;
-
-
-/**
- * <p>Object factory for resource links.</p>
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class ResourceLinkFactory
- implements ObjectFactory {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- // ------------------------------------------------------- Static Variables
-
-
- /**
- * Global naming context.
- */
- private static Context globalContext = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Set the global context (note: can only be used once).
- *
- * @param newGlobalContext new global context value
- */
- public static void setGlobalContext(Context newGlobalContext) {
- if (globalContext != null)
- return;
- globalContext = newGlobalContext;
- }
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Create a new DataSource instance.
- *
- * @param obj The reference object describing the DataSource
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws NamingException {
-
- if (!(obj instanceof ResourceLinkRef))
- return null;
-
- // Can we process this request?
- Reference ref = (Reference) obj;
-
- String type = ref.getClassName();
-
- // Read the global ref addr
- String globalName = null;
- RefAddr refAddr = ref.get(ResourceLinkRef.GLOBALNAME);
- if (refAddr != null) {
- globalName = refAddr.getContent().toString();
- Object result = null;
- result = globalContext.lookup(globalName);
- // FIXME: Check type
- return result;
- }
-
- return (null);
-
-
- }
-
-
-}
Deleted: trunk/java/org/apache/naming/factory/TransactionFactory.java
===================================================================
--- trunk/java/org/apache/naming/factory/TransactionFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/TransactionFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.factory;
-
-import java.util.Hashtable;
-import javax.naming.Name;
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import javax.naming.spi.ObjectFactory;
-import org.apache.naming.TransactionRef;
-
-/**
- * Object factory for User trasactions.
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class TransactionFactory
- implements ObjectFactory {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- // -------------------------------------------------------------- Constants
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Crete a new User transaction instance.
- *
- * @param obj The reference object describing the DataSource
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws Exception {
-
- if (obj instanceof TransactionRef) {
- Reference ref = (Reference) obj;
- ObjectFactory factory = null;
- RefAddr factoryRefAddr = ref.get(Constants.FACTORY);
- if (factoryRefAddr != null) {
- // Using the specified factory
- String factoryClassName =
- factoryRefAddr.getContent().toString();
- // Loading factory
- ClassLoader tcl =
- Thread.currentThread().getContextClassLoader();
- Class factoryClass = null;
- if (tcl != null) {
- try {
- factoryClass = tcl.loadClass(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- } else {
- try {
- factoryClass = Class.forName(factoryClassName);
- } catch(ClassNotFoundException e) {
- NamingException ex = new NamingException
- ("Could not load resource factory class");
- ex.initCause(e);
- throw ex;
- }
- }
- if (factoryClass != null) {
- try {
- factory = (ObjectFactory) factoryClass.newInstance();
- } catch(Throwable t) {
- if (t instanceof NamingException)
- throw (NamingException) t;
- NamingException ex = new NamingException
- ("Could not create resource factory instance");
- ex.initCause(t);
- throw ex;
- }
- }
- }
- if (factory != null) {
- return factory.getObjectInstance
- (obj, name, nameCtx, environment);
- } else {
- throw new NamingException
- ("Cannot create resource instance");
- }
-
- }
-
- return null;
-
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/factory/package.html
===================================================================
--- trunk/java/org/apache/naming/factory/package.html 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/factory/package.html 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,7 +0,0 @@
-<body>
-
-<p>This package contains object factories used by the naming service.</p>
-
-<p></p>
-
-</body>
Deleted: trunk/java/org/apache/naming/java/javaURLContextFactory.java
===================================================================
--- trunk/java/org/apache/naming/java/javaURLContextFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/java/javaURLContextFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,112 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.naming.java;
-
-import java.util.Hashtable;
-import javax.naming.Name;
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.spi.ObjectFactory;
-import javax.naming.spi.InitialContextFactory;
-import org.apache.naming.SelectorContext;
-import org.apache.naming.NamingContext;
-import org.apache.naming.ContextBindings;
-
-/**
- * Context factory for the "java:" namespace.
- * <p>
- * <b>Important note</b> : This factory MUST be associated with the "java" URL
- * prefix, which can be done by either :
- * <ul>
- * <li>Adding a
- * java.naming.factory.url.pkgs=org.apache.catalina.util.naming property
- * to the JNDI properties file</li>
- * <li>Setting an environment variable named Context.URL_PKG_PREFIXES with
- * its value including the org.apache.catalina.util.naming package name.
- * More detail about this can be found in the JNDI documentation :
- * {@link javax.naming.spi.NamingManager#getURLContext(java.lang.String, java.util.Hashtable)}.</li>
- * </ul>
- *
- * @author Remy Maucherat
- * @version $Revision$ $Date$
- */
-
-public class javaURLContextFactory
- implements ObjectFactory, InitialContextFactory {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- // -------------------------------------------------------------- Constants
-
-
- public static final String MAIN = "initialContext";
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * Initial context.
- */
- protected static Context initialContext = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- // -------------------------------------------------- ObjectFactory Methods
-
-
- /**
- * Crete a new Context's instance.
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment)
- throws NamingException {
- if ((ContextBindings.isThreadBound()) ||
- (ContextBindings.isClassLoaderBound())) {
- return new SelectorContext(environment);
- } else {
- return null;
- }
- }
-
-
- /**
- * Get a new (writable) initial context.
- */
- public Context getInitialContext(Hashtable environment)
- throws NamingException {
- if (ContextBindings.isThreadBound() ||
- (ContextBindings.isClassLoaderBound())) {
- // Redirect the request to the bound initial context
- return new SelectorContext(environment, true);
- } else {
- // If the thread is not bound, return a shared writable context
- if (initialContext == null)
- initialContext = new NamingContext(environment, MAIN);
- return initialContext;
- }
- }
-
-
-}
-
Deleted: trunk/java/org/apache/naming/java/package.html
===================================================================
--- trunk/java/org/apache/naming/java/package.html 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/naming/java/package.html 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,7 +0,0 @@
-<body>
-
-<p>This package contains the URL context factory for the "java" namespace.</p>
-
-<p></p>
-
-</body>
Deleted: trunk/java/org/apache/tomcat/util/digester/AbstractObjectCreationFactory.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/AbstractObjectCreationFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/AbstractObjectCreationFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,79 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.xml.sax.Attributes;
-
-
-/**
- * <p>Abstract base class for <code>ObjectCreationFactory</code>
- * implementations.</p>
- */
-abstract public class AbstractObjectCreationFactory implements ObjectCreationFactory {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The associated <code>Digester</code> instance that was set up by
- * {@link FactoryCreateRule} upon initialization.
- */
- protected Digester digester = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * <p>Factory method called by {@link FactoryCreateRule} to supply an
- * object based on the element's attributes.
- *
- * @param attributes the element's attributes
- *
- * @throws Exception any exception thrown will be propagated upwards
- */
- public abstract Object createObject(Attributes attributes) throws Exception;
-
-
- /**
- * <p>Returns the {@link Digester} that was set by the
- * {@link FactoryCreateRule} upon initialization.
- */
- public Digester getDigester() {
-
- return (this.digester);
-
- }
-
-
- /**
- * <p>Set the {@link Digester} to allow the implementation to do logging,
- * classloading based on the digester's classloader, etc.
- *
- * @param digester parent Digester object
- */
- public void setDigester(Digester digester) {
-
- this.digester = digester;
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/AbstractRulesImpl.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/AbstractRulesImpl.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/AbstractRulesImpl.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,167 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import java.util.List;
-
-
-/**
- * <p><code>AbstractRuleImpl</code> provides basic services for <code>Rules</code> implementations.
- * Extending this class should make it easier to create a <code>Rules</code> implementation.</p>
- *
- * <p><code>AbstractRuleImpl</code> manages the <code>Digester</code>
- * and <code>namespaceUri</code> properties.
- * If the subclass overrides {@link #registerRule} (rather than {@link #add}),
- * then the <code>Digester</code> and <code>namespaceURI</code> of the <code>Rule</code>
- * will be set correctly before it is passed to <code>registerRule</code>.
- * The subclass can then perform whatever it needs to do to register the rule.</p>
- *
- * @since 1.5
- */
-
-abstract public class AbstractRulesImpl implements Rules {
-
- // ------------------------------------------------------------- Fields
-
- /** Digester using this <code>Rules</code> implementation */
- private Digester digester;
- /** Namespace uri to assoicate with subsequent <code>Rule</code>'s */
- private String namespaceURI;
-
- // ------------------------------------------------------------- Properties
-
- /**
- * Return the Digester instance with which this Rules instance is
- * associated.
- */
- public Digester getDigester() {
- return digester;
- }
-
- /**
- * Set the Digester instance with which this Rules instance is associated.
- *
- * @param digester The newly associated Digester instance
- */
- public void setDigester(Digester digester) {
- this.digester = digester;
- }
-
- /**
- * Return the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- */
- public String getNamespaceURI() {
- return namespaceURI;
- }
-
- /**
- * Set the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- *
- * @param namespaceURI Namespace URI that must match on all
- * subsequently added rules, or <code>null</code> for matching
- * regardless of the current namespace URI
- */
- public void setNamespaceURI(String namespaceURI) {
- this.namespaceURI = namespaceURI;
- }
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * Registers a new Rule instance matching the specified pattern.
- * This implementation sets the <code>Digester</code> and the
- * <code>namespaceURI</code> on the <code>Rule</code> before calling {@link #registerRule}.
- *
- * @param pattern Nesting pattern to be matched for this Rule
- * @param rule Rule instance to be registered
- */
- public void add(String pattern, Rule rule) {
- // set up rule
- if (this.digester != null) {
- rule.setDigester(this.digester);
- }
-
- if (this.namespaceURI != null) {
- rule.setNamespaceURI(this.namespaceURI);
- }
-
- registerRule(pattern, rule);
-
- }
-
- /**
- * Register rule at given pattern.
- * The the Digester and namespaceURI properties of the given <code>Rule</code>
- * can be assumed to have been set properly before this method is called.
- *
- * @param pattern Nesting pattern to be matched for this Rule
- * @param rule Rule instance to be registered
- */
- abstract protected void registerRule(String pattern, Rule rule);
-
- /**
- * Clear all existing Rule instance registrations.
- */
- abstract public void clear();
-
-
- /**
- * Return a List of all registered Rule instances that match the specified
- * nesting pattern, or a zero-length List if there are no matches. If more
- * than one Rule instance matches, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- *
- * @param pattern Nesting pattern to be matched
- *
- * @deprecated Call match(namespaceURI,pattern) instead.
- */
- public List match(String pattern) {
- return match(namespaceURI, pattern);
- }
-
-
- /**
- * Return a List of all registered Rule instances that match the specified
- * nesting pattern, or a zero-length List if there are no matches. If more
- * than one Rule instance matches, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- *
- * @param namespaceURI Namespace URI for which to select matching rules,
- * or <code>null</code> to match regardless of namespace URI
- * @param pattern Nesting pattern to be matched
- */
- abstract public List match(String namespaceURI, String pattern);
-
-
- /**
- * Return a List of all registered Rule instances, or a zero-length List
- * if there are no registered Rule instances. If more than one Rule
- * instance has been registered, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- */
- abstract public List rules();
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/ArrayStack.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/ArrayStack.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/ArrayStack.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,169 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import java.util.ArrayList;
-import java.util.EmptyStackException;
-
-/**
- * <p>Imported copy of the <code>ArrayStack</code> class from
- * Commons Collections, which was the only direct dependency from Digester.</p>
- *
- * <p><strong>WARNNG</strong> - This class is public solely to allow it to be
- * used from subpackages of <code>org.apache.commons.digester</code>.
- * It should not be considered part of the public API of Commons Digester.
- * If you want to use such a class yourself, you should use the one from
- * Commons Collections directly.</p>
- *
- * <p>An implementation of the {@link java.util.Stack} API that is based on an
- * <code>ArrayList</code> instead of a <code>Vector</code>, so it is not
- * synchronized to protect against multi-threaded access. The implementation
- * is therefore operates faster in environments where you do not need to
- * worry about multiple thread contention.</p>
- *
- * <p>Unlike <code>Stack</code>, <code>ArrayStack</code> accepts null entries.
- * </p>
- *
- * @see java.util.Stack
- * @since Digester 1.6 (from Commons Collections 1.0)
- */
-public class ArrayStack extends ArrayList {
-
- /** Ensure serialization compatibility */
- private static final long serialVersionUID = 2130079159931574599L;
-
- /**
- * Constructs a new empty <code>ArrayStack</code>. The initial size
- * is controlled by <code>ArrayList</code> and is currently 10.
- */
- public ArrayStack() {
- super();
- }
-
- /**
- * Constructs a new empty <code>ArrayStack</code> with an initial size.
- *
- * @param initialSize the initial size to use
- * @throws IllegalArgumentException if the specified initial size
- * is negative
- */
- public ArrayStack(int initialSize) {
- super(initialSize);
- }
-
- /**
- * Return <code>true</code> if this stack is currently empty.
- * <p>
- * This method exists for compatibility with <code>java.util.Stack</code>.
- * New users of this class should use <code>isEmpty</code> instead.
- *
- * @return true if the stack is currently empty
- */
- public boolean empty() {
- return isEmpty();
- }
-
- /**
- * Returns the top item off of this stack without removing it.
- *
- * @return the top item on the stack
- * @throws EmptyStackException if the stack is empty
- */
- public Object peek() throws EmptyStackException {
- int n = size();
- if (n <= 0) {
- throw new EmptyStackException();
- } else {
- return get(n - 1);
- }
- }
-
- /**
- * Returns the n'th item down (zero-relative) from the top of this
- * stack without removing it.
- *
- * @param n the number of items down to go
- * @return the n'th item on the stack, zero relative
- * @throws EmptyStackException if there are not enough items on the
- * stack to satisfy this request
- */
- public Object peek(int n) throws EmptyStackException {
- int m = (size() - n) - 1;
- if (m < 0) {
- throw new EmptyStackException();
- } else {
- return get(m);
- }
- }
-
- /**
- * Pops the top item off of this stack and return it.
- *
- * @return the top item on the stack
- * @throws EmptyStackException if the stack is empty
- */
- public Object pop() throws EmptyStackException {
- int n = size();
- if (n <= 0) {
- throw new EmptyStackException();
- } else {
- return remove(n - 1);
- }
- }
-
- /**
- * Pushes a new item onto the top of this stack. The pushed item is also
- * returned. This is equivalent to calling <code>add</code>.
- *
- * @param item the item to be added
- * @return the item just pushed
- */
- public Object push(Object item) {
- add(item);
- return item;
- }
-
-
- /**
- * Returns the one-based position of the distance from the top that the
- * specified object exists on this stack, where the top-most element is
- * considered to be at distance <code>1</code>. If the object is not
- * present on the stack, return <code>-1</code> instead. The
- * <code>equals()</code> method is used to compare to the items
- * in this stack.
- *
- * @param object the object to be searched for
- * @return the 1-based depth into the stack of the object, or -1 if not found
- */
- public int search(Object object) {
- int i = size() - 1; // Current index
- int n = 1; // Current distance
- while (i >= 0) {
- Object current = get(i);
- if ((object == null && current == null) ||
- (object != null && object.equals(current))) {
- return n;
- }
- i--;
- n++;
- }
- return -1;
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/CallMethodRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/CallMethodRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/CallMethodRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,630 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.apache.tomcat.util.IntrospectionUtils;
-import org.xml.sax.Attributes;
-
-
-/**
- * <p>Rule implementation that calls a method on an object on the stack
- * (normally the top/parent object), passing arguments collected from
- * subsequent <code>CallParamRule</code> rules or from the body of this
- * element. </p>
- *
- * <p>By using {@link #CallMethodRule(String methodName)}
- * a method call can be made to a method which accepts no
- * arguments.</p>
- *
- * <p>Incompatible method parameter types are converted
- * using <code>org.apache.commons.beanutils.ConvertUtils</code>.
- * </p>
- *
- * <p>This rule now uses
- * <a href="http://jakarta.apache.org/commons/beanutils/apidocs/org/apache/commons/be...">
- * org.apache.commons.beanutils.MethodUtils#invokeMethod
- * </a> by default.
- * This increases the kinds of methods successfully and allows primitives
- * to be matched by passing in wrapper classes.
- * There are rare cases when org.apache.commons.beanutils.MethodUtils#invokeExactMethod
- * (the old default) is required.
- * This method is much stricter in its reflection.
- * Setting the <code>UseExactMatch</code> to true reverts to the use of this
- * method.</p>
- *
- * <p>Note that the target method is invoked when the <i>end</i> of
- * the tag the CallMethodRule fired on is encountered, <i>not</i> when the
- * last parameter becomes available. This implies that rules which fire on
- * tags nested within the one associated with the CallMethodRule will
- * fire before the CallMethodRule invokes the target method. This behaviour is
- * not configurable. </p>
- *
- * <p>Note also that if a CallMethodRule is expecting exactly one parameter
- * and that parameter is not available (eg CallParamRule is used with an
- * attribute name but the attribute does not exist) then the method will
- * not be invoked. If a CallMethodRule is expecting more than one parameter,
- * then it is always invoked, regardless of whether the parameters were
- * available or not (missing parameters are passed as null values).</p>
- */
-
-public class CallMethodRule extends Rule {
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a "call method" rule with the specified method name. The
- * parameter types (if any) default to java.lang.String.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of this element.
- *
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #CallMethodRule(String methodName,int paramCount)} instead.
- */
- public CallMethodRule(Digester digester, String methodName,
- int paramCount) {
-
- this(methodName, paramCount);
-
- }
-
-
- /**
- * Construct a "call method" rule with the specified method name.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of ths element
- * @param paramTypes The Java class names of the arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #CallMethodRule(String methodName,int paramCount, String [] paramTypes)} instead.
- */
- public CallMethodRule(Digester digester, String methodName,
- int paramCount, String paramTypes[]) {
-
- this(methodName, paramCount, paramTypes);
-
- }
-
-
- /**
- * Construct a "call method" rule with the specified method name.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of ths element
- * @param paramTypes The Java classes that represent the
- * parameter types of the method arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
- * for a <code>boolean</code> parameter)
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #CallMethodRule(String methodName,int paramCount, Class [] paramTypes)} instead.
- */
- public CallMethodRule(Digester digester, String methodName,
- int paramCount, Class paramTypes[]) {
-
- this(methodName, paramCount, paramTypes);
- }
-
-
- /**
- * Construct a "call method" rule with the specified method name. The
- * parameter types (if any) default to java.lang.String.
- *
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of this element.
- */
- public CallMethodRule(String methodName,
- int paramCount) {
- this(0, methodName, paramCount);
- }
-
- /**
- * Construct a "call method" rule with the specified method name. The
- * parameter types (if any) default to java.lang.String.
- *
- * @param targetOffset location of the target object. Positive numbers are
- * relative to the top of the digester object stack. Negative numbers
- * are relative to the bottom of the stack. Zero implies the top
- * object on the stack.
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of this element.
- */
- public CallMethodRule(int targetOffset,
- String methodName,
- int paramCount) {
-
- this.targetOffset = targetOffset;
- this.methodName = methodName;
- this.paramCount = paramCount;
- if (paramCount == 0) {
- this.paramTypes = new Class[] { String.class };
- } else {
- this.paramTypes = new Class[paramCount];
- for (int i = 0; i < this.paramTypes.length; i++) {
- this.paramTypes[i] = String.class;
- }
- }
-
- }
-
- /**
- * Construct a "call method" rule with the specified method name.
- * The method should accept no parameters.
- *
- * @param methodName Method name of the parent method to call
- */
- public CallMethodRule(String methodName) {
-
- this(0, methodName, 0, (Class[]) null);
-
- }
-
-
- /**
- * Construct a "call method" rule with the specified method name.
- * The method should accept no parameters.
- *
- * @param targetOffset location of the target object. Positive numbers are
- * relative to the top of the digester object stack. Negative numbers
- * are relative to the bottom of the stack. Zero implies the top
- * object on the stack.
- * @param methodName Method name of the parent method to call
- */
- public CallMethodRule(int targetOffset, String methodName) {
-
- this(targetOffset, methodName, 0, (Class[]) null);
-
- }
-
-
- /**
- * Construct a "call method" rule with the specified method name and
- * parameter types. If <code>paramCount</code> is set to zero the rule
- * will use the body of this element as the single argument of the
- * method, unless <code>paramTypes</code> is null or empty, in this
- * case the rule will call the specified method with no arguments.
- *
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of ths element
- * @param paramTypes The Java class names of the arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- */
- public CallMethodRule(
- String methodName,
- int paramCount,
- String paramTypes[]) {
- this(0, methodName, paramCount, paramTypes);
- }
-
- /**
- * Construct a "call method" rule with the specified method name and
- * parameter types. If <code>paramCount</code> is set to zero the rule
- * will use the body of this element as the single argument of the
- * method, unless <code>paramTypes</code> is null or empty, in this
- * case the rule will call the specified method with no arguments.
- *
- * @param targetOffset location of the target object. Positive numbers are
- * relative to the top of the digester object stack. Negative numbers
- * are relative to the bottom of the stack. Zero implies the top
- * object on the stack.
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of ths element
- * @param paramTypes The Java class names of the arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- */
- public CallMethodRule( int targetOffset,
- String methodName,
- int paramCount,
- String paramTypes[]) {
-
- this.targetOffset = targetOffset;
- this.methodName = methodName;
- this.paramCount = paramCount;
- if (paramTypes == null) {
- this.paramTypes = new Class[paramCount];
- for (int i = 0; i < this.paramTypes.length; i++) {
- this.paramTypes[i] = "abc".getClass();
- }
- } else {
- // copy the parameter class names into an array
- // the classes will be loaded when the digester is set
- this.paramClassNames = new String[paramTypes.length];
- for (int i = 0; i < this.paramClassNames.length; i++) {
- this.paramClassNames[i] = paramTypes[i];
- }
- }
-
- }
-
-
- /**
- * Construct a "call method" rule with the specified method name and
- * parameter types. If <code>paramCount</code> is set to zero the rule
- * will use the body of this element as the single argument of the
- * method, unless <code>paramTypes</code> is null or empty, in this
- * case the rule will call the specified method with no arguments.
- *
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of ths element
- * @param paramTypes The Java classes that represent the
- * parameter types of the method arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
- * for a <code>boolean</code> parameter)
- */
- public CallMethodRule(
- String methodName,
- int paramCount,
- Class paramTypes[]) {
- this(0, methodName, paramCount, paramTypes);
- }
-
- /**
- * Construct a "call method" rule with the specified method name and
- * parameter types. If <code>paramCount</code> is set to zero the rule
- * will use the body of this element as the single argument of the
- * method, unless <code>paramTypes</code> is null or empty, in this
- * case the rule will call the specified method with no arguments.
- *
- * @param targetOffset location of the target object. Positive numbers are
- * relative to the top of the digester object stack. Negative numbers
- * are relative to the bottom of the stack. Zero implies the top
- * object on the stack.
- * @param methodName Method name of the parent method to call
- * @param paramCount The number of parameters to collect, or
- * zero for a single argument from the body of ths element
- * @param paramTypes The Java classes that represent the
- * parameter types of the method arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
- * for a <code>boolean</code> parameter)
- */
- public CallMethodRule( int targetOffset,
- String methodName,
- int paramCount,
- Class paramTypes[]) {
-
- this.targetOffset = targetOffset;
- this.methodName = methodName;
- this.paramCount = paramCount;
- if (paramTypes == null) {
- this.paramTypes = new Class[paramCount];
- for (int i = 0; i < this.paramTypes.length; i++) {
- this.paramTypes[i] = "abc".getClass();
- }
- } else {
- this.paramTypes = new Class[paramTypes.length];
- for (int i = 0; i < this.paramTypes.length; i++) {
- this.paramTypes[i] = paramTypes[i];
- }
- }
-
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The body text collected from this element.
- */
- protected String bodyText = null;
-
-
- /**
- * location of the target object for the call, relative to the
- * top of the digester object stack. The default value of zero
- * means the target object is the one on top of the stack.
- */
- protected int targetOffset = 0;
-
- /**
- * The method name to call on the parent object.
- */
- protected String methodName = null;
-
-
- /**
- * The number of parameters to collect from <code>MethodParam</code> rules.
- * If this value is zero, a single parameter will be collected from the
- * body of this element.
- */
- protected int paramCount = 0;
-
-
- /**
- * The parameter types of the parameters to be collected.
- */
- protected Class paramTypes[] = null;
-
- /**
- * The names of the classes of the parameters to be collected.
- * This attribute allows creation of the classes to be postponed until the digester is set.
- */
- protected String paramClassNames[] = null;
-
- /**
- * Should <code>MethodUtils.invokeExactMethod</code> be used for reflection.
- */
- protected boolean useExactMatch = false;
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * Should <code>MethodUtils.invokeExactMethod</code>
- * be used for the reflection.
- */
- public boolean getUseExactMatch() {
- return useExactMatch;
- }
-
- /**
- * Set whether <code>MethodUtils.invokeExactMethod</code>
- * should be used for the reflection.
- */
- public void setUseExactMatch(boolean useExactMatch)
- {
- this.useExactMatch = useExactMatch;
- }
-
- /**
- * Set the associated digester.
- * If needed, this class loads the parameter classes from their names.
- */
- public void setDigester(Digester digester)
- {
- // call superclass
- super.setDigester(digester);
- // if necessary, load parameter classes
- if (this.paramClassNames != null) {
- this.paramTypes = new Class[paramClassNames.length];
- for (int i = 0; i < this.paramClassNames.length; i++) {
- try {
- this.paramTypes[i] =
- digester.getClassLoader().loadClass(this.paramClassNames[i]);
- } catch (ClassNotFoundException e) {
- // use the digester log
- digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e);
- this.paramTypes[i] = null; // Will cause NPE later
- }
- }
- }
- }
-
- /**
- * Process the start of this element.
- *
- * @param attributes The attribute list for this element
- */
- public void begin(Attributes attributes) throws Exception {
-
- // Push an array to capture the parameter values if necessary
- if (paramCount > 0) {
- Object parameters[] = new Object[paramCount];
- for (int i = 0; i < parameters.length; i++) {
- parameters[i] = null;
- }
- digester.pushParams(parameters);
- }
-
- }
-
-
- /**
- * Process the body text of this element.
- *
- * @param bodyText The body text of this element
- */
- public void body(String bodyText) throws Exception {
-
- if (paramCount == 0) {
- this.bodyText = bodyText.trim();
- }
-
- }
-
-
- /**
- * Process the end of this element.
- */
- public void end() throws Exception {
-
- // Retrieve or construct the parameter values array
- Object parameters[] = null;
- if (paramCount > 0) {
-
- parameters = (Object[]) digester.popParams();
-
- if (digester.log.isTraceEnabled()) {
- for (int i=0,size=parameters.length;i<size;i++) {
- digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ;
- }
- }
-
- // In the case where the parameter for the method
- // is taken from an attribute, and that attribute
- // isn't actually defined in the source XML file,
- // skip the method call
- if (paramCount == 1 && parameters[0] == null) {
- return;
- }
-
- } else if (paramTypes != null && paramTypes.length != 0) {
-
- // In the case where the parameter for the method
- // is taken from the body text, but there is no
- // body text included in the source XML file,
- // skip the method call
- if (bodyText == null) {
- return;
- }
-
- parameters = new Object[1];
- parameters[0] = bodyText;
- if (paramTypes.length == 0) {
- paramTypes = new Class[1];
- paramTypes[0] = "abc".getClass();
- }
-
- }
-
- // Construct the parameter values array we will need
- // We only do the conversion if the param value is a String and
- // the specified paramType is not String.
- Object paramValues[] = new Object[paramTypes.length];
- for (int i = 0; i < paramTypes.length; i++) {
- // convert nulls and convert stringy parameters
- // for non-stringy param types
- if(
- parameters[i] == null ||
- (parameters[i] instanceof String &&
- !String.class.isAssignableFrom(paramTypes[i]))) {
-
- paramValues[i] =
- IntrospectionUtils.convert((String) parameters[i], paramTypes[i]);
- } else {
- paramValues[i] = parameters[i];
- }
- }
-
- // Determine the target object for the method call
- Object target;
- if (targetOffset >= 0) {
- target = digester.peek(targetOffset);
- } else {
- target = digester.peek( digester.getCount() + targetOffset );
- }
-
- if (target == null) {
- StringBuilder sb = new StringBuilder();
- sb.append("[CallMethodRule]{");
- sb.append(digester.match);
- sb.append("} Call target is null (");
- sb.append("targetOffset=");
- sb.append(targetOffset);
- sb.append(",stackdepth=");
- sb.append(digester.getCount());
- sb.append(")");
- throw new org.xml.sax.SAXException(sb.toString());
- }
-
- // Invoke the required method on the top object
- if (digester.log.isDebugEnabled()) {
- StringBuilder sb = new StringBuilder("[CallMethodRule]{");
- sb.append(digester.match);
- sb.append("} Call ");
- sb.append(target.getClass().getName());
- sb.append(".");
- sb.append(methodName);
- sb.append("(");
- for (int i = 0; i < paramValues.length; i++) {
- if (i > 0) {
- sb.append(",");
- }
- if (paramValues[i] == null) {
- sb.append("null");
- } else {
- sb.append(paramValues[i].toString());
- }
- sb.append("/");
- if (paramTypes[i] == null) {
- sb.append("null");
- } else {
- sb.append(paramTypes[i].getName());
- }
- }
- sb.append(")");
- digester.log.debug(sb.toString());
- }
- Object result = IntrospectionUtils.callMethodN(target, methodName,
- paramValues, paramTypes);
- processMethodCallResult(result);
- }
-
-
- /**
- * Clean up after parsing is complete.
- */
- public void finish() throws Exception {
-
- bodyText = null;
-
- }
-
- /**
- * Subclasses may override this method to perform additional processing of the
- * invoked method's result.
- *
- * @param result the Object returned by the method invoked, possibly null
- */
- protected void processMethodCallResult(Object result) {
- // do nothing
- }
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("CallMethodRule[");
- sb.append("methodName=");
- sb.append(methodName);
- sb.append(", paramCount=");
- sb.append(paramCount);
- sb.append(", paramTypes={");
- if (paramTypes != null) {
- for (int i = 0; i < paramTypes.length; i++) {
- if (i > 0) {
- sb.append(", ");
- }
- sb.append(paramTypes[i].getName());
- }
- }
- sb.append("}");
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/CallParamRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/CallParamRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/CallParamRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,263 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.xml.sax.Attributes;
-
-
-/**
- * <p>Rule implementation that saves a parameter for use by a surrounding
- * <code>CallMethodRule<code>.</p>
- *
- * <p>This parameter may be:
- * <ul>
- * <li>from an attribute of the current element
- * See {@link #CallParamRule(int paramIndex, String attributeName)}
- * <li>from current the element body
- * See {@link #CallParamRule(int paramIndex)}
- * <li>from the top object on the stack.
- * See {@link #CallParamRule(int paramIndex, boolean fromStack)}
- * <li>the current path being processed (separate <code>Rule</code>).
- * See {@link PathCallParamRule}
- * </ul>
- * </p>
- */
-
-public class CallParamRule extends Rule {
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a "call parameter" rule that will save the body text of this
- * element as the parameter value.
- *
- * @param digester The associated Digester
- * @param paramIndex The zero-relative parameter number
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #CallParamRule(int paramIndex)} instead.
- */
- public CallParamRule(Digester digester, int paramIndex) {
-
- this(paramIndex);
-
- }
-
-
- /**
- * Construct a "call parameter" rule that will save the value of the
- * specified attribute as the parameter value.
- *
- * @param digester The associated Digester
- * @param paramIndex The zero-relative parameter number
- * @param attributeName The name of the attribute to save
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #CallParamRule(int paramIndex, String attributeName)} instead.
- */
- public CallParamRule(Digester digester, int paramIndex,
- String attributeName) {
-
- this(paramIndex, attributeName);
-
- }
-
- /**
- * Construct a "call parameter" rule that will save the body text of this
- * element as the parameter value.
- *
- * @param paramIndex The zero-relative parameter number
- */
- public CallParamRule(int paramIndex) {
-
- this(paramIndex, null);
-
- }
-
-
- /**
- * Construct a "call parameter" rule that will save the value of the
- * specified attribute as the parameter value.
- *
- * @param paramIndex The zero-relative parameter number
- * @param attributeName The name of the attribute to save
- */
- public CallParamRule(int paramIndex,
- String attributeName) {
-
- this.paramIndex = paramIndex;
- this.attributeName = attributeName;
-
- }
-
-
- /**
- * Construct a "call parameter" rule.
- *
- * @param paramIndex The zero-relative parameter number
- * @param fromStack should this parameter be taken from the top of the stack?
- */
- public CallParamRule(int paramIndex, boolean fromStack) {
-
- this.paramIndex = paramIndex;
- this.fromStack = fromStack;
-
- }
-
- /**
- * Constructs a "call parameter" rule which sets a parameter from the stack.
- * If the stack contains too few objects, then the parameter will be set to null.
- *
- * @param paramIndex The zero-relative parameter number
- * @param stackIndex the index of the object which will be passed as a parameter.
- * The zeroth object is the top of the stack, 1 is the next object down and so on.
- */
- public CallParamRule(int paramIndex, int stackIndex) {
-
- this.paramIndex = paramIndex;
- this.fromStack = true;
- this.stackIndex = stackIndex;
- }
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The attribute from which to save the parameter value
- */
- protected String attributeName = null;
-
-
- /**
- * The zero-relative index of the parameter we are saving.
- */
- protected int paramIndex = 0;
-
-
- /**
- * Is the parameter to be set from the stack?
- */
- protected boolean fromStack = false;
-
- /**
- * The position of the object from the top of the stack
- */
- protected int stackIndex = 0;
-
- /**
- * Stack is used to allow nested body text to be processed.
- * Lazy creation.
- */
- protected ArrayStack bodyTextStack;
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Process the start of this element.
- *
- * @param attributes The attribute list for this element
- */
- public void begin(Attributes attributes) throws Exception {
-
- Object param = null;
-
- if (attributeName != null) {
-
- param = attributes.getValue(attributeName);
-
- } else if(fromStack) {
-
- param = digester.peek(stackIndex);
-
- if (digester.log.isDebugEnabled()) {
-
- StringBuilder sb = new StringBuilder("[CallParamRule]{");
- sb.append(digester.match);
- sb.append("} Save from stack; from stack?").append(fromStack);
- sb.append("; object=").append(param);
- digester.log.debug(sb.toString());
- }
- }
-
- // Have to save the param object to the param stack frame here.
- // Can't wait until end(). Otherwise, the object will be lost.
- // We can't save the object as instance variables, as
- // the instance variables will be overwritten
- // if this CallParamRule is reused in subsequent nesting.
-
- if(param != null) {
- Object parameters[] = (Object[]) digester.peekParams();
- parameters[paramIndex] = param;
- }
- }
-
-
- /**
- * Process the body text of this element.
- *
- * @param bodyText The body text of this element
- */
- public void body(String bodyText) throws Exception {
-
- if (attributeName == null && !fromStack) {
- // We must wait to set the parameter until end
- // so that we can make sure that the right set of parameters
- // is at the top of the stack
- if (bodyTextStack == null) {
- bodyTextStack = new ArrayStack();
- }
- bodyTextStack.push(bodyText.trim());
- }
-
- }
-
- /**
- * Process any body texts now.
- */
- public void end(String namespace, String name) {
- if (bodyTextStack != null && !bodyTextStack.empty()) {
- // what we do now is push one parameter onto the top set of parameters
- Object parameters[] = (Object[]) digester.peekParams();
- parameters[paramIndex] = bodyTextStack.pop();
- }
- }
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("CallParamRule[");
- sb.append("paramIndex=");
- sb.append(paramIndex);
- sb.append(", attributeName=");
- sb.append(attributeName);
- sb.append(", from stack=");
- sb.append(fromStack);
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/Digester.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/Digester.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/Digester.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,2851 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.lang.reflect.InvocationTargetException;
-import java.util.EmptyStackException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.apache.tomcat.util.IntrospectionUtils;
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-import org.xml.sax.Attributes;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.AttributesImpl;
-import org.xml.sax.helpers.DefaultHandler;
-
-
-
-
-/**
- * <p>A <strong>Digester</strong> processes an XML input stream by matching a
- * series of element nesting patterns to execute Rules that have been added
- * prior to the start of parsing. This package was inspired by the
- * <code>XmlMapper</code> class that was part of Tomcat 3.0 and 3.1,
- * but is organized somewhat differently.</p>
- *
- * <p>See the <a href="package-summary.html#package_description">Digester
- * Developer Guide</a> for more information.</p>
- *
- * <p><strong>IMPLEMENTATION NOTE</strong> - A single Digester instance may
- * only be used within the context of a single thread at a time, and a call
- * to <code>parse()</code> must be completed before another can be initiated
- * even from the same thread.</p>
- *
- * <p><strong>IMPLEMENTATION NOTE</strong> - A bug in Xerces 2.0.2 prevents
- * the support of XML schema. You need Xerces 2.1/2.3 and up to make
- * this class working with XML schema</p>
- */
-
-public class Digester extends DefaultHandler {
-
-
- // ---------------------------------------------------------- Static Fields
-
-
- private static class SystemPropertySource
- implements IntrospectionUtils.PropertySource {
- public String getProperty( String key ) {
- return System.getProperty(key);
- }
- }
-
- protected static IntrospectionUtils.PropertySource source[] =
- new IntrospectionUtils.PropertySource[] { new SystemPropertySource() };
-
-
- // --------------------------------------------------------- Constructors
-
-
- /**
- * Construct a new Digester with default properties.
- */
- public Digester() {
-
- super();
-
- }
-
-
- /**
- * Construct a new Digester, allowing a SAXParser to be passed in. This
- * allows Digester to be used in environments which are unfriendly to
- * JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to
- * James House (james(a)interobjective.com). This may help in places where
- * you are able to load JAXP 1.1 classes yourself.
- */
- public Digester(SAXParser parser) {
-
- super();
-
- this.parser = parser;
-
- }
-
-
- /**
- * Construct a new Digester, allowing an XMLReader to be passed in. This
- * allows Digester to be used in environments which are unfriendly to
- * JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you
- * have to configure namespace and validation support yourself, as these
- * properties only affect the SAXParser and emtpy constructor.
- */
- public Digester(XMLReader reader) {
-
- super();
-
- this.reader = reader;
-
- }
-
-
- // --------------------------------------------------- Instance Variables
-
-
- /**
- * The body text of the current element.
- */
- protected StringBuilder bodyText = new StringBuilder();
-
-
- /**
- * The stack of body text string buffers for surrounding elements.
- */
- protected ArrayStack bodyTexts = new ArrayStack();
-
-
- /**
- * Stack whose elements are List objects, each containing a list of
- * Rule objects as returned from Rules.getMatch(). As each xml element
- * in the input is entered, the matching rules are pushed onto this
- * stack. After the end tag is reached, the matches are popped again.
- * The depth of is stack is therefore exactly the same as the current
- * "nesting" level of the input xml.
- *
- * @since 1.6
- */
- protected ArrayStack matches = new ArrayStack(10);
-
- /**
- * The class loader to use for instantiating application objects.
- * If not specified, the context class loader, or the class loader
- * used to load Digester itself, is used, based on the value of the
- * <code>useContextClassLoader</code> variable.
- */
- protected ClassLoader classLoader = null;
-
-
- /**
- * Has this Digester been configured yet.
- */
- protected boolean configured = false;
-
-
- /**
- * The EntityResolver used by the SAX parser. By default it use this class
- */
- protected EntityResolver entityResolver;
-
- /**
- * The URLs of entityValidator that have been registered, keyed by the public
- * identifier that corresponds.
- */
- protected HashMap entityValidator = new HashMap();
-
-
- /**
- * The application-supplied error handler that is notified when parsing
- * warnings, errors, or fatal errors occur.
- */
- protected ErrorHandler errorHandler = null;
-
-
- /**
- * The SAXParserFactory that is created the first time we need it.
- */
- protected SAXParserFactory factory = null;
-
- /**
- * @deprecated This is now managed by {@link ParserFeatureSetterFactory}
- */
- protected String JAXP_SCHEMA_LANGUAGE =
- "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
-
-
- /**
- * The Locator associated with our parser.
- */
- protected Locator locator = null;
-
-
- /**
- * The current match pattern for nested element processing.
- */
- protected String match = "";
-
-
- /**
- * Do we want a "namespace aware" parser.
- */
- protected boolean namespaceAware = false;
-
-
- /**
- * Registered namespaces we are currently processing. The key is the
- * namespace prefix that was declared in the document. The value is an
- * ArrayStack of the namespace URIs this prefix has been mapped to --
- * the top Stack element is the most current one. (This architecture
- * is required because documents can declare nested uses of the same
- * prefix for different Namespace URIs).
- */
- protected HashMap namespaces = new HashMap();
-
-
- /**
- * The parameters stack being utilized by CallMethodRule and
- * CallParamRule rules.
- */
- protected ArrayStack params = new ArrayStack();
-
-
- /**
- * The SAXParser we will use to parse the input stream.
- */
- protected SAXParser parser = null;
-
-
- /**
- * The public identifier of the DTD we are currently parsing under
- * (if any).
- */
- protected String publicId = null;
-
-
- /**
- * The XMLReader used to parse digester rules.
- */
- protected XMLReader reader = null;
-
-
- /**
- * The "root" element of the stack (in other words, the last object
- * that was popped.
- */
- protected Object root = null;
-
-
- /**
- * The <code>Rules</code> implementation containing our collection of
- * <code>Rule</code> instances and associated matching policy. If not
- * established before the first rule is added, a default implementation
- * will be provided.
- */
- protected Rules rules = null;
-
-
- /**
- * The object stack being constructed.
- */
- protected ArrayStack stack = new ArrayStack();
-
-
- /**
- * Do we want to use the Context ClassLoader when loading classes
- * for instantiating new objects. Default is <code>false</code>.
- */
- protected boolean useContextClassLoader = false;
-
-
- /**
- * Do we want to use a validating parser.
- */
- protected boolean validating = false;
-
-
- /**
- * Warn on missing attributes and elements.
- */
- protected boolean rulesValidation = false;
-
-
- /**
- * Fake attributes map (attributes are often used for object creation).
- */
- protected Map<Class, List<String>> fakeAttributes = null;
-
-
- /**
- * The Log to which most logging calls will be made.
- */
- protected Logger log =
- Logger.getLogger("org.apache.commons.digester.Digester");
-
-
- /**
- * The Log to which all SAX event related logging calls will be made.
- */
- protected Logger saxLog =
- Logger.getLogger("org.apache.commons.digester.Digester.sax");
-
-
- /**
- * The schema language supported. By default, we use this one.
- */
- protected static final String W3C_XML_SCHEMA =
- "http://www.w3.org/2001/XMLSchema";
-
- /** Stacks used for interrule communication, indexed by name String */
- private HashMap stacksByName = new HashMap();
-
- // ------------------------------------------------------------- Properties
-
- /**
- * Return the currently mapped namespace URI for the specified prefix,
- * if any; otherwise return <code>null</code>. These mappings come and
- * go dynamically as the document is parsed.
- *
- * @param prefix Prefix to look up
- */
- public String findNamespaceURI(String prefix) {
-
- ArrayStack stack = (ArrayStack) namespaces.get(prefix);
- if (stack == null) {
- return (null);
- }
- try {
- return ((String) stack.peek());
- } catch (EmptyStackException e) {
- return (null);
- }
-
- }
-
-
- /**
- * Return the class loader to be used for instantiating application objects
- * when required. This is determined based upon the following rules:
- * <ul>
- * <li>The class loader set by <code>setClassLoader()</code>, if any</li>
- * <li>The thread context class loader, if it exists and the
- * <code>useContextClassLoader</code> property is set to true</li>
- * <li>The class loader used to load the Digester class itself.
- * </ul>
- */
- public ClassLoader getClassLoader() {
-
- if (this.classLoader != null) {
- return (this.classLoader);
- }
- if (this.useContextClassLoader) {
- ClassLoader classLoader =
- Thread.currentThread().getContextClassLoader();
- if (classLoader != null) {
- return (classLoader);
- }
- }
- return (this.getClass().getClassLoader());
-
- }
-
-
- /**
- * Set the class loader to be used for instantiating application objects
- * when required.
- *
- * @param classLoader The new class loader to use, or <code>null</code>
- * to revert to the standard rules
- */
- public void setClassLoader(ClassLoader classLoader) {
-
- this.classLoader = classLoader;
-
- }
-
-
- /**
- * Return the current depth of the element stack.
- */
- public int getCount() {
-
- return (stack.size());
-
- }
-
-
- /**
- * Return the name of the XML element that is currently being processed.
- */
- public String getCurrentElementName() {
-
- String elementName = match;
- int lastSlash = elementName.lastIndexOf('/');
- if (lastSlash >= 0) {
- elementName = elementName.substring(lastSlash + 1);
- }
- return (elementName);
-
- }
-
-
- /**
- * Return the debugging detail level of our currently enabled logger.
- *
- * @deprecated This method now always returns 0. Digester uses the apache
- * jakarta commons-logging library; see the documentation for that library
- * for more information.
- */
- public int getDebug() {
-
- return (0);
-
- }
-
-
- /**
- * Set the debugging detail level of our currently enabled logger.
- *
- * @param debug New debugging detail level (0=off, increasing integers
- * for more detail)
- *
- * @deprecated This method now has no effect at all. Digester uses
- * the apache jakarta comons-logging library; see the documentation
- * for that library for more information.
- */
- public void setDebug(int debug) {
-
- ; // No action is taken
-
- }
-
-
- /**
- * Return the error handler for this Digester.
- */
- public ErrorHandler getErrorHandler() {
-
- return (this.errorHandler);
-
- }
-
-
- /**
- * Set the error handler for this Digester.
- *
- * @param errorHandler The new error handler
- */
- public void setErrorHandler(ErrorHandler errorHandler) {
-
- this.errorHandler = errorHandler;
-
- }
-
-
- /**
- * Return the SAXParserFactory we will use, creating one if necessary.
- * @throws ParserConfigurationException
- * @throws SAXNotSupportedException
- * @throws SAXNotRecognizedException
- */
- public SAXParserFactory getFactory()
- throws SAXNotRecognizedException, SAXNotSupportedException,
- ParserConfigurationException {
-
- if (factory == null) {
- factory = SAXParserFactory.newInstance();
- factory.setNamespaceAware(namespaceAware);
- factory.setValidating(validating);
- if (validating) {
- // Enable DTD validation
- factory.setFeature(
- "http://xml.org/sax/features/validation",
- true);
- // Enable schema validation
- factory.setFeature(
- "http://apache.org/xml/features/validation/schema",
- true);
- }
- }
- return (factory);
-
- }
-
-
- /**
- * Returns a flag indicating whether the requested feature is supported
- * by the underlying implementation of <code>org.xml.sax.XMLReader</code>.
- * See <a href="http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des..."
- * http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des...</a>
- * for information about the standard SAX2 feature flags.
- *
- * @param feature Name of the feature to inquire about
- *
- * @exception ParserConfigurationException if a parser configuration error
- * occurs
- * @exception SAXNotRecognizedException if the property name is
- * not recognized
- * @exception SAXNotSupportedException if the property name is
- * recognized but not supported
- */
- public boolean getFeature(String feature)
- throws ParserConfigurationException, SAXNotRecognizedException,
- SAXNotSupportedException {
-
- return (getFactory().getFeature(feature));
-
- }
-
-
- /**
- * Sets a flag indicating whether the requested feature is supported
- * by the underlying implementation of <code>org.xml.sax.XMLReader</code>.
- * See <a href="http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des..."
- * http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des...</a>
- * for information about the standard SAX2 feature flags. In order to be
- * effective, this method must be called <strong>before</strong> the
- * <code>getParser()</code> method is called for the first time, either
- * directly or indirectly.
- *
- * @param feature Name of the feature to set the status for
- * @param value The new value for this feature
- *
- * @exception ParserConfigurationException if a parser configuration error
- * occurs
- * @exception SAXNotRecognizedException if the property name is
- * not recognized
- * @exception SAXNotSupportedException if the property name is
- * recognized but not supported
- */
- public void setFeature(String feature, boolean value)
- throws ParserConfigurationException, SAXNotRecognizedException,
- SAXNotSupportedException {
-
- getFactory().setFeature(feature, value);
-
- }
-
-
- /**
- * Return the current Logger associated with this instance of the Digester
- */
- public Logger getLogger() {
-
- return log;
-
- }
-
-
- /**
- * Set the current logger for this Digester.
- */
- public void setLogger(Logger log) {
-
- this.log = log;
-
- }
-
- /**
- * Gets the logger used for logging SAX-related information.
- * <strong>Note</strong> the output is finely grained.
- *
- * @since 1.6
- */
- public Logger getSAXLogger() {
-
- return saxLog;
- }
-
-
- /**
- * Sets the logger used for logging SAX-related information.
- * <strong>Note</strong> the output is finely grained.
- * @param saxLog Log, not null
- *
- * @since 1.6
- */
- public void setSAXLogger(Logger saxLog) {
-
- this.saxLog = saxLog;
- }
-
- /**
- * Return the current rule match path
- */
- public String getMatch() {
-
- return match;
-
- }
-
-
- /**
- * Return the "namespace aware" flag for parsers we create.
- */
- public boolean getNamespaceAware() {
-
- return (this.namespaceAware);
-
- }
-
-
- /**
- * Set the "namespace aware" flag for parsers we create.
- *
- * @param namespaceAware The new "namespace aware" flag
- */
- public void setNamespaceAware(boolean namespaceAware) {
-
- this.namespaceAware = namespaceAware;
-
- }
-
-
- /**
- * Set the publid id of the current file being parse.
- * @param publicId the DTD/Schema public's id.
- */
- public void setPublicId(String publicId){
- this.publicId = publicId;
- }
-
-
- /**
- * Return the public identifier of the DTD we are currently
- * parsing under, if any.
- */
- public String getPublicId() {
-
- return (this.publicId);
-
- }
-
-
- /**
- * Return the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- */
- public String getRuleNamespaceURI() {
-
- return (getRules().getNamespaceURI());
-
- }
-
-
- /**
- * Set the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- *
- * @param ruleNamespaceURI Namespace URI that must match on all
- * subsequently added rules, or <code>null</code> for matching
- * regardless of the current namespace URI
- */
- public void setRuleNamespaceURI(String ruleNamespaceURI) {
-
- getRules().setNamespaceURI(ruleNamespaceURI);
-
- }
-
-
- /**
- * Return the SAXParser we will use to parse the input stream. If there
- * is a problem creating the parser, return <code>null</code>.
- */
- public SAXParser getParser() {
-
- // Return the parser we already created (if any)
- if (parser != null) {
- return (parser);
- }
-
- // Create a new parser
- try {
- parser = getFactory().newSAXParser();
- } catch (Exception e) {
- log.error("Digester.getParser: ", e);
- return (null);
- }
-
- return (parser);
-
- }
-
-
- /**
- * Return the current value of the specified property for the underlying
- * <code>XMLReader</code> implementation.
- * See <a href="http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des..."
- * http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des...</a>
- * for information about the standard SAX2 properties.
- *
- * @param property Property name to be retrieved
- *
- * @exception SAXNotRecognizedException if the property name is
- * not recognized
- * @exception SAXNotSupportedException if the property name is
- * recognized but not supported
- */
- public Object getProperty(String property)
- throws SAXNotRecognizedException, SAXNotSupportedException {
-
- return (getParser().getProperty(property));
-
- }
-
-
- /**
- * Set the current value of the specified property for the underlying
- * <code>XMLReader</code> implementation.
- * See <a href="http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des..."
- * http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-des...</a>
- * for information about the standard SAX2 properties.
- *
- * @param property Property name to be set
- * @param value Property value to be set
- *
- * @exception SAXNotRecognizedException if the property name is
- * not recognized
- * @exception SAXNotSupportedException if the property name is
- * recognized but not supported
- */
- public void setProperty(String property, Object value)
- throws SAXNotRecognizedException, SAXNotSupportedException {
-
- getParser().setProperty(property, value);
-
- }
-
-
- /**
- * By setting the reader in the constructor, you can bypass JAXP and
- * be able to use digester in Weblogic 6.0.
- *
- * @deprecated Use getXMLReader() instead, which can throw a
- * SAXException if the reader cannot be instantiated
- */
- public XMLReader getReader() {
-
- try {
- return (getXMLReader());
- } catch (SAXException e) {
- log.error("Cannot get XMLReader", e);
- return (null);
- }
-
- }
-
-
- /**
- * Return the <code>Rules</code> implementation object containing our
- * rules collection and associated matching policy. If none has been
- * established, a default implementation will be created and returned.
- */
- public Rules getRules() {
-
- if (this.rules == null) {
- this.rules = new RulesBase();
- this.rules.setDigester(this);
- }
- return (this.rules);
-
- }
-
-
- /**
- * Set the <code>Rules</code> implementation object containing our
- * rules collection and associated matching policy.
- *
- * @param rules New Rules implementation
- */
- public void setRules(Rules rules) {
-
- this.rules = rules;
- this.rules.setDigester(this);
-
- }
-
-
- /**
- * Return the boolean as to whether the context classloader should be used.
- */
- public boolean getUseContextClassLoader() {
-
- return useContextClassLoader;
-
- }
-
-
- /**
- * Determine whether to use the Context ClassLoader (the one found by
- * calling <code>Thread.currentThread().getContextClassLoader()</code>)
- * to resolve/load classes that are defined in various rules. If not
- * using Context ClassLoader, then the class-loading defaults to
- * using the calling-class' ClassLoader.
- *
- * @param use determines whether to use Context ClassLoader.
- */
- public void setUseContextClassLoader(boolean use) {
-
- useContextClassLoader = use;
-
- }
-
-
- /**
- * Return the validating parser flag.
- */
- public boolean getValidating() {
-
- return (this.validating);
-
- }
-
-
- /**
- * Set the validating parser flag. This must be called before
- * <code>parse()</code> is called the first time.
- *
- * @param validating The new validating parser flag.
- */
- public void setValidating(boolean validating) {
-
- this.validating = validating;
-
- }
-
-
- /**
- * Return the rules validation flag.
- */
- public boolean getRulesValidation() {
-
- return (this.rulesValidation);
-
- }
-
-
- /**
- * Set the rules validation flag. This must be called before
- * <code>parse()</code> is called the first time.
- *
- * @param rulesValidation The new rules validation flag.
- */
- public void setRulesValidation(boolean rulesValidation) {
-
- this.rulesValidation = rulesValidation;
-
- }
-
-
- /**
- * Return the fake attributes list.
- */
- public Map<Class, List<String>> getFakeAttributes() {
-
- return (this.fakeAttributes);
-
- }
-
-
- /**
- * Determine if an attribute is a fake attribute.
- */
- public boolean isFakeAttribute(Object object, String name) {
-
- if (fakeAttributes == null) {
- return false;
- }
- List<String> result = fakeAttributes.get(object.getClass());
- if (result == null) {
- result = fakeAttributes.get(Object.class);
- }
- if (result == null) {
- return false;
- } else {
- return result.contains(name);
- }
-
- }
-
-
- /**
- * Set the fake attributes.
- *
- * @param fakeAttributes The new fake attributes.
- */
- public void setFakeAttributes(Map<Class, List<String>> fakeAttributes) {
-
- this.fakeAttributes = fakeAttributes;
-
- }
-
-
- /**
- * Return the XMLReader to be used for parsing the input document.
- *
- * FIX ME: there is a bug in JAXP/XERCES that prevent the use of a
- * parser that contains a schema with a DTD.
- * @exception SAXException if no XMLReader can be instantiated
- */
- public XMLReader getXMLReader() throws SAXException {
- if (reader == null){
- reader = getParser().getXMLReader();
- }
-
- reader.setDTDHandler(this);
- reader.setContentHandler(this);
-
- if (entityResolver == null){
- reader.setEntityResolver(this);
- } else {
- reader.setEntityResolver(entityResolver);
- }
-
- reader.setErrorHandler(this);
- return reader;
- }
-
- // ------------------------------------------------- ContentHandler Methods
-
-
- /**
- * Process notification of character data received from the body of
- * an XML element.
- *
- * @param buffer The characters from the XML document
- * @param start Starting offset into the buffer
- * @param length Number of characters from the buffer
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void characters(char buffer[], int start, int length)
- throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("characters(" + new String(buffer, start, length) + ")");
- }
-
- bodyText.append(buffer, start, length);
-
- }
-
-
- /**
- * Process notification of the end of the document being reached.
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void endDocument() throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- if (getCount() > 1) {
- saxLog.debug("endDocument(): " + getCount() +
- " elements left");
- } else {
- saxLog.debug("endDocument()");
- }
- }
-
- while (getCount() > 1) {
- pop();
- }
-
- // Fire "finish" events for all defined rules
- Iterator rules = getRules().rules().iterator();
- while (rules.hasNext()) {
- Rule rule = (Rule) rules.next();
- try {
- rule.finish();
- } catch (Exception e) {
- log.error("Finish event threw exception", e);
- throw createSAXException(e);
- } catch (Error e) {
- log.error("Finish event threw error", e);
- throw e;
- }
- }
-
- // Perform final cleanup
- clear();
-
- }
-
-
- /**
- * Process notification of the end of an XML element being reached.
- *
- * @param namespaceURI - The Namespace URI, or the empty string if the
- * element has no Namespace URI or if Namespace processing is not
- * being performed.
- * @param localName - The local name (without prefix), or the empty
- * string if Namespace processing is not being performed.
- * @param qName - The qualified XML 1.0 name (with prefix), or the
- * empty string if qualified names are not available.
- * @exception SAXException if a parsing error is to be reported
- */
- public void endElement(String namespaceURI, String localName,
- String qName) throws SAXException {
-
- boolean debug = log.isDebugEnabled();
-
- if (debug) {
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("endElement(" + namespaceURI + "," + localName +
- "," + qName + ")");
- }
- log.debug(" match='" + match + "'");
- log.debug(" bodyText='" + bodyText + "'");
- }
-
- // Parse system properties
- bodyText = updateBodyText(bodyText);
-
- // the actual element name is either in localName or qName, depending
- // on whether the parser is namespace aware
- String name = localName;
- if ((name == null) || (name.length() < 1)) {
- name = qName;
- }
-
- // Fire "body" events for all relevant rules
- List rules = (List) matches.pop();
- if ((rules != null) && (rules.size() > 0)) {
- String bodyText = this.bodyText.toString();
- for (int i = 0; i < rules.size(); i++) {
- try {
- Rule rule = (Rule) rules.get(i);
- if (debug) {
- log.debug(" Fire body() for " + rule);
- }
- rule.body(namespaceURI, name, bodyText);
- } catch (Exception e) {
- log.error("Body event threw exception", e);
- throw createSAXException(e);
- } catch (Error e) {
- log.error("Body event threw error", e);
- throw e;
- }
- }
- } else {
- if (debug) {
- log.debug(" No rules found matching '" + match + "'.");
- }
- }
-
- // Recover the body text from the surrounding element
- bodyText = (StringBuilder) bodyTexts.pop();
- if (debug) {
- log.debug(" Popping body text '" + bodyText.toString() + "'");
- }
-
- // Fire "end" events for all relevant rules in reverse order
- if (rules != null) {
- for (int i = 0; i < rules.size(); i++) {
- int j = (rules.size() - i) - 1;
- try {
- Rule rule = (Rule) rules.get(j);
- if (debug) {
- log.debug(" Fire end() for " + rule);
- }
- rule.end(namespaceURI, name);
- } catch (Exception e) {
- log.error("End event threw exception", e);
- throw createSAXException(e);
- } catch (Error e) {
- log.error("End event threw error", e);
- throw e;
- }
- }
- }
-
- // Recover the previous match expression
- int slash = match.lastIndexOf('/');
- if (slash >= 0) {
- match = match.substring(0, slash);
- } else {
- match = "";
- }
-
- }
-
-
- /**
- * Process notification that a namespace prefix is going out of scope.
- *
- * @param prefix Prefix that is going out of scope
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void endPrefixMapping(String prefix) throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("endPrefixMapping(" + prefix + ")");
- }
-
- // Deregister this prefix mapping
- ArrayStack stack = (ArrayStack) namespaces.get(prefix);
- if (stack == null) {
- return;
- }
- try {
- stack.pop();
- if (stack.empty())
- namespaces.remove(prefix);
- } catch (EmptyStackException e) {
- throw createSAXException("endPrefixMapping popped too many times");
- }
-
- }
-
-
- /**
- * Process notification of ignorable whitespace received from the body of
- * an XML element.
- *
- * @param buffer The characters from the XML document
- * @param start Starting offset into the buffer
- * @param len Number of characters from the buffer
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void ignorableWhitespace(char buffer[], int start, int len)
- throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("ignorableWhitespace(" +
- new String(buffer, start, len) + ")");
- }
-
- ; // No processing required
-
- }
-
-
- /**
- * Process notification of a processing instruction that was encountered.
- *
- * @param target The processing instruction target
- * @param data The processing instruction data (if any)
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void processingInstruction(String target, String data)
- throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("processingInstruction('" + target + "','" + data + "')");
- }
-
- ; // No processing is required
-
- }
-
-
- /**
- * Gets the document locator associated with our parser.
- *
- * @return the Locator supplied by the document parser
- */
- public Locator getDocumentLocator() {
-
- return locator;
-
- }
-
- /**
- * Sets the document locator associated with our parser.
- *
- * @param locator The new locator
- */
- public void setDocumentLocator(Locator locator) {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("setDocumentLocator(" + locator + ")");
- }
-
- this.locator = locator;
-
- }
-
-
- /**
- * Process notification of a skipped entity.
- *
- * @param name Name of the skipped entity
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void skippedEntity(String name) throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("skippedEntity(" + name + ")");
- }
-
- ; // No processing required
-
- }
-
-
- /**
- * Process notification of the beginning of the document being reached.
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void startDocument() throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("startDocument()");
- }
-
- // ensure that the digester is properly configured, as
- // the digester could be used as a SAX ContentHandler
- // rather than via the parse() methods.
- configure();
- }
-
-
- /**
- * Process notification of the start of an XML element being reached.
- *
- * @param namespaceURI The Namespace URI, or the empty string if the element
- * has no Namespace URI or if Namespace processing is not being performed.
- * @param localName The local name (without prefix), or the empty
- * string if Namespace processing is not being performed.
- * @param qName The qualified name (with prefix), or the empty
- * string if qualified names are not available.\
- * @param list The attributes attached to the element. If there are
- * no attributes, it shall be an empty Attributes object.
- * @exception SAXException if a parsing error is to be reported
- */
- public void startElement(String namespaceURI, String localName,
- String qName, Attributes list)
- throws SAXException {
- boolean debug = log.isDebugEnabled();
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("startElement(" + namespaceURI + "," + localName + "," +
- qName + ")");
- }
-
- // Parse system properties
- list = updateAttributes(list);
-
- // Save the body text accumulated for our surrounding element
- bodyTexts.push(bodyText);
- if (debug) {
- log.debug(" Pushing body text '" + bodyText.toString() + "'");
- }
- bodyText = new StringBuilder();
-
- // the actual element name is either in localName or qName, depending
- // on whether the parser is namespace aware
- String name = localName;
- if ((name == null) || (name.length() < 1)) {
- name = qName;
- }
-
- // Compute the current matching rule
- StringBuilder sb = new StringBuilder(match);
- if (match.length() > 0) {
- sb.append('/');
- }
- sb.append(name);
- match = sb.toString();
- if (debug) {
- log.debug(" New match='" + match + "'");
- }
-
- // Fire "begin" events for all relevant rules
- List rules = getRules().match(namespaceURI, match);
- matches.push(rules);
- if ((rules != null) && (rules.size() > 0)) {
- for (int i = 0; i < rules.size(); i++) {
- try {
- Rule rule = (Rule) rules.get(i);
- if (debug) {
- log.debug(" Fire begin() for " + rule);
- }
- rule.begin(namespaceURI, name, list);
- } catch (Exception e) {
- log.error("Begin event threw exception", e);
- throw createSAXException(e);
- } catch (Error e) {
- log.error("Begin event threw error", e);
- throw e;
- }
- }
- } else {
- if (debug) {
- log.debug(" No rules found matching '" + match + "'.");
- }
- if (rulesValidation) {
- log.warn(" No rules found matching '" + match + "'.");
- }
- }
-
- }
-
-
- /**
- * Process notification that a namespace prefix is coming in to scope.
- *
- * @param prefix Prefix that is being declared
- * @param namespaceURI Corresponding namespace URI being mapped to
- *
- * @exception SAXException if a parsing error is to be reported
- */
- public void startPrefixMapping(String prefix, String namespaceURI)
- throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")");
- }
-
- // Register this prefix mapping
- ArrayStack stack = (ArrayStack) namespaces.get(prefix);
- if (stack == null) {
- stack = new ArrayStack();
- namespaces.put(prefix, stack);
- }
- stack.push(namespaceURI);
-
- }
-
-
- // ----------------------------------------------------- DTDHandler Methods
-
-
- /**
- * Receive notification of a notation declaration event.
- *
- * @param name The notation name
- * @param publicId The public identifier (if any)
- * @param systemId The system identifier (if any)
- */
- public void notationDecl(String name, String publicId, String systemId) {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("notationDecl(" + name + "," + publicId + "," +
- systemId + ")");
- }
-
- }
-
-
- /**
- * Receive notification of an unparsed entity declaration event.
- *
- * @param name The unparsed entity name
- * @param publicId The public identifier (if any)
- * @param systemId The system identifier (if any)
- * @param notation The name of the associated notation
- */
- public void unparsedEntityDecl(String name, String publicId,
- String systemId, String notation) {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("unparsedEntityDecl(" + name + "," + publicId + "," +
- systemId + "," + notation + ")");
- }
-
- }
-
-
- // ----------------------------------------------- EntityResolver Methods
-
- /**
- * Set the <code>EntityResolver</code> used by SAX when resolving
- * public id and system id.
- * This must be called before the first call to <code>parse()</code>.
- * @param entityResolver a class that implement the <code>EntityResolver</code> interface.
- */
- public void setEntityResolver(EntityResolver entityResolver){
- this.entityResolver = entityResolver;
- }
-
-
- /**
- * Return the Entity Resolver used by the SAX parser.
- * @return Return the Entity Resolver used by the SAX parser.
- */
- public EntityResolver getEntityResolver(){
- return entityResolver;
- }
-
- /**
- * Resolve the requested external entity.
- *
- * @param publicId The public identifier of the entity being referenced
- * @param systemId The system identifier of the entity being referenced
- *
- * @exception SAXException if a parsing exception occurs
- *
- */
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException {
-
- if (saxLog.isDebugEnabled()) {
- saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')");
- }
-
- if (publicId != null)
- this.publicId = publicId;
-
- // Has this system identifier been registered?
- String entityURL = null;
- if (publicId != null) {
- entityURL = (String) entityValidator.get(publicId);
- }
-
- if (entityURL == null) {
- if (systemId == null) {
- // cannot resolve
- if (log.isDebugEnabled()) {
- log.debug(" Cannot resolve entity: '" + entityURL + "'");
- }
- return (null);
-
- } else {
- // try to resolve using system ID
- if (log.isDebugEnabled()) {
- log.debug(" Trying to resolve using system ID '" + systemId + "'");
- }
- entityURL = systemId;
- }
- }
-
- // Return an input source to our alternative URL
- if (log.isDebugEnabled()) {
- log.debug(" Resolving to alternate DTD '" + entityURL + "'");
- }
-
- try {
- return (new InputSource(entityURL));
- } catch (Exception e) {
- throw createSAXException(e);
- }
- }
-
-
- // ------------------------------------------------- ErrorHandler Methods
-
-
- /**
- * Forward notification of a parsing error to the application supplied
- * error handler (if any).
- *
- * @param exception The error information
- *
- * @exception SAXException if a parsing exception occurs
- */
- public void error(SAXParseException exception) throws SAXException {
-
- log.error("Parse Error at line " + exception.getLineNumber() +
- " column " + exception.getColumnNumber() + ": " +
- exception.getMessage(), exception);
- if (errorHandler != null) {
- errorHandler.error(exception);
- }
-
- }
-
-
- /**
- * Forward notification of a fatal parsing error to the application
- * supplied error handler (if any).
- *
- * @param exception The fatal error information
- *
- * @exception SAXException if a parsing exception occurs
- */
- public void fatalError(SAXParseException exception) throws SAXException {
-
- log.error("Parse Fatal Error at line " + exception.getLineNumber() +
- " column " + exception.getColumnNumber() + ": " +
- exception.getMessage(), exception);
- if (errorHandler != null) {
- errorHandler.fatalError(exception);
- }
-
- }
-
-
- /**
- * Forward notification of a parse warning to the application supplied
- * error handler (if any).
- *
- * @param exception The warning information
- *
- * @exception SAXException if a parsing exception occurs
- */
- public void warning(SAXParseException exception) throws SAXException {
- if (errorHandler != null) {
- log.warn("Parse Warning Error at line " + exception.getLineNumber() +
- " column " + exception.getColumnNumber() + ": " +
- exception.getMessage(), exception);
-
- errorHandler.warning(exception);
- }
-
- }
-
-
- // ------------------------------------------------------- Public Methods
-
-
- /**
- * Log a message to our associated logger.
- *
- * @param message The message to be logged
- * @deprecated Call getLogger() and use it's logging methods
- */
- public void log(String message) {
-
- log.info(message);
-
- }
-
-
- /**
- * Log a message and exception to our associated logger.
- *
- * @param message The message to be logged
- * @deprecated Call getLogger() and use it's logging methods
- */
- public void log(String message, Throwable exception) {
-
- log.error(message, exception);
-
- }
-
-
- /**
- * Parse the content of the specified file using this Digester. Returns
- * the root element from the object stack (if any).
- *
- * @param file File containing the XML data to be parsed
- *
- * @exception IOException if an input/output error occurs
- * @exception SAXException if a parsing exception occurs
- */
- public Object parse(File file) throws IOException, SAXException {
-
- configure();
- InputSource input = new InputSource(new FileInputStream(file));
- input.setSystemId("file://" + file.getAbsolutePath());
- getXMLReader().parse(input);
- return (root);
-
- }
- /**
- * Parse the content of the specified input source using this Digester.
- * Returns the root element from the object stack (if any).
- *
- * @param input Input source containing the XML data to be parsed
- *
- * @exception IOException if an input/output error occurs
- * @exception SAXException if a parsing exception occurs
- */
- public Object parse(InputSource input) throws IOException, SAXException {
-
- configure();
- getXMLReader().parse(input);
- return (root);
-
- }
-
-
- /**
- * Parse the content of the specified input stream using this Digester.
- * Returns the root element from the object stack (if any).
- *
- * @param input Input stream containing the XML data to be parsed
- *
- * @exception IOException if an input/output error occurs
- * @exception SAXException if a parsing exception occurs
- */
- public Object parse(InputStream input) throws IOException, SAXException {
-
- configure();
- InputSource is = new InputSource(input);
- getXMLReader().parse(is);
- return (root);
-
- }
-
-
- /**
- * Parse the content of the specified reader using this Digester.
- * Returns the root element from the object stack (if any).
- *
- * @param reader Reader containing the XML data to be parsed
- *
- * @exception IOException if an input/output error occurs
- * @exception SAXException if a parsing exception occurs
- */
- public Object parse(Reader reader) throws IOException, SAXException {
-
- configure();
- InputSource is = new InputSource(reader);
- getXMLReader().parse(is);
- return (root);
-
- }
-
-
- /**
- * Parse the content of the specified URI using this Digester.
- * Returns the root element from the object stack (if any).
- *
- * @param uri URI containing the XML data to be parsed
- *
- * @exception IOException if an input/output error occurs
- * @exception SAXException if a parsing exception occurs
- */
- public Object parse(String uri) throws IOException, SAXException {
-
- configure();
- InputSource is = new InputSource(uri);
- getXMLReader().parse(is);
- return (root);
-
- }
-
-
- /**
- * <p>Register the specified DTD URL for the specified public identifier.
- * This must be called before the first call to <code>parse()</code>.
- * </p><p>
- * <code>Digester</code> contains an internal <code>EntityResolver</code>
- * implementation. This maps <code>PUBLICID</code>'s to URLs
- * (from which the resource will be loaded). A common use case for this
- * method is to register local URLs (possibly computed at runtime by a
- * classloader) for DTDs. This allows the performance advantage of using
- * a local version without having to ensure every <code>SYSTEM</code>
- * URI on every processed xml document is local. This implementation provides
- * only basic functionality. If more sophisticated features are required,
- * using {@link #setEntityResolver} to set a custom resolver is recommended.
- * </p><p>
- * <strong>Note:</strong> This method will have no effect when a custom
- * <code>EntityResolver</code> has been set. (Setting a custom
- * <code>EntityResolver</code> overrides the internal implementation.)
- * </p>
- * @param publicId Public identifier of the DTD to be resolved
- * @param entityURL The URL to use for reading this DTD
- */
- public void register(String publicId, String entityURL) {
-
- if (log.isDebugEnabled()) {
- log.debug("register('" + publicId + "', '" + entityURL + "'");
- }
- entityValidator.put(publicId, entityURL);
-
- }
-
-
- // --------------------------------------------------------- Rule Methods
-
-
- /**
- * <p>Register a new Rule matching the specified pattern.
- * This method sets the <code>Digester</code> property on the rule.</p>
- *
- * @param pattern Element matching pattern
- * @param rule Rule to be registered
- */
- public void addRule(String pattern, Rule rule) {
-
- rule.setDigester(this);
- getRules().add(pattern, rule);
-
- }
-
-
- /**
- * Register a set of Rule instances defined in a RuleSet.
- *
- * @param ruleSet The RuleSet instance to configure from
- */
- public void addRuleSet(RuleSet ruleSet) {
-
- String oldNamespaceURI = getRuleNamespaceURI();
- String newNamespaceURI = ruleSet.getNamespaceURI();
- if (log.isDebugEnabled()) {
- if (newNamespaceURI == null) {
- log.debug("addRuleSet() with no namespace URI");
- } else {
- log.debug("addRuleSet() with namespace URI " + newNamespaceURI);
- }
- }
- setRuleNamespaceURI(newNamespaceURI);
- ruleSet.addRuleInstances(this);
- setRuleNamespaceURI(oldNamespaceURI);
-
- }
-
-
- /**
- * Add an "call method" rule for a method which accepts no arguments.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to be called
- * @see CallMethodRule
- */
- public void addCallMethod(String pattern, String methodName) {
-
- addRule(
- pattern,
- new CallMethodRule(methodName));
-
- }
-
- /**
- * Add an "call method" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to be called
- * @param paramCount Number of expected parameters (or zero
- * for a single parameter from the body of this element)
- * @see CallMethodRule
- */
- public void addCallMethod(String pattern, String methodName,
- int paramCount) {
-
- addRule(pattern,
- new CallMethodRule(methodName, paramCount));
-
- }
-
-
- /**
- * Add an "call method" rule for the specified parameters.
- * If <code>paramCount</code> is set to zero the rule will use
- * the body of the matched element as the single argument of the
- * method, unless <code>paramTypes</code> is null or empty, in this
- * case the rule will call the specified method with no arguments.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to be called
- * @param paramCount Number of expected parameters (or zero
- * for a single parameter from the body of this element)
- * @param paramTypes Set of Java class names for the types
- * of the expected parameters
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- * @see CallMethodRule
- */
- public void addCallMethod(String pattern, String methodName,
- int paramCount, String paramTypes[]) {
-
- addRule(pattern,
- new CallMethodRule(
- methodName,
- paramCount,
- paramTypes));
-
- }
-
-
- /**
- * Add an "call method" rule for the specified parameters.
- * If <code>paramCount</code> is set to zero the rule will use
- * the body of the matched element as the single argument of the
- * method, unless <code>paramTypes</code> is null or empty, in this
- * case the rule will call the specified method with no arguments.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to be called
- * @param paramCount Number of expected parameters (or zero
- * for a single parameter from the body of this element)
- * @param paramTypes The Java class names of the arguments
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- * @see CallMethodRule
- */
- public void addCallMethod(String pattern, String methodName,
- int paramCount, Class paramTypes[]) {
-
- addRule(pattern,
- new CallMethodRule(
- methodName,
- paramCount,
- paramTypes));
-
- }
-
-
- /**
- * Add a "call parameter" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param paramIndex Zero-relative parameter index to set
- * (from the body of this element)
- * @see CallParamRule
- */
- public void addCallParam(String pattern, int paramIndex) {
-
- addRule(pattern,
- new CallParamRule(paramIndex));
-
- }
-
-
- /**
- * Add a "call parameter" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param paramIndex Zero-relative parameter index to set
- * (from the specified attribute)
- * @param attributeName Attribute whose value is used as the
- * parameter value
- * @see CallParamRule
- */
- public void addCallParam(String pattern, int paramIndex,
- String attributeName) {
-
- addRule(pattern,
- new CallParamRule(paramIndex, attributeName));
-
- }
-
-
- /**
- * Add a "call parameter" rule.
- * This will either take a parameter from the stack
- * or from the current element body text.
- *
- * @param paramIndex The zero-relative parameter number
- * @param fromStack Should the call parameter be taken from the top of the stack?
- * @see CallParamRule
- */
- public void addCallParam(String pattern, int paramIndex, boolean fromStack) {
-
- addRule(pattern,
- new CallParamRule(paramIndex, fromStack));
-
- }
-
- /**
- * Add a "call parameter" rule that sets a parameter from the stack.
- * This takes a parameter from the given position on the stack.
- *
- * @param paramIndex The zero-relative parameter number
- * @param stackIndex set the call parameter to the stackIndex'th object down the stack,
- * where 0 is the top of the stack, 1 the next element down and so on
- * @see CallMethodRule
- */
- public void addCallParam(String pattern, int paramIndex, int stackIndex) {
-
- addRule(pattern,
- new CallParamRule(paramIndex, stackIndex));
-
- }
-
- /**
- * Add a "call parameter" rule that sets a parameter from the current
- * <code>Digester</code> matching path.
- * This is sometimes useful when using rules that support wildcards.
- *
- * @param pattern the pattern that this rule should match
- * @param paramIndex The zero-relative parameter number
- * @see CallMethodRule
- */
- public void addCallParamPath(String pattern,int paramIndex) {
- addRule(pattern, new PathCallParamRule(paramIndex));
- }
-
- /**
- * Add a "call parameter" rule that sets a parameter from a
- * caller-provided object. This can be used to pass constants such as
- * strings to methods; it can also be used to pass mutable objects,
- * providing ways for objects to do things like "register" themselves
- * with some shared object.
- * <p>
- * Note that when attempting to locate a matching method to invoke,
- * the true type of the paramObj is used, so that despite the paramObj
- * being passed in here as type Object, the target method can declare
- * its parameters as being the true type of the object (or some ancestor
- * type, according to the usual type-conversion rules).
- *
- * @param paramIndex The zero-relative parameter number
- * @param paramObj Any arbitrary object to be passed to the target
- * method.
- * @see CallMethodRule
- *
- * @since 1.6
- */
- public void addObjectParam(String pattern, int paramIndex,
- Object paramObj) {
-
- addRule(pattern,
- new ObjectParamRule(paramIndex, paramObj));
-
- }
-
- /**
- * Add a "factory create" rule for the specified parameters.
- * Exceptions thrown during the object creation process will be propagated.
- *
- * @param pattern Element matching pattern
- * @param className Java class name of the object creation factory class
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(String pattern, String className) {
-
- addFactoryCreate(pattern, className, false);
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- * Exceptions thrown during the object creation process will be propagated.
- *
- * @param pattern Element matching pattern
- * @param clazz Java class of the object creation factory class
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(String pattern, Class clazz) {
-
- addFactoryCreate(pattern, clazz, false);
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- * Exceptions thrown during the object creation process will be propagated.
- *
- * @param pattern Element matching pattern
- * @param className Java class name of the object creation factory class
- * @param attributeName Attribute name which, if present, overrides the
- * value specified by <code>className</code>
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(String pattern, String className,
- String attributeName) {
-
- addFactoryCreate(pattern, className, attributeName, false);
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- * Exceptions thrown during the object creation process will be propagated.
- *
- * @param pattern Element matching pattern
- * @param clazz Java class of the object creation factory class
- * @param attributeName Attribute name which, if present, overrides the
- * value specified by <code>className</code>
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(String pattern, Class clazz,
- String attributeName) {
-
- addFactoryCreate(pattern, clazz, attributeName, false);
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- * Exceptions thrown during the object creation process will be propagated.
- *
- * @param pattern Element matching pattern
- * @param creationFactory Previously instantiated ObjectCreationFactory
- * to be utilized
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(String pattern,
- ObjectCreationFactory creationFactory) {
-
- addFactoryCreate(pattern, creationFactory, false);
-
- }
-
- /**
- * Add a "factory create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param className Java class name of the object creation factory class
- * @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
- * object creation will be ignored.
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(
- String pattern,
- String className,
- boolean ignoreCreateExceptions) {
-
- addRule(
- pattern,
- new FactoryCreateRule(className, ignoreCreateExceptions));
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param clazz Java class of the object creation factory class
- * @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
- * object creation will be ignored.
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(
- String pattern,
- Class clazz,
- boolean ignoreCreateExceptions) {
-
- addRule(
- pattern,
- new FactoryCreateRule(clazz, ignoreCreateExceptions));
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param className Java class name of the object creation factory class
- * @param attributeName Attribute name which, if present, overrides the
- * value specified by <code>className</code>
- * @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
- * object creation will be ignored.
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(
- String pattern,
- String className,
- String attributeName,
- boolean ignoreCreateExceptions) {
-
- addRule(
- pattern,
- new FactoryCreateRule(className, attributeName, ignoreCreateExceptions));
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param clazz Java class of the object creation factory class
- * @param attributeName Attribute name which, if present, overrides the
- * value specified by <code>className</code>
- * @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
- * object creation will be ignored.
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(
- String pattern,
- Class clazz,
- String attributeName,
- boolean ignoreCreateExceptions) {
-
- addRule(
- pattern,
- new FactoryCreateRule(clazz, attributeName, ignoreCreateExceptions));
-
- }
-
-
- /**
- * Add a "factory create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param creationFactory Previously instantiated ObjectCreationFactory
- * to be utilized
- * @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
- * object creation will be ignored.
- * @see FactoryCreateRule
- */
- public void addFactoryCreate(String pattern,
- ObjectCreationFactory creationFactory,
- boolean ignoreCreateExceptions) {
-
- creationFactory.setDigester(this);
- addRule(pattern,
- new FactoryCreateRule(creationFactory, ignoreCreateExceptions));
-
- }
-
- /**
- * Add an "object create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param className Java class name to be created
- * @see ObjectCreateRule
- */
- public void addObjectCreate(String pattern, String className) {
-
- addRule(pattern,
- new ObjectCreateRule(className));
-
- }
-
-
- /**
- * Add an "object create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param clazz Java class to be created
- * @see ObjectCreateRule
- */
- public void addObjectCreate(String pattern, Class clazz) {
-
- addRule(pattern,
- new ObjectCreateRule(clazz));
-
- }
-
-
- /**
- * Add an "object create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param className Default Java class name to be created
- * @param attributeName Attribute name that optionally overrides
- * the default Java class name to be created
- * @see ObjectCreateRule
- */
- public void addObjectCreate(String pattern, String className,
- String attributeName) {
-
- addRule(pattern,
- new ObjectCreateRule(className, attributeName));
-
- }
-
-
- /**
- * Add an "object create" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param attributeName Attribute name that optionally overrides
- * @param clazz Default Java class to be created
- * the default Java class name to be created
- * @see ObjectCreateRule
- */
- public void addObjectCreate(String pattern,
- String attributeName,
- Class clazz) {
-
- addRule(pattern,
- new ObjectCreateRule(attributeName, clazz));
-
- }
-
- /**
- * Add a "set next" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to call on the parent element
- * @see SetNextRule
- */
- public void addSetNext(String pattern, String methodName) {
-
- addRule(pattern,
- new SetNextRule(methodName));
-
- }
-
-
- /**
- * Add a "set next" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to call on the parent element
- * @param paramType Java class name of the expected parameter type
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- * @see SetNextRule
- */
- public void addSetNext(String pattern, String methodName,
- String paramType) {
-
- addRule(pattern,
- new SetNextRule(methodName, paramType));
-
- }
-
-
- /**
- * Add {@link SetRootRule} with the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to call on the root object
- * @see SetRootRule
- */
- public void addSetRoot(String pattern, String methodName) {
-
- addRule(pattern,
- new SetRootRule(methodName));
-
- }
-
-
- /**
- * Add {@link SetRootRule} with the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to call on the root object
- * @param paramType Java class name of the expected parameter type
- * @see SetRootRule
- */
- public void addSetRoot(String pattern, String methodName,
- String paramType) {
-
- addRule(pattern,
- new SetRootRule(methodName, paramType));
-
- }
-
- /**
- * Add a "set properties" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @see SetPropertiesRule
- */
- public void addSetProperties(String pattern) {
-
- addRule(pattern,
- new SetPropertiesRule());
-
- }
-
- /**
- * Add a "set properties" rule with a single overridden parameter.
- * See {@link SetPropertiesRule#SetPropertiesRule(String attributeName, String propertyName)}
- *
- * @param pattern Element matching pattern
- * @param attributeName map this attribute
- * @param propertyName to this property
- * @see SetPropertiesRule
- */
- public void addSetProperties(
- String pattern,
- String attributeName,
- String propertyName) {
-
- addRule(pattern,
- new SetPropertiesRule(attributeName, propertyName));
-
- }
-
- /**
- * Add a "set properties" rule with overridden parameters.
- * See {@link SetPropertiesRule#SetPropertiesRule(String [] attributeNames, String [] propertyNames)}
- *
- * @param pattern Element matching pattern
- * @param attributeNames names of attributes with custom mappings
- * @param propertyNames property names these attributes map to
- * @see SetPropertiesRule
- */
- public void addSetProperties(
- String pattern,
- String [] attributeNames,
- String [] propertyNames) {
-
- addRule(pattern,
- new SetPropertiesRule(attributeNames, propertyNames));
-
- }
-
-
- /**
- * Add a "set property" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param name Attribute name containing the property name to be set
- * @param value Attribute name containing the property value to set
- * @see SetPropertyRule
- */
- public void addSetProperty(String pattern, String name, String value) {
-
- addRule(pattern,
- new SetPropertyRule(name, value));
-
- }
-
-
- /**
- * Add a "set top" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to call on the parent element
- * @see SetTopRule
- */
- public void addSetTop(String pattern, String methodName) {
-
- addRule(pattern,
- new SetTopRule(methodName));
-
- }
-
-
- /**
- * Add a "set top" rule for the specified parameters.
- *
- * @param pattern Element matching pattern
- * @param methodName Method name to call on the parent element
- * @param paramType Java class name of the expected parameter type
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- * @see SetTopRule
- */
- public void addSetTop(String pattern, String methodName,
- String paramType) {
-
- addRule(pattern,
- new SetTopRule(methodName, paramType));
-
- }
-
-
- // --------------------------------------------------- Object Stack Methods
-
-
- /**
- * Clear the current contents of the object stack.
- * <p>
- * Calling this method <i>might</i> allow another document of the same type
- * to be correctly parsed. However this method was not intended for this
- * purpose. In general, a separate Digester object should be created for
- * each document to be parsed.
- */
- public void clear() {
-
- match = "";
- bodyTexts.clear();
- params.clear();
- publicId = null;
- stack.clear();
- log = null;
- saxLog = null;
- configured = false;
-
- }
-
-
- public void reset() {
- root = null;
- setErrorHandler(null);
- clear();
- }
-
-
- /**
- * Return the top object on the stack without removing it. If there are
- * no objects on the stack, return <code>null</code>.
- */
- public Object peek() {
-
- try {
- return (stack.peek());
- } catch (EmptyStackException e) {
- log.warn("Empty stack (returning null)");
- return (null);
- }
-
- }
-
-
- /**
- * Return the n'th object down the stack, where 0 is the top element
- * and [getCount()-1] is the bottom element. If the specified index
- * is out of range, return <code>null</code>.
- *
- * @param n Index of the desired element, where 0 is the top of the stack,
- * 1 is the next element down, and so on.
- */
- public Object peek(int n) {
-
- try {
- return (stack.peek(n));
- } catch (EmptyStackException e) {
- log.warn("Empty stack (returning null)");
- return (null);
- }
-
- }
-
-
- /**
- * Pop the top object off of the stack, and return it. If there are
- * no objects on the stack, return <code>null</code>.
- */
- public Object pop() {
-
- try {
- return (stack.pop());
- } catch (EmptyStackException e) {
- log.warn("Empty stack (returning null)");
- return (null);
- }
-
- }
-
-
- /**
- * Push a new object onto the top of the object stack.
- *
- * @param object The new object
- */
- public void push(Object object) {
-
- if (stack.size() == 0) {
- root = object;
- }
- stack.push(object);
-
- }
-
- /**
- * Pushes the given object onto the stack with the given name.
- * If no stack already exists with the given name then one will be created.
- *
- * @param stackName the name of the stack onto which the object should be pushed
- * @param value the Object to be pushed onto the named stack.
- *
- * @since 1.6
- */
- public void push(String stackName, Object value) {
- ArrayStack namedStack = (ArrayStack) stacksByName.get(stackName);
- if (namedStack == null) {
- namedStack = new ArrayStack();
- stacksByName.put(stackName, namedStack);
- }
- namedStack.push(value);
- }
-
- /**
- * <p>Pops (gets and removes) the top object from the stack with the given name.</p>
- *
- * <p><strong>Note:</strong> a stack is considered empty
- * if no objects have been pushed onto it yet.</p>
- *
- * @param stackName the name of the stack from which the top value is to be popped
- * @return the top <code>Object</code> on the stack or or null if the stack is either
- * empty or has not been created yet
- * @throws EmptyStackException if the named stack is empty
- *
- * @since 1.6
- */
- public Object pop(String stackName) {
- Object result = null;
- ArrayStack namedStack = (ArrayStack) stacksByName.get(stackName);
- if (namedStack == null) {
- if (log.isDebugEnabled()) {
- log.debug("Stack '" + stackName + "' is empty");
- }
- throw new EmptyStackException();
-
- } else {
-
- result = namedStack.pop();
- }
- return result;
- }
-
- /**
- * <p>Gets the top object from the stack with the given name.
- * This method does not remove the object from the stack.
- * </p>
- * <p><strong>Note:</strong> a stack is considered empty
- * if no objects have been pushed onto it yet.</p>
- *
- * @param stackName the name of the stack to be peeked
- * @return the top <code>Object</code> on the stack or null if the stack is either
- * empty or has not been created yet
- * @throws EmptyStackException if the named stack is empty
- *
- * @since 1.6
- */
- public Object peek(String stackName) {
- Object result = null;
- ArrayStack namedStack = (ArrayStack) stacksByName.get(stackName);
- if (namedStack == null ) {
- if (log.isDebugEnabled()) {
- log.debug("Stack '" + stackName + "' is empty");
- }
- throw new EmptyStackException();
-
- } else {
-
- result = namedStack.peek();
- }
- return result;
- }
-
- /**
- * <p>Is the stack with the given name empty?</p>
- * <p><strong>Note:</strong> a stack is considered empty
- * if no objects have been pushed onto it yet.</p>
- * @param stackName the name of the stack whose emptiness
- * should be evaluated
- * @return true if the given stack if empty
- *
- * @since 1.6
- */
- public boolean isEmpty(String stackName) {
- boolean result = true;
- ArrayStack namedStack = (ArrayStack) stacksByName.get(stackName);
- if (namedStack != null ) {
- result = namedStack.isEmpty();
- }
- return result;
- }
-
- /**
- * When the Digester is being used as a SAXContentHandler,
- * this method allows you to access the root object that has been
- * created after parsing.
- *
- * @return the root object that has been created after parsing
- * or null if the digester has not parsed any XML yet.
- */
- public Object getRoot() {
- return root;
- }
-
-
- // ------------------------------------------------ Parameter Stack Methods
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * <p>
- * Provide a hook for lazy configuration of this <code>Digester</code>
- * instance. The default implementation does nothing, but subclasses
- * can override as needed.
- * </p>
- *
- * <p>
- * <strong>Note</strong> This method may be called more than once.
- * Once only initialization code should be placed in {@link #initialize}
- * or the code should take responsibility by checking and setting the
- * {@link #configured} flag.
- * </p>
- */
- protected void configure() {
-
- // Do not configure more than once
- if (configured) {
- return;
- }
-
- log = Logger.getLogger("org.apache.commons.digester.Digester");
- saxLog = Logger.getLogger("org.apache.commons.digester.Digester.sax");
-
- // Perform lazy configuration as needed
- initialize(); // call hook method for subclasses that want to be initialized once only
- // Nothing else required by default
-
- // Set the configuration flag to avoid repeating
- configured = true;
-
- }
-
- /**
- * <p>
- * Provides a hook for lazy initialization of this <code>Digester</code>
- * instance.
- * The default implementation does nothing, but subclasses
- * can override as needed.
- * Digester (by default) only calls this method once.
- * </p>
- *
- * <p>
- * <strong>Note</strong> This method will be called by {@link #configure}
- * only when the {@link #configured} flag is false.
- * Subclasses that override <code>configure</code> or who set <code>configured</code>
- * may find that this method may be called more than once.
- * </p>
- *
- * @since 1.6
- */
- protected void initialize() {
-
- // Perform lazy initialization as needed
- ; // Nothing required by default
-
- }
-
- // -------------------------------------------------------- Package Methods
-
-
- /**
- * Return the set of DTD URL registrations, keyed by public identifier.
- */
- Map getRegistrations() {
-
- return (entityValidator);
-
- }
-
-
- /**
- * Return the set of rules that apply to the specified match position.
- * The selected rules are those that match exactly, or those rules
- * that specify a suffix match and the tail of the rule matches the
- * current match position. Exact matches have precedence over
- * suffix matches, then (among suffix matches) the longest match
- * is preferred.
- *
- * @param match The current match position
- *
- * @deprecated Call <code>match()</code> on the <code>Rules</code>
- * implementation returned by <code>getRules()</code>
- */
- List getRules(String match) {
-
- return (getRules().match(match));
-
- }
-
-
- /**
- * <p>Return the top object on the parameters stack without removing it. If there are
- * no objects on the stack, return <code>null</code>.</p>
- *
- * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
- * See {@link #params}.</p>
- */
- public Object peekParams() {
-
- try {
- return (params.peek());
- } catch (EmptyStackException e) {
- log.warn("Empty stack (returning null)");
- return (null);
- }
-
- }
-
-
- /**
- * <p>Return the n'th object down the parameters stack, where 0 is the top element
- * and [getCount()-1] is the bottom element. If the specified index
- * is out of range, return <code>null</code>.</p>
- *
- * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
- * See {@link #params}.</p>
- *
- * @param n Index of the desired element, where 0 is the top of the stack,
- * 1 is the next element down, and so on.
- */
- public Object peekParams(int n) {
-
- try {
- return (params.peek(n));
- } catch (EmptyStackException e) {
- log.warn("Empty stack (returning null)");
- return (null);
- }
-
- }
-
-
- /**
- * <p>Pop the top object off of the parameters stack, and return it. If there are
- * no objects on the stack, return <code>null</code>.</p>
- *
- * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
- * See {@link #params}.</p>
- */
- public Object popParams() {
-
- try {
- if (log.isTraceEnabled()) {
- log.trace("Popping params");
- }
- return (params.pop());
- } catch (EmptyStackException e) {
- log.warn("Empty stack (returning null)");
- return (null);
- }
-
- }
-
-
- /**
- * <p>Push a new object onto the top of the parameters stack.</p>
- *
- * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
- * See {@link #params}.</p>
- *
- * @param object The new object
- */
- public void pushParams(Object object) {
- if (log.isTraceEnabled()) {
- log.trace("Pushing params");
- }
- params.push(object);
-
- }
-
- /**
- * Create a SAX exception which also understands about the location in
- * the digester file where the exception occurs
- *
- * @return the new exception
- */
- public SAXException createSAXException(String message, Exception e) {
- if ((e != null) &&
- (e instanceof InvocationTargetException)) {
- Throwable t = ((InvocationTargetException) e).getTargetException();
- if ((t != null) && (t instanceof Exception)) {
- e = (Exception) t;
- }
- }
- if (locator != null) {
- String error = "Error at (" + locator.getLineNumber() + ", " +
- locator.getColumnNumber() + ": " + message;
- if (e != null) {
- return new SAXParseException(error, locator, e);
- } else {
- return new SAXParseException(error, locator);
- }
- }
- log.error("No Locator!");
- if (e != null) {
- return new SAXException(message, e);
- } else {
- return new SAXException(message);
- }
- }
-
- /**
- * Create a SAX exception which also understands about the location in
- * the digester file where the exception occurs
- *
- * @return the new exception
- */
- public SAXException createSAXException(Exception e) {
- if (e instanceof InvocationTargetException) {
- Throwable t = ((InvocationTargetException) e).getTargetException();
- if ((t != null) && (t instanceof Exception)) {
- e = (Exception) t;
- }
- }
- return createSAXException(e.getMessage(), e);
- }
-
- /**
- * Create a SAX exception which also understands about the location in
- * the digester file where the exception occurs
- *
- * @return the new exception
- */
- public SAXException createSAXException(String message) {
- return createSAXException(message, null);
- }
-
-
- // ------------------------------------------------------- Private Methods
-
-
- /**
- * Returns an attributes list which contains all the attributes
- * passed in, with any text of form "${xxx}" in an attribute value
- * replaced by the appropriate value from the system property.
- */
- private Attributes updateAttributes(Attributes list) {
-
- if (list.getLength() == 0) {
- return list;
- }
-
- AttributesImpl newAttrs = new AttributesImpl(list);
- int nAttributes = newAttrs.getLength();
- for (int i = 0; i < nAttributes; ++i) {
- String value = newAttrs.getValue(i);
- try {
- String newValue =
- IntrospectionUtils.replaceProperties(value, null, source);
- if (value != newValue) {
- newAttrs.setValue(i, newValue);
- }
- }
- catch (Exception e) {
- // ignore - let the attribute have its original value
- }
- }
-
- return newAttrs;
-
- }
-
-
- /**
- * Return a new StringBuilder containing the same contents as the
- * input buffer, except that data of form ${varname} have been
- * replaced by the value of that var as defined in the system property.
- */
- private StringBuilder updateBodyText(StringBuilder bodyText) {
- String in = bodyText.toString();
- String out;
- try {
- out = IntrospectionUtils.replaceProperties(in, null, source);
- } catch(Exception e) {
- return bodyText; // return unchanged data
- }
-
- if (out == in) {
- // No substitutions required. Don't waste memory creating
- // a new buffer
- return bodyText;
- } else {
- return new StringBuilder(out);
- }
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/FactoryCreateRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/FactoryCreateRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/FactoryCreateRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,496 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import org.xml.sax.Attributes;
-
-
-/**
- * <p>Rule implementation that uses an {@link ObjectCreationFactory} to create
- * a new object which it pushes onto the object stack. When the element is
- * complete, the object will be popped.</p>
- *
- * <p>This rule is intended in situations where the element's attributes are
- * needed before the object can be created. A common senario is for the
- * ObjectCreationFactory implementation to use the attributes as parameters
- * in a call to either a factory method or to a non-empty constructor.
- */
-
-public class FactoryCreateRule extends Rule {
-
- // ----------------------------------------------------------- Fields
-
- /** Should exceptions thrown by the factory be ignored? */
- private boolean ignoreCreateExceptions;
- /** Stock to manage */
- private ArrayStack exceptionIgnoredStack;
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class name to create an {@link ObjectCreationFactory} which will
- * then be used to create an object and push it on the stack.
- *
- * @param digester The associated Digester
- * @param className Java class name of the object creation factory class
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #FactoryCreateRule(String className)} instead.
- */
- public FactoryCreateRule(Digester digester, String className) {
-
- this(className);
-
- }
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class to create an {@link ObjectCreationFactory} which will
- * then be used to create an object and push it on the stack.
- *
- * @param digester The associated Digester
- * @param clazz Java class name of the object creation factory class
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #FactoryCreateRule(Class clazz)} instead.
- */
- public FactoryCreateRule(Digester digester, Class clazz) {
-
- this(clazz);
-
- }
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class name (possibly overridden by the specified attribute if present)
- * to create an {@link ObjectCreationFactory}, which will then be used
- * to instantiate an object instance and push it onto the stack.
- *
- * @param digester The associated Digester
- * @param className Default Java class name of the factory class
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name of the object creation factory to create.
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #FactoryCreateRule(String className, String attributeName)} instead.
- */
- public FactoryCreateRule(Digester digester,
- String className, String attributeName) {
-
- this(className, attributeName);
-
- }
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class (possibly overridden by the specified attribute if present)
- * to create an {@link ObjectCreationFactory}, which will then be used
- * to instantiate an object instance and push it onto the stack.
- *
- * @param digester The associated Digester
- * @param clazz Default Java class name of the factory class
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name of the object creation factory to create.
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #FactoryCreateRule(Class clazz, String attributeName)} instead.
- */
- public FactoryCreateRule(Digester digester,
- Class clazz, String attributeName) {
-
- this(clazz, attributeName);
-
- }
-
-
- /**
- * Construct a factory create rule using the given, already instantiated,
- * {@link ObjectCreationFactory}.
- *
- * @param digester The associated Digester
- * @param creationFactory called on to create the object.
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #FactoryCreateRule(ObjectCreationFactory creationFactory)} instead.
- */
- public FactoryCreateRule(Digester digester,
- ObjectCreationFactory creationFactory) {
-
- this(creationFactory);
-
- }
-
- /**
- * <p>Construct a factory create rule that will use the specified
- * class name to create an {@link ObjectCreationFactory} which will
- * then be used to create an object and push it on the stack.</p>
- *
- * <p>Exceptions thrown during the object creation process will be propagated.</p>
- *
- * @param className Java class name of the object creation factory class
- */
- public FactoryCreateRule(String className) {
-
- this(className, false);
-
- }
-
-
- /**
- * <p>Construct a factory create rule that will use the specified
- * class to create an {@link ObjectCreationFactory} which will
- * then be used to create an object and push it on the stack.</p>
- *
- * <p>Exceptions thrown during the object creation process will be propagated.</p>
- *
- * @param clazz Java class name of the object creation factory class
- */
- public FactoryCreateRule(Class clazz) {
-
- this(clazz, false);
-
- }
-
-
- /**
- * <p>Construct a factory create rule that will use the specified
- * class name (possibly overridden by the specified attribute if present)
- * to create an {@link ObjectCreationFactory}, which will then be used
- * to instantiate an object instance and push it onto the stack.</p>
- *
- * <p>Exceptions thrown during the object creation process will be propagated.</p>
- *
- * @param className Default Java class name of the factory class
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name of the object creation factory to create.
- */
- public FactoryCreateRule(String className, String attributeName) {
-
- this(className, attributeName, false);
-
- }
-
-
- /**
- * <p>Construct a factory create rule that will use the specified
- * class (possibly overridden by the specified attribute if present)
- * to create an {@link ObjectCreationFactory}, which will then be used
- * to instantiate an object instance and push it onto the stack.</p>
- *
- * <p>Exceptions thrown during the object creation process will be propagated.</p>
- *
- * @param clazz Default Java class name of the factory class
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name of the object creation factory to create.
- */
- public FactoryCreateRule(Class clazz, String attributeName) {
-
- this(clazz, attributeName, false);
-
- }
-
-
- /**
- * <p>Construct a factory create rule using the given, already instantiated,
- * {@link ObjectCreationFactory}.</p>
- *
- * <p>Exceptions thrown during the object creation process will be propagated.</p>
- *
- * @param creationFactory called on to create the object.
- */
- public FactoryCreateRule(ObjectCreationFactory creationFactory) {
-
- this(creationFactory, false);
-
- }
-
- /**
- * Construct a factory create rule that will use the specified
- * class name to create an {@link ObjectCreationFactory} which will
- * then be used to create an object and push it on the stack.
- *
- * @param className Java class name of the object creation factory class
- * @param ignoreCreateExceptions if true, exceptions thrown by the object
- * creation factory
- * will be ignored.
- */
- public FactoryCreateRule(String className, boolean ignoreCreateExceptions) {
-
- this(className, null, ignoreCreateExceptions);
-
- }
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class to create an {@link ObjectCreationFactory} which will
- * then be used to create an object and push it on the stack.
- *
- * @param clazz Java class name of the object creation factory class
- * @param ignoreCreateExceptions if true, exceptions thrown by the
- * object creation factory
- * will be ignored.
- */
- public FactoryCreateRule(Class clazz, boolean ignoreCreateExceptions) {
-
- this(clazz, null, ignoreCreateExceptions);
-
- }
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class name (possibly overridden by the specified attribute if present)
- * to create an {@link ObjectCreationFactory}, which will then be used
- * to instantiate an object instance and push it onto the stack.
- *
- * @param className Default Java class name of the factory class
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name of the object creation factory to create.
- * @param ignoreCreateExceptions if true, exceptions thrown by the object
- * creation factory will be ignored.
- */
- public FactoryCreateRule(
- String className,
- String attributeName,
- boolean ignoreCreateExceptions) {
-
- this.className = className;
- this.attributeName = attributeName;
- this.ignoreCreateExceptions = ignoreCreateExceptions;
-
- }
-
-
- /**
- * Construct a factory create rule that will use the specified
- * class (possibly overridden by the specified attribute if present)
- * to create an {@link ObjectCreationFactory}, which will then be used
- * to instantiate an object instance and push it onto the stack.
- *
- * @param clazz Default Java class name of the factory class
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name of the object creation factory to create.
- * @param ignoreCreateExceptions if true, exceptions thrown by the object
- * creation factory will be ignored.
- */
- public FactoryCreateRule(
- Class clazz,
- String attributeName,
- boolean ignoreCreateExceptions) {
-
- this(clazz.getName(), attributeName, ignoreCreateExceptions);
-
- }
-
-
- /**
- * Construct a factory create rule using the given, already instantiated,
- * {@link ObjectCreationFactory}.
- *
- * @param creationFactory called on to create the object.
- * @param ignoreCreateExceptions if true, exceptions thrown by the object
- * creation factory will be ignored.
- */
- public FactoryCreateRule(
- ObjectCreationFactory creationFactory,
- boolean ignoreCreateExceptions) {
-
- this.creationFactory = creationFactory;
- this.ignoreCreateExceptions = ignoreCreateExceptions;
- }
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The attribute containing an override class name if it is present.
- */
- protected String attributeName = null;
-
-
- /**
- * The Java class name of the ObjectCreationFactory to be created.
- * This class must have a no-arguments constructor.
- */
- protected String className = null;
-
-
- /**
- * The object creation factory we will use to instantiate objects
- * as required based on the attributes specified in the matched XML
- * element.
- */
- protected ObjectCreationFactory creationFactory = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Process the beginning of this element.
- *
- * @param attributes The attribute list of this element
- */
- public void begin(String namespace, String name, Attributes attributes) throws Exception {
-
- if (ignoreCreateExceptions) {
-
- if (exceptionIgnoredStack == null) {
- exceptionIgnoredStack = new ArrayStack();
- }
-
- try {
- Object instance = getFactory(attributes).createObject(attributes);
-
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[FactoryCreateRule]{" + digester.match +
- "} New " + instance.getClass().getName());
- }
- digester.push(instance);
- exceptionIgnoredStack.push(Boolean.FALSE);
-
- } catch (Exception e) {
- // log message and error
- if (digester.log.isInfoEnabled()) {
- digester.log.info("[FactoryCreateRule] Create exception ignored: " +
- ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage()));
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[FactoryCreateRule] Ignored exception:", e);
- }
- }
- exceptionIgnoredStack.push(Boolean.TRUE);
- }
-
- } else {
- Object instance = getFactory(attributes).createObject(attributes);
-
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[FactoryCreateRule]{" + digester.match +
- "} New " + instance.getClass().getName());
- }
- digester.push(instance);
- }
- }
-
-
- /**
- * Process the end of this element.
- */
- public void end(String namespace, String name) throws Exception {
-
- // check if object was created
- // this only happens if an exception was thrown and we're ignoring them
- if (
- ignoreCreateExceptions &&
- exceptionIgnoredStack != null &&
- !(exceptionIgnoredStack.empty())) {
-
- if (((Boolean) exceptionIgnoredStack.pop()).booleanValue()) {
- // creation exception was ignored
- // nothing was put onto the stack
- if (digester.log.isTraceEnabled()) {
- digester.log.trace("[FactoryCreateRule] No creation so no push so no pop");
- }
- return;
- }
- }
-
- Object top = digester.pop();
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[FactoryCreateRule]{" + digester.match +
- "} Pop " + top.getClass().getName());
- }
-
- }
-
-
- /**
- * Clean up after parsing is complete.
- */
- public void finish() throws Exception {
-
- if (attributeName != null) {
- creationFactory = null;
- }
-
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("FactoryCreateRule[");
- sb.append("className=");
- sb.append(className);
- sb.append(", attributeName=");
- sb.append(attributeName);
- if (creationFactory != null) {
- sb.append(", creationFactory=");
- sb.append(creationFactory);
- }
- sb.append("]");
- return (sb.toString());
-
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Return an instance of our associated object creation factory,
- * creating one if necessary.
- *
- * @param attributes Attributes passed to our factory creation element
- *
- * @exception Exception if any error occurs
- */
- protected ObjectCreationFactory getFactory(Attributes attributes)
- throws Exception {
-
- if (creationFactory == null) {
- String realClassName = className;
- if (attributeName != null) {
- String value = attributes.getValue(attributeName);
- if (value != null) {
- realClassName = value;
- }
- }
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[FactoryCreateRule]{" + digester.match +
- "} New factory " + realClassName);
- }
- Class clazz = digester.getClassLoader().loadClass(realClassName);
- creationFactory = (ObjectCreationFactory)
- clazz.newInstance();
- creationFactory.setDigester(digester);
- }
- return (creationFactory);
-
- }
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/GenericParser.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/GenericParser.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/GenericParser.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,87 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import java.util.Properties;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-
-/**
- * Create a <code>SAXParser</code> configured to support XML Schema and DTD.
- *
- * @since 1.6
- */
-
-public class GenericParser{
-
- /**
- * The Log to which all SAX event related logging calls will be made.
- */
- protected static Logger log =
- Logger.getLogger("org.apache.commons.digester.Digester.sax");
-
- /**
- * The JAXP 1.2 property required to set up the schema location.
- */
- private static final String JAXP_SCHEMA_SOURCE =
- "http://java.sun.com/xml/jaxp/properties/schemaSource";
-
- /**
- * The JAXP 1.2 property to set up the schemaLanguage used.
- */
- protected static String JAXP_SCHEMA_LANGUAGE =
- "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
-
- /**
- * Create a <code>SAXParser</code> configured to support XML Scheman and DTD
- * @param properties parser specific properties/features
- * @return an XML Schema/DTD enabled <code>SAXParser</code>
- */
- public static SAXParser newSAXParser(Properties properties)
- throws ParserConfigurationException,
- SAXException,
- SAXNotRecognizedException{
-
- SAXParserFactory factory =
- (SAXParserFactory)properties.get("SAXParserFactory");
- SAXParser parser = factory.newSAXParser();
- String schemaLocation = (String)properties.get("schemaLocation");
- String schemaLanguage = (String)properties.get("schemaLanguage");
-
- try{
- if (schemaLocation != null) {
- parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
- parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
- }
- } catch (SAXNotRecognizedException e){
- log.info(parser.getClass().getName() + ": "
- + e.getMessage() + " not supported.");
- }
- return parser;
- }
-
-}
\ No newline at end of file
Deleted: trunk/java/org/apache/tomcat/util/digester/NodeCreateRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/NodeCreateRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/NodeCreateRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,429 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.w3c.dom.Attr;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.DefaultHandler;
-
-
-/**
- * A rule implementation that creates a DOM
- * {@link org.w3c.dom.Node Node} containing the XML at the element that matched
- * the rule. Two concrete types of nodes can be created by this rule:
- * <ul>
- * <li>the default is to create an {@link org.w3c.dom.Element Element} node.
- * The created element will correspond to the element that matched the rule,
- * containing all XML content underneath that element.</li>
- * <li>alternatively, this rule can create nodes of type
- * {@link org.w3c.dom.DocumentFragment DocumentFragment}, which will contain
- * only the XML content under the element the rule was trigged on.</li>
- * </ul>
- * The created node will be normalized, meaning it will not contain text nodes
- * that only contain white space characters.
- *
-
- *
- * <p>The created <code>Node</code> will be pushed on Digester's object stack
- * when done. To use it in the context of another DOM
- * {@link org.w3c.dom.Document Document}, it must be imported first, using the
- * Document method
- * {@link org.w3c.dom.Document#importNode(org.w3c.dom.Node, boolean) importNode()}.
- * </p>
- *
- * <p><strong>Important Note:</strong> This is implemented by replacing the SAX
- * {@link org.xml.sax.ContentHandler ContentHandler} in the parser used by
- * Digester, and resetting it when the matched element is closed. As a side
- * effect, rules that would match XML nodes under the element that matches
- * a <code>NodeCreateRule</code> will never be triggered by Digester, which
- * usually is the behavior one would expect.</p>
- *
- * <p><strong>Note</strong> that the current implementation does not set the namespace prefixes
- * in the exported nodes. The (usually more important) namespace URIs are set,
- * of course.</p>
- *
- * @since Digester 1.4
- */
-
-public class NodeCreateRule extends Rule {
-
-
- // ---------------------------------------------------------- Inner Classes
-
-
- /**
- * The SAX content handler that does all the actual work of assembling the
- * DOM node tree from the SAX events.
- */
- private class NodeBuilder
- extends DefaultHandler {
-
-
- // ------------------------------------------------------- Constructors
-
-
- /**
- * Constructor.
- *
- * <p>Stores the content handler currently used by Digester so it can
- * be reset when done, and initializes the DOM objects needed to
- * build the node.</p>
- *
- * @param doc the document to use to create nodes
- * @param root the root node
- * @throws ParserConfigurationException if the DocumentBuilderFactory
- * could not be instantiated
- * @throws SAXException if the XMLReader could not be instantiated by
- * Digester (should not happen)
- */
- public NodeBuilder(Document doc, Node root)
- throws ParserConfigurationException, SAXException {
-
- this.doc = doc;
- this.root = root;
- this.top = root;
-
- oldContentHandler = digester.getXMLReader().getContentHandler();
-
- }
-
-
- // ------------------------------------------------- Instance Variables
-
-
- /**
- * The content handler used by Digester before it was set to this
- * content handler.
- */
- protected ContentHandler oldContentHandler = null;
-
-
- /**
- * Depth of the current node, relative to the element where the content
- * handler was put into action.
- */
- protected int depth = 0;
-
-
- /**
- * A DOM Document used to create the various Node instances.
- */
- protected Document doc = null;
-
-
- /**
- * The DOM node that will be pushed on Digester's stack.
- */
- protected Node root = null;
-
-
- /**
- * The current top DOM mode.
- */
- protected Node top = null;
-
-
- // --------------------------------------------- ContentHandler Methods
-
-
- /**
- * Appends a {@link org.w3c.dom.Text Text} node to the current node.
- *
- * @param ch the characters from the XML document
- * @param start the start position in the array
- * @param length the number of characters to read from the array
- * @throws SAXException if the DOM implementation throws an exception
- */
- public void characters(char[] ch, int start, int length)
- throws SAXException {
-
- try {
- String str = new String(ch, start, length);
- if (str.trim().length() > 0) {
- top.appendChild(doc.createTextNode(str));
- }
- } catch (DOMException e) {
- throw new SAXException(e.getMessage());
- }
-
- }
-
-
- /**
- * Checks whether control needs to be returned to Digester.
- *
- * @param namespaceURI the namespace URI
- * @param localName the local name
- * @param qName the qualified (prefixed) name
- * @throws SAXException if the DOM implementation throws an exception
- */
- public void endElement(String namespaceURI, String localName,
- String qName)
- throws SAXException {
-
- try {
- if (depth == 0) {
- getDigester().getXMLReader().setContentHandler(
- oldContentHandler);
- getDigester().push(root);
- getDigester().endElement(namespaceURI, localName, qName);
- }
-
- top = top.getParentNode();
- depth--;
- } catch (DOMException e) {
- throw new SAXException(e.getMessage());
- }
-
- }
-
-
- /**
- * Adds a new
- * {@link org.w3c.dom.ProcessingInstruction ProcessingInstruction} to
- * the current node.
- *
- * @param target the processing instruction target
- * @param data the processing instruction data, or null if none was
- * supplied
- * @throws SAXException if the DOM implementation throws an exception
- */
- public void processingInstruction(String target, String data)
- throws SAXException {
-
- try {
- top.appendChild(doc.createProcessingInstruction(target, data));
- } catch (DOMException e) {
- throw new SAXException(e.getMessage());
- }
-
- }
-
-
- /**
- * Adds a new child {@link org.w3c.dom.Element Element} to the current
- * node.
- *
- * @param namespaceURI the namespace URI
- * @param localName the local name
- * @param qName the qualified (prefixed) name
- * @param atts the list of attributes
- * @throws SAXException if the DOM implementation throws an exception
- */
- public void startElement(String namespaceURI, String localName,
- String qName, Attributes atts)
- throws SAXException {
-
- try {
- Node previousTop = top;
- if ((localName == null) || (localName.length() == 0)) {
- top = doc.createElement(qName);
- } else {
- top = doc.createElementNS(namespaceURI, localName);
- }
- for (int i = 0; i < atts.getLength(); i++) {
- Attr attr = null;
- if ((atts.getLocalName(i) == null) ||
- (atts.getLocalName(i).length() == 0)) {
- attr = doc.createAttribute(atts.getQName(i));
- attr.setNodeValue(atts.getValue(i));
- ((Element)top).setAttributeNode(attr);
- } else {
- attr = doc.createAttributeNS(atts.getURI(i),
- atts.getLocalName(i));
- attr.setNodeValue(atts.getValue(i));
- ((Element)top).setAttributeNodeNS(attr);
- }
- }
- previousTop.appendChild(top);
- depth++;
- } catch (DOMException e) {
- throw new SAXException(e.getMessage());
- }
-
- }
-
- }
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Default constructor. Creates an instance of this rule that will create a
- * DOM {@link org.w3c.dom.Element Element}.
- */
- public NodeCreateRule() throws ParserConfigurationException {
-
- this(Node.ELEMENT_NODE);
-
- }
-
-
- /**
- * Constructor. Creates an instance of this rule that will create a DOM
- * {@link org.w3c.dom.Element Element}, but lets you specify the JAXP
- * <code>DocumentBuilder</code> that should be used when constructing the
- * node tree.
- *
- * @param documentBuilder the JAXP <code>DocumentBuilder</code> to use
- */
- public NodeCreateRule(DocumentBuilder documentBuilder) {
-
- this(Node.ELEMENT_NODE, documentBuilder);
-
- }
-
-
- /**
- * Constructor. Creates an instance of this rule that will create either a
- * DOM {@link org.w3c.dom.Element Element} or a DOM
- * {@link org.w3c.dom.DocumentFragment DocumentFragment}, depending on the
- * value of the <code>nodeType</code> parameter.
- *
- * @param nodeType the type of node to create, which can be either
- * {@link org.w3c.dom.Node#ELEMENT_NODE Node.ELEMENT_NODE} or
- * {@link org.w3c.dom.Node#DOCUMENT_FRAGMENT_NODE Node.DOCUMENT_FRAGMENT_NODE}
- * @throws IllegalArgumentException if the node type is not supported
- */
- public NodeCreateRule(int nodeType) throws ParserConfigurationException {
-
- this(nodeType,
- DocumentBuilderFactory.newInstance().newDocumentBuilder());
-
- }
-
-
- /**
- * Constructor. Creates an instance of this rule that will create either a
- * DOM {@link org.w3c.dom.Element Element} or a DOM
- * {@link org.w3c.dom.DocumentFragment DocumentFragment}, depending on the
- * value of the <code>nodeType</code> parameter. This constructor lets you
- * specify the JAXP <code>DocumentBuilder</code> that should be used when
- * constructing the node tree.
- *
- * @param nodeType the type of node to create, which can be either
- * {@link org.w3c.dom.Node#ELEMENT_NODE Node.ELEMENT_NODE} or
- * {@link org.w3c.dom.Node#DOCUMENT_FRAGMENT_NODE Node.DOCUMENT_FRAGMENT_NODE}
- * @param documentBuilder the JAXP <code>DocumentBuilder</code> to use
- * @throws IllegalArgumentException if the node type is not supported
- */
- public NodeCreateRule(int nodeType, DocumentBuilder documentBuilder) {
-
- if (!((nodeType == Node.DOCUMENT_FRAGMENT_NODE) ||
- (nodeType == Node.ELEMENT_NODE))) {
- throw new IllegalArgumentException(
- "Can only create nodes of type DocumentFragment and Element");
- }
- this.nodeType = nodeType;
- this.documentBuilder = documentBuilder;
-
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The JAXP <code>DocumentBuilder</code> to use.
- */
- private DocumentBuilder documentBuilder = null;
-
-
- /**
- * The type of the node that should be created. Must be one of the
- * constants defined in {@link org.w3c.dom.Node Node}, but currently only
- * {@link org.w3c.dom.Node#ELEMENT_NODE Node.ELEMENT_NODE} and
- * {@link org.w3c.dom.Node#DOCUMENT_FRAGMENT_NODE Node.DOCUMENT_FRAGMENT_NODE}
- * are allowed values.
- */
- private int nodeType = Node.ELEMENT_NODE;
-
-
- // ----------------------------------------------------------- Rule Methods
-
-
- /**
- * Implemented to replace the content handler currently in use by a
- * NodeBuilder.
- *
- * @param namespaceURI the namespace URI of the matching element, or an
- * empty string if the parser is not namespace aware or the element has
- * no namespace
- * @param name the local name if the parser is namespace aware, or just
- * the element name otherwise
- * @param attributes The attribute list of this element
- * @throws Exception indicates a JAXP configuration problem
- */
- public void begin(String namespaceURI, String name, Attributes attributes)
- throws Exception {
-
- XMLReader xmlReader = getDigester().getXMLReader();
- Document doc = documentBuilder.newDocument();
- NodeBuilder builder = null;
- if (nodeType == Node.ELEMENT_NODE) {
- Element element = null;
- if (getDigester().getNamespaceAware()) {
- element =
- doc.createElementNS(namespaceURI, name);
- for (int i = 0; i < attributes.getLength(); i++) {
- element.setAttributeNS(attributes.getURI(i),
- attributes.getLocalName(i),
- attributes.getValue(i));
- }
- } else {
- element = doc.createElement(name);
- for (int i = 0; i < attributes.getLength(); i++) {
- element.setAttribute(attributes.getQName(i),
- attributes.getValue(i));
- }
- }
- builder = new NodeBuilder(doc, element);
- } else {
- builder = new NodeBuilder(doc, doc.createDocumentFragment());
- }
- xmlReader.setContentHandler(builder);
-
- }
-
-
- /**
- * Pop the Node off the top of the stack.
- */
- public void end() throws Exception {
-
- Object top = digester.pop();
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/ObjectCreateRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/ObjectCreateRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/ObjectCreateRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,242 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.xml.sax.Attributes;
-
-
-/**
- * Rule implementation that creates a new object and pushes it
- * onto the object stack. When the element is complete, the
- * object will be popped
- */
-
-public class ObjectCreateRule extends Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct an object create rule with the specified class name.
- *
- * @param digester The associated Digester
- * @param className Java class name of the object to be created
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #ObjectCreateRule(String className)} instead.
- */
- public ObjectCreateRule(Digester digester, String className) {
-
- this(className);
-
- }
-
-
- /**
- * Construct an object create rule with the specified class.
- *
- * @param digester The associated Digester
- * @param clazz Java class name of the object to be created
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #ObjectCreateRule(Class clazz)} instead.
- */
- public ObjectCreateRule(Digester digester, Class clazz) {
-
- this(clazz);
-
- }
-
-
- /**
- * Construct an object create rule with the specified class name and an
- * optional attribute name containing an override.
- *
- * @param digester The associated Digester
- * @param className Java class name of the object to be created
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name to create
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #ObjectCreateRule(String className, String attributeName)} instead.
- */
- public ObjectCreateRule(Digester digester, String className,
- String attributeName) {
-
- this (className, attributeName);
-
- }
-
-
- /**
- * Construct an object create rule with the specified class and an
- * optional attribute name containing an override.
- *
- * @param digester The associated Digester
- * @param attributeName Attribute name which, if present, contains an
- * @param clazz Java class name of the object to be created
- * override of the class name to create
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #ObjectCreateRule(String attributeName, Class clazz)} instead.
- */
- public ObjectCreateRule(Digester digester,
- String attributeName,
- Class clazz) {
-
- this(attributeName, clazz);
-
- }
-
- /**
- * Construct an object create rule with the specified class name.
- *
- * @param className Java class name of the object to be created
- */
- public ObjectCreateRule(String className) {
-
- this(className, (String) null);
-
- }
-
-
- /**
- * Construct an object create rule with the specified class.
- *
- * @param clazz Java class name of the object to be created
- */
- public ObjectCreateRule(Class clazz) {
-
- this(clazz.getName(), (String) null);
-
- }
-
-
- /**
- * Construct an object create rule with the specified class name and an
- * optional attribute name containing an override.
- *
- * @param className Java class name of the object to be created
- * @param attributeName Attribute name which, if present, contains an
- * override of the class name to create
- */
- public ObjectCreateRule(String className,
- String attributeName) {
-
- this.className = className;
- this.attributeName = attributeName;
-
- }
-
-
- /**
- * Construct an object create rule with the specified class and an
- * optional attribute name containing an override.
- *
- * @param attributeName Attribute name which, if present, contains an
- * @param clazz Java class name of the object to be created
- * override of the class name to create
- */
- public ObjectCreateRule(String attributeName,
- Class clazz) {
-
- this(clazz.getName(), attributeName);
-
- }
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The attribute containing an override class name if it is present.
- */
- protected String attributeName = null;
-
-
- /**
- * The Java class name of the object to be created.
- */
- protected String className = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Process the beginning of this element.
- *
- * @param attributes The attribute list of this element
- */
- public void begin(Attributes attributes) throws Exception {
-
- // Identify the name of the class to instantiate
- String realClassName = className;
- if (attributeName != null) {
- String value = attributes.getValue(attributeName);
- if (value != null) {
- realClassName = value;
- }
- }
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[ObjectCreateRule]{" + digester.match +
- "}New " + realClassName);
- }
-
- // Instantiate the new object and push it on the context stack
- Class clazz = digester.getClassLoader().loadClass(realClassName);
- Object instance = clazz.newInstance();
- digester.push(instance);
-
- }
-
-
- /**
- * Process the end of this element.
- */
- public void end() throws Exception {
-
- Object top = digester.pop();
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[ObjectCreateRule]{" + digester.match +
- "} Pop " + top.getClass().getName());
- }
-
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("ObjectCreateRule[");
- sb.append("className=");
- sb.append(className);
- sb.append(", attributeName=");
- sb.append(attributeName);
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/ObjectCreationFactory.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/ObjectCreationFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/ObjectCreationFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,60 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.xml.sax.Attributes;
-
-/**
- * <p> Interface for use with {@link FactoryCreateRule}.
- * The rule calls {@link #createObject} to create an object
- * to be pushed onto the <code>Digester</code> stack
- * whenever it is matched.</p>
- *
- * <p> {@link AbstractObjectCreationFactory} is an abstract
- * implementation suitable for creating anonymous
- * <code>ObjectCreationFactory</code> implementations.
- */
-public interface ObjectCreationFactory {
-
- /**
- * <p>Factory method called by {@link FactoryCreateRule} to supply an
- * object based on the element's attributes.
- *
- * @param attributes the element's attributes
- *
- * @throws Exception any exception thrown will be propagated upwards
- */
- public Object createObject(Attributes attributes) throws Exception;
-
- /**
- * <p>Returns the {@link Digester} that was set by the
- * {@link FactoryCreateRule} upon initialization.
- */
- public Digester getDigester();
-
- /**
- * <p>Set the {@link Digester} to allow the implementation to do logging,
- * classloading based on the digester's classloader, etc.
- *
- * @param digester parent Digester object
- */
- public void setDigester(Digester digester);
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/ObjectParamRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/ObjectParamRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/ObjectParamRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,125 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import org.xml.sax.Attributes;
-
-/**
- * <p>Rule implementation that saves a parameter for use by a surrounding
- * <code>CallMethodRule<code>.</p>
- *
- * <p>This parameter may be:
- * <ul>
- * <li>an arbitrary Object defined programatically, assigned when the element pattern associated with the Rule is matched
- * See {@link #ObjectParamRule(int paramIndex, Object param)}
- * <li>an arbitrary Object defined programatically, assigned if the element pattern AND specified attribute name are matched
- * See {@link #ObjectParamRule(int paramIndex, String attributeName, Object param)}
- * </ul>
- * </p>
- *
- * @since 1.4
- */
-
-public class ObjectParamRule extends Rule {
- // ----------------------------------------------------------- Constructors
- /**
- * Construct a "call parameter" rule that will save the given Object as
- * the parameter value.
- *
- * @param paramIndex The zero-relative parameter number
- * @param param the parameter to pass along
- */
- public ObjectParamRule(int paramIndex, Object param) {
- this(paramIndex, null, param);
- }
-
-
- /**
- * Construct a "call parameter" rule that will save the given Object as
- * the parameter value, provided that the specified attribute exists.
- *
- * @param paramIndex The zero-relative parameter number
- * @param attributeName The name of the attribute to match
- * @param param the parameter to pass along
- */
- public ObjectParamRule(int paramIndex, String attributeName, Object param) {
- this.paramIndex = paramIndex;
- this.attributeName = attributeName;
- this.param = param;
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * The attribute which we are attempting to match
- */
- protected String attributeName = null;
-
- /**
- * The zero-relative index of the parameter we are saving.
- */
- protected int paramIndex = 0;
-
- /**
- * The parameter we wish to pass to the method call
- */
- protected Object param = null;
-
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * Process the start of this element.
- *
- * @param attributes The attribute list for this element
- */
- public void begin(String namespace, String name,
- Attributes attributes) throws Exception {
- Object anAttribute = null;
- Object parameters[] = (Object[]) digester.peekParams();
-
- if (attributeName != null) {
- anAttribute = attributes.getValue(attributeName);
- if(anAttribute != null) {
- parameters[paramIndex] = param;
- }
- // note -- if attributeName != null and anAttribute == null, this rule
- // will pass null as its parameter!
- }else{
- parameters[paramIndex] = param;
- }
- }
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
- StringBuilder sb = new StringBuilder("ObjectParamRule[");
- sb.append("paramIndex=");
- sb.append(paramIndex);
- sb.append(", attributeName=");
- sb.append(attributeName);
- sb.append(", param=");
- sb.append(param);
- sb.append("]");
- return (sb.toString());
- }
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/ParserFeatureSetterFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,75 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import java.util.Properties;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-
-/**
- * Creates a <code>SAXParser</code> based on the underlying parser.
- * Allows logical properties depending on logical parser versions
- * to be set.
- *
- * @since 1.6
- */
-public class ParserFeatureSetterFactory{
-
- /**
- * <code>true</code> is Xerces is used.
- */
- private static boolean isXercesUsed;
-
- static {
- try{
- // Use reflection to avoid a build dependency with Xerces.
- Class versionClass =
- Class.forName("org.apache.xerces.impl.Version");
- isXercesUsed = true;
- } catch (Exception ex){
- isXercesUsed = false;
- }
- }
-
- /**
- * Create a new <code>SAXParser</code>
- * @param properties (logical) properties to be set on parser
- * @return a <code>SAXParser</code> configured based on the underlying
- * parser implementation.
- */
- public static SAXParser newSAXParser(Properties properties)
- throws ParserConfigurationException,
- SAXException,
- SAXNotRecognizedException,
- SAXNotSupportedException {
-
- if (isXercesUsed){
- return XercesParser.newSAXParser(properties);
- } else {
- return GenericParser.newSAXParser(properties);
- }
- }
-
-}
\ No newline at end of file
Deleted: trunk/java/org/apache/tomcat/util/digester/PathCallParamRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/PathCallParamRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/PathCallParamRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,94 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.xml.sax.Attributes;
-
-/**
- * <p>Rule implementation that saves a parameter containing the
- * <code>Digester</code> matching path for use by a surrounding
- * <code>CallMethodRule</code>. This Rule is most useful when making
- * extensive use of wildcards in rule patterns.</p>
- *
- * @since 1.6
- */
-
-public class PathCallParamRule extends Rule {
-
- // ----------------------------------------------------------- Constructors
-
- /**
- * Construct a "call parameter" rule that will save the body text of this
- * element as the parameter value.
- *
- * @param paramIndex The zero-relative parameter number
- */
- public PathCallParamRule(int paramIndex) {
-
- this.paramIndex = paramIndex;
-
- }
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * The zero-relative index of the parameter we are saving.
- */
- protected int paramIndex = 0;
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Process the start of this element.
- *
- * @param namespace the namespace URI of the matching element, or an
- * empty string if the parser is not namespace aware or the element has
- * no namespace
- * @param name the local name if the parser is namespace aware, or just
- * the element name otherwise
- * @param attributes The attribute list for this element
-
- */
- public void begin(String namespace, String name, Attributes attributes) throws Exception {
-
- String param = getDigester().getMatch();
-
- if(param != null) {
- Object parameters[] = (Object[]) digester.peekParams();
- parameters[paramIndex] = param;
- }
-
- }
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("PathCallParamRule[");
- sb.append("paramIndex=");
- sb.append(paramIndex);
- sb.append("]");
- return (sb.toString());
-
- }
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/Rule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/Rule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/Rule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,245 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.xml.sax.Attributes;
-
-
-/**
- * Concrete implementations of this class implement actions to be taken when
- * a corresponding nested pattern of XML elements has been matched.
- */
-
-public abstract class Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Constructor sets the associated Digester.
- *
- * @param digester The digester with which this rule is associated
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method. Use {@link #Rule()} instead.
- */
- public Rule(Digester digester) {
-
- super();
- setDigester(digester);
-
- }
-
- /**
- * <p>Base constructor.
- * Now the digester will be set when the rule is added.</p>
- */
- public Rule() {}
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The Digester with which this Rule is associated.
- */
- protected Digester digester = null;
-
-
- /**
- * The namespace URI for which this Rule is relevant, if any.
- */
- protected String namespaceURI = null;
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return the Digester with which this Rule is associated.
- */
- public Digester getDigester() {
-
- return (this.digester);
-
- }
-
- /**
- * Set the <code>Digester</code> with which this <code>Rule</code> is associated.
- */
- public void setDigester(Digester digester) {
-
- this.digester = digester;
-
- }
-
- /**
- * Return the namespace URI for which this Rule is relevant, if any.
- */
- public String getNamespaceURI() {
-
- return (this.namespaceURI);
-
- }
-
-
- /**
- * Set the namespace URI for which this Rule is relevant, if any.
- *
- * @param namespaceURI Namespace URI for which this Rule is relevant,
- * or <code>null</code> to match independent of namespace.
- */
- public void setNamespaceURI(String namespaceURI) {
-
- this.namespaceURI = namespaceURI;
-
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * This method is called when the beginning of a matching XML element
- * is encountered.
- *
- * @param attributes The attribute list of this element
- * @deprecated Use the {@link #begin(String,String,Attributes) begin}
- * method with <code>namespace</code> and <code>name</code>
- * parameters instead.
- */
- public void begin(Attributes attributes) throws Exception {
-
- ; // The default implementation does nothing
-
- }
-
-
- /**
- * This method is called when the beginning of a matching XML element
- * is encountered. The default implementation delegates to the deprecated
- * method {@link #begin(Attributes) begin} without the
- * <code>namespace</code> and <code>name</code> parameters, to retain
- * backwards compatibility.
- *
- * @param namespace the namespace URI of the matching element, or an
- * empty string if the parser is not namespace aware or the element has
- * no namespace
- * @param name the local name if the parser is namespace aware, or just
- * the element name otherwise
- * @param attributes The attribute list of this element
- * @since Digester 1.4
- */
- public void begin(String namespace, String name, Attributes attributes)
- throws Exception {
-
- begin(attributes);
-
- }
-
-
- /**
- * This method is called when the body of a matching XML element
- * is encountered. If the element has no body, this method is
- * not called at all.
- *
- * @param text The text of the body of this element
- * @deprecated Use the {@link #body(String,String,String) body} method
- * with <code>namespace</code> and <code>name</code> parameters
- * instead.
- */
- public void body(String text) throws Exception {
-
- ; // The default implementation does nothing
-
- }
-
-
- /**
- * This method is called when the body of a matching XML element is
- * encountered. If the element has no body, this method is not called at
- * all. The default implementation delegates to the deprecated method
- * {@link #body(String) body} without the <code>namespace</code> and
- * <code>name</code> parameters, to retain backwards compatibility.
- *
- * @param namespace the namespace URI of the matching element, or an
- * empty string if the parser is not namespace aware or the element has
- * no namespace
- * @param name the local name if the parser is namespace aware, or just
- * the element name otherwise
- * @param text The text of the body of this element
- * @since Digester 1.4
- */
- public void body(String namespace, String name, String text)
- throws Exception {
-
- body(text);
-
- }
-
-
- /**
- * This method is called when the end of a matching XML element
- * is encountered.
- *
- * @deprecated Use the {@link #end(String,String) end} method with
- * <code>namespace</code> and <code>name</code> parameters instead.
- */
- public void end() throws Exception {
-
- ; // The default implementation does nothing
-
- }
-
-
- /**
- * This method is called when the end of a matching XML element
- * is encountered. The default implementation delegates to the deprecated
- * method {@link #end end} without the
- * <code>namespace</code> and <code>name</code> parameters, to retain
- * backwards compatibility.
- *
- * @param namespace the namespace URI of the matching element, or an
- * empty string if the parser is not namespace aware or the element has
- * no namespace
- * @param name the local name if the parser is namespace aware, or just
- * the element name otherwise
- * @since Digester 1.4
- */
- public void end(String namespace, String name)
- throws Exception {
-
- end();
-
- }
-
-
- /**
- * This method is called after all parsing methods have been
- * called, to allow Rules to remove temporary data.
- */
- public void finish() throws Exception {
-
- ; // The default implementation does nothing
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/RuleSet.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/RuleSet.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/RuleSet.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,67 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-/**
- * <p>Public interface defining a shorthand means of configuring a complete
- * set of related <code>Rule</code> definitions, possibly associated with
- * a particular namespace URI, in one operation. To use an instance of a
- * class that imlements this interface:</p>
- * <ul>
- * <li>Create a concrete implementation of this interface.</li>
- * <li>Optionally, you can configure a <code>RuleSet</code> to be relevant
- * only for a particular namespace URI by configuring the value to be
- * returned by <code>getNamespaceURI()</code>.</li>
- * <li>As you are configuring your Digester instance, call
- * <code>digester.addRuleSet()</code> and pass the RuleSet instance.</li>
- * <li>Digester will call the <code>addRuleInstances()</code> method of
- * your RuleSet to configure the necessary rules.</li>
- * </ul>
- */
-
-public interface RuleSet {
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return the namespace URI that will be applied to all Rule instances
- * created from this RuleSet.
- */
- public String getNamespaceURI();
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Add the set of Rule instances defined in this RuleSet to the
- * specified <code>Digester</code> instance, associating them with
- * our namespace URI (if any). This method should only be called
- * by a Digester instance.
- *
- * @param digester Digester instance to which the new Rule instances
- * should be added.
- */
- public void addRuleInstances(Digester digester);
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/RuleSetBase.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/RuleSetBase.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/RuleSetBase.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,71 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-/**
- * <p>Convenience base class that implements the {@link RuleSet} interface.
- * Concrete implementations should list all of their actual rule creation
- * logic in the <code>addRuleSet()</code> implementation.</p>
- */
-
-public abstract class RuleSetBase implements RuleSet {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The namespace URI that all Rule instances created by this RuleSet
- * will be associated with.
- */
- protected String namespaceURI = null;
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return the namespace URI that will be applied to all Rule instances
- * created from this RuleSet.
- */
- public String getNamespaceURI() {
-
- return (this.namespaceURI);
-
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Add the set of Rule instances defined in this RuleSet to the
- * specified <code>Digester</code> instance, associating them with
- * our namespace URI (if any). This method should only be called
- * by a Digester instance.
- *
- * @param digester Digester instance to which the new Rule instances
- * should be added.
- */
- public abstract void addRuleInstances(Digester digester);
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/Rules.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/Rules.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/Rules.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,128 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import java.util.List;
-
-
-/**
- * Public interface defining a collection of Rule instances (and corresponding
- * matching patterns) plus an implementation of a matching policy that selects
- * the rules that match a particular pattern of nested elements discovered
- * during parsing.
- */
-
-public interface Rules {
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return the Digester instance with which this Rules instance is
- * associated.
- */
- public Digester getDigester();
-
-
- /**
- * Set the Digester instance with which this Rules instance is associated.
- *
- * @param digester The newly associated Digester instance
- */
- public void setDigester(Digester digester);
-
-
- /**
- * Return the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- */
- public String getNamespaceURI();
-
-
- /**
- * Set the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- *
- * @param namespaceURI Namespace URI that must match on all
- * subsequently added rules, or <code>null</code> for matching
- * regardless of the current namespace URI
- */
- public void setNamespaceURI(String namespaceURI);
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Register a new Rule instance matching the specified pattern.
- *
- * @param pattern Nesting pattern to be matched for this Rule
- * @param rule Rule instance to be registered
- */
- public void add(String pattern, Rule rule);
-
-
- /**
- * Clear all existing Rule instance registrations.
- */
- public void clear();
-
-
- /**
- * Return a List of all registered Rule instances that match the specified
- * nesting pattern, or a zero-length List if there are no matches. If more
- * than one Rule instance matches, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- *
- * @param pattern Nesting pattern to be matched
- *
- * @deprecated Call match(namespaceURI,pattern) instead.
- */
- public List match(String pattern);
-
-
- /**
- * Return a List of all registered Rule instances that match the specified
- * nesting pattern, or a zero-length List if there are no matches. If more
- * than one Rule instance matches, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- *
- * @param namespaceURI Namespace URI for which to select matching rules,
- * or <code>null</code> to match regardless of namespace URI
- * @param pattern Nesting pattern to be matched
- */
- public List match(String namespaceURI, String pattern);
-
-
- /**
- * Return a List of all registered Rule instances, or a zero-length List
- * if there are no registered Rule instances. If more than one Rule
- * instance has been registered, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- */
- public List rules();
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/RulesBase.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/RulesBase.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/RulesBase.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,294 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-
-/**
- * <p>Default implementation of the <code>Rules</code> interface that supports
- * the standard rule matching behavior. This class can also be used as a
- * base class for specialized <code>Rules</code> implementations.</p>
- *
- * <p>The matching policies implemented by this class support two different
- * types of pattern matching rules:</p>
- * <ul>
- * <li><em>Exact Match</em> - A pattern "a/b/c" exactly matches a
- * <code><c></code> element, nested inside a <code><b></code>
- * element, which is nested inside an <code><a></code> element.</li>
- * <li><em>Tail Match</em> - A pattern "*/a/b" matches a
- * <code><b></code> element, nested inside an <code><a></code>
- * element, no matter how deeply the pair is nested.</li>
- * </ul>
- */
-
-public class RulesBase implements Rules {
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The set of registered Rule instances, keyed by the matching pattern.
- * Each value is a List containing the Rules for that pattern, in the
- * order that they were orginally registered.
- */
- protected HashMap cache = new HashMap();
-
-
- /**
- * The Digester instance with which this Rules instance is associated.
- */
- protected Digester digester = null;
-
-
- /**
- * The namespace URI for which subsequently added <code>Rule</code>
- * objects are relevant, or <code>null</code> for matching independent
- * of namespaces.
- */
- protected String namespaceURI = null;
-
-
- /**
- * The set of registered Rule instances, in the order that they were
- * originally registered.
- */
- protected ArrayList rules = new ArrayList();
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Return the Digester instance with which this Rules instance is
- * associated.
- */
- public Digester getDigester() {
-
- return (this.digester);
-
- }
-
-
- /**
- * Set the Digester instance with which this Rules instance is associated.
- *
- * @param digester The newly associated Digester instance
- */
- public void setDigester(Digester digester) {
-
- this.digester = digester;
- Iterator items = rules.iterator();
- while (items.hasNext()) {
- Rule item = (Rule) items.next();
- item.setDigester(digester);
- }
-
- }
-
-
- /**
- * Return the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- */
- public String getNamespaceURI() {
-
- return (this.namespaceURI);
-
- }
-
-
- /**
- * Set the namespace URI that will be applied to all subsequently
- * added <code>Rule</code> objects.
- *
- * @param namespaceURI Namespace URI that must match on all
- * subsequently added rules, or <code>null</code> for matching
- * regardless of the current namespace URI
- */
- public void setNamespaceURI(String namespaceURI) {
-
- this.namespaceURI = namespaceURI;
-
- }
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Register a new Rule instance matching the specified pattern.
- *
- * @param pattern Nesting pattern to be matched for this Rule
- * @param rule Rule instance to be registered
- */
- public void add(String pattern, Rule rule) {
- // to help users who accidently add '/' to the end of their patterns
- int patternLength = pattern.length();
- if (patternLength>1 && pattern.endsWith("/")) {
- pattern = pattern.substring(0, patternLength-1);
- }
-
-
- List list = (List) cache.get(pattern);
- if (list == null) {
- list = new ArrayList();
- cache.put(pattern, list);
- }
- list.add(rule);
- rules.add(rule);
- if (this.digester != null) {
- rule.setDigester(this.digester);
- }
- if (this.namespaceURI != null) {
- rule.setNamespaceURI(this.namespaceURI);
- }
-
- }
-
-
- /**
- * Clear all existing Rule instance registrations.
- */
- public void clear() {
-
- cache.clear();
- rules.clear();
-
- }
-
-
- /**
- * Return a List of all registered Rule instances that match the specified
- * nesting pattern, or a zero-length List if there are no matches. If more
- * than one Rule instance matches, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- *
- * @param pattern Nesting pattern to be matched
- *
- * @deprecated Call match(namespaceURI,pattern) instead.
- */
- public List match(String pattern) {
-
- return (match(null, pattern));
-
- }
-
-
- /**
- * Return a List of all registered Rule instances that match the specified
- * nesting pattern, or a zero-length List if there are no matches. If more
- * than one Rule instance matches, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- *
- * @param namespaceURI Namespace URI for which to select matching rules,
- * or <code>null</code> to match regardless of namespace URI
- * @param pattern Nesting pattern to be matched
- */
- public List match(String namespaceURI, String pattern) {
-
- // List rulesList = (List) this.cache.get(pattern);
- List rulesList = lookup(namespaceURI, pattern);
- if ((rulesList == null) || (rulesList.size() < 1)) {
- // Find the longest key, ie more discriminant
- String longKey = "";
- Iterator keys = this.cache.keySet().iterator();
- while (keys.hasNext()) {
- String key = (String) keys.next();
- if (key.startsWith("*/")) {
- if (pattern.equals(key.substring(2)) ||
- pattern.endsWith(key.substring(1))) {
- if (key.length() > longKey.length()) {
- // rulesList = (List) this.cache.get(key);
- rulesList = lookup(namespaceURI, key);
- longKey = key;
- }
- }
- }
- }
- }
- if (rulesList == null) {
- rulesList = new ArrayList();
- }
- return (rulesList);
-
- }
-
-
- /**
- * Return a List of all registered Rule instances, or a zero-length List
- * if there are no registered Rule instances. If more than one Rule
- * instance has been registered, they <strong>must</strong> be returned
- * in the order originally registered through the <code>add()</code>
- * method.
- */
- public List rules() {
-
- return (this.rules);
-
- }
-
-
- // ------------------------------------------------------ Protected Methods
-
-
- /**
- * Return a List of Rule instances for the specified pattern that also
- * match the specified namespace URI (if any). If there are no such
- * rules, return <code>null</code>.
- *
- * @param namespaceURI Namespace URI to match, or <code>null</code> to
- * select matching rules regardless of namespace URI
- * @param pattern Pattern to be matched
- */
- protected List lookup(String namespaceURI, String pattern) {
-
- // Optimize when no namespace URI is specified
- List list = (List) this.cache.get(pattern);
- if (list == null) {
- return (null);
- }
- if ((namespaceURI == null) || (namespaceURI.length() == 0)) {
- return (list);
- }
-
- // Select only Rules that match on the specified namespace URI
- ArrayList results = new ArrayList();
- Iterator items = list.iterator();
- while (items.hasNext()) {
- Rule item = (Rule) items.next();
- if ((namespaceURI.equals(item.getNamespaceURI())) ||
- (item.getNamespaceURI() == null)) {
- results.add(item);
- }
- }
- return (results);
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/SetNextRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/SetNextRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/SetNextRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,215 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import org.apache.tomcat.util.IntrospectionUtils;
-
-
-/**
- * <p>Rule implementation that calls a method on the (top-1) (parent)
- * object, passing the top object (child) as an argument. It is
- * commonly used to establish parent-child relationships.</p>
- *
- * <p>This rule now supports more flexible method matching by default.
- * It is possible that this may break (some) code
- * written against release 1.1.1 or earlier.
- * See {@link #isExactMatch()} for more details.</p>
- */
-
-public class SetNextRule extends Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a "set next" rule with the specified method name. The
- * method's argument type is assumed to be the class of the
- * child object.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetNextRule(String methodName)} instead.
- */
- public SetNextRule(Digester digester, String methodName) {
-
- this(methodName);
-
- }
-
-
- /**
- * Construct a "set next" rule with the specified method name.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- * @param paramType Java class of the parent method's argument
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetNextRule(String methodName,String paramType)} instead.
- */
- public SetNextRule(Digester digester, String methodName,
- String paramType) {
-
- this(methodName, paramType);
-
- }
-
- /**
- * Construct a "set next" rule with the specified method name. The
- * method's argument type is assumed to be the class of the
- * child object.
- *
- * @param methodName Method name of the parent method to call
- */
- public SetNextRule(String methodName) {
-
- this(methodName, null);
-
- }
-
-
- /**
- * Construct a "set next" rule with the specified method name.
- *
- * @param methodName Method name of the parent method to call
- * @param paramType Java class of the parent method's argument
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- */
- public SetNextRule(String methodName,
- String paramType) {
-
- this.methodName = methodName;
- this.paramType = paramType;
-
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The method name to call on the parent object.
- */
- protected String methodName = null;
-
-
- /**
- * The Java class name of the parameter type expected by the method.
- */
- protected String paramType = null;
-
- /**
- * Should we use exact matching. Default is no.
- */
- protected boolean useExactMatch = false;
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * <p>Is exact matching being used.</p>
- *
- * <p>This rule uses <code>org.apache.commons.beanutils.MethodUtils</code>
- * to introspect the relevent objects so that the right method can be called.
- * Originally, <code>MethodUtils.invokeExactMethod</code> was used.
- * This matches methods very strictly
- * and so may not find a matching method when one exists.
- * This is still the behaviour when exact matching is enabled.</p>
- *
- * <p>When exact matching is disabled, <code>MethodUtils.invokeMethod</code> is used.
- * This method finds more methods but is less precise when there are several methods
- * with correct signatures.
- * So, if you want to choose an exact signature you might need to enable this property.</p>
- *
- * <p>The default setting is to disable exact matches.</p>
- *
- * @return true iff exact matching is enabled
- * @since Digester Release 1.1.1
- */
- public boolean isExactMatch() {
-
- return useExactMatch;
- }
-
- /**
- * <p>Set whether exact matching is enabled.</p>
- *
- * <p>See {@link #isExactMatch()}.</p>
- *
- * @param useExactMatch should this rule use exact method matching
- * @since Digester Release 1.1.1
- */
- public void setExactMatch(boolean useExactMatch) {
-
- this.useExactMatch = useExactMatch;
- }
-
- /**
- * Process the end of this element.
- */
- public void end() throws Exception {
-
- // Identify the objects to be used
- Object child = digester.peek(0);
- Object parent = digester.peek(1);
- if (digester.log.isDebugEnabled()) {
- if (parent == null) {
- digester.log.debug("[SetNextRule]{" + digester.match +
- "} Call [NULL PARENT]." +
- methodName + "(" + child + ")");
- } else {
- digester.log.debug("[SetNextRule]{" + digester.match +
- "} Call " + parent.getClass().getName() + "." +
- methodName + "(" + child + ")");
- }
- }
-
- // Call the specified method
- IntrospectionUtils.callMethod1(parent, methodName,
- child, paramType, digester.getClassLoader());
-
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("SetNextRule[");
- sb.append("methodName=");
- sb.append(methodName);
- sb.append(", paramType=");
- sb.append(paramType);
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/SetPropertiesRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/SetPropertiesRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/SetPropertiesRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,268 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.apache.tomcat.util.IntrospectionUtils;
-import org.xml.sax.Attributes;
-
-
-/**
- * <p>Rule implementation that sets properties on the object at the top of the
- * stack, based on attributes with corresponding names.</p>
- *
- * <p>This rule supports custom mapping of attribute names to property names.
- * The default mapping for particular attributes can be overridden by using
- * {@link #SetPropertiesRule(String[] attributeNames, String[] propertyNames)}.
- * This allows attributes to be mapped to properties with different names.
- * Certain attributes can also be marked to be ignored.</p>
- */
-
-public class SetPropertiesRule extends Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Default constructor sets only the the associated Digester.
- *
- * @param digester The digester with which this rule is associated
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetPropertiesRule()} instead.
- */
- public SetPropertiesRule(Digester digester) {
-
- this();
-
- }
-
-
- /**
- * Base constructor.
- */
- public SetPropertiesRule() {
-
- // nothing to set up
-
- }
-
- /**
- * <p>Convenience constructor overrides the mapping for just one property.</p>
- *
- * <p>For details about how this works, see
- * {@link #SetPropertiesRule(String[] attributeNames, String[] propertyNames)}.</p>
- *
- * @param attributeName map this attribute
- * @param propertyName to a property with this name
- */
- public SetPropertiesRule(String attributeName, String propertyName) {
-
- attributeNames = new String[1];
- attributeNames[0] = attributeName;
- propertyNames = new String[1];
- propertyNames[0] = propertyName;
- }
-
- /**
- * <p>Constructor allows attribute->property mapping to be overriden.</p>
- *
- * <p>Two arrays are passed in.
- * One contains the attribute names and the other the property names.
- * The attribute name / property name pairs are match by position
- * In order words, the first string in the attribute name list matches
- * to the first string in the property name list and so on.</p>
- *
- * <p>If a property name is null or the attribute name has no matching
- * property name, then this indicates that the attibute should be ignored.</p>
- *
- * <h5>Example One</h5>
- * <p> The following constructs a rule that maps the <code>alt-city</code>
- * attribute to the <code>city</code> property and the <code>alt-state</code>
- * to the <code>state</code> property.
- * All other attributes are mapped as usual using exact name matching.
- * <code><pre>
- * SetPropertiesRule(
- * new String[] {"alt-city", "alt-state"},
- * new String[] {"city", "state"});
- * </pre></code>
- *
- * <h5>Example Two</h5>
- * <p> The following constructs a rule that maps the <code>class</code>
- * attribute to the <code>className</code> property.
- * The attribute <code>ignore-me</code> is not mapped.
- * All other attributes are mapped as usual using exact name matching.
- * <code><pre>
- * SetPropertiesRule(
- * new String[] {"class", "ignore-me"},
- * new String[] {"className"});
- * </pre></code>
- *
- * @param attributeNames names of attributes to map
- * @param propertyNames names of properties mapped to
- */
- public SetPropertiesRule(String[] attributeNames, String[] propertyNames) {
- // create local copies
- this.attributeNames = new String[attributeNames.length];
- for (int i=0, size=attributeNames.length; i<size; i++) {
- this.attributeNames[i] = attributeNames[i];
- }
-
- this.propertyNames = new String[propertyNames.length];
- for (int i=0, size=propertyNames.length; i<size; i++) {
- this.propertyNames[i] = propertyNames[i];
- }
- }
-
- // ----------------------------------------------------- Instance Variables
-
- /**
- * Attribute names used to override natural attribute->property mapping
- */
- private String [] attributeNames;
- /**
- * Property names used to override natural attribute->property mapping
- */
- private String [] propertyNames;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Process the beginning of this element.
- *
- * @param attributes The attribute list of this element
- */
- public void begin(Attributes attributes) throws Exception {
-
- // Populate the corresponding properties of the top object
- Object top = digester.peek();
- if (digester.log.isDebugEnabled()) {
- if (top != null) {
- digester.log.debug("[SetPropertiesRule]{" + digester.match +
- "} Set " + top.getClass().getName() +
- " properties");
- } else {
- digester.log.debug("[SetPropertiesRule]{" + digester.match +
- "} Set NULL properties");
- }
- }
-
- // set up variables for custom names mappings
- int attNamesLength = 0;
- if (attributeNames != null) {
- attNamesLength = attributeNames.length;
- }
- int propNamesLength = 0;
- if (propertyNames != null) {
- propNamesLength = propertyNames.length;
- }
-
- for (int i = 0; i < attributes.getLength(); i++) {
- String name = attributes.getLocalName(i);
- if ("".equals(name)) {
- name = attributes.getQName(i);
- }
- String value = attributes.getValue(i);
-
- // we'll now check for custom mappings
- for (int n = 0; n<attNamesLength; n++) {
- if (name.equals(attributeNames[n])) {
- if (n < propNamesLength) {
- // set this to value from list
- name = propertyNames[n];
-
- } else {
- // set name to null
- // we'll check for this later
- name = null;
- }
- break;
- }
- }
-
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[SetPropertiesRule]{" + digester.match +
- "} Setting property '" + name + "' to '" +
- value + "'");
- }
- if (!digester.isFakeAttribute(top, name)
- && !IntrospectionUtils.setProperty(top, name, value)
- && digester.getRulesValidation()) {
- digester.log.warn("[SetPropertiesRule]{" + digester.match +
- "} Setting property '" + name + "' to '" +
- value + "' did not find a matching property.");
- }
- }
-
- }
-
-
- /**
- * <p>Add an additional attribute name to property name mapping.
- * This is intended to be used from the xml rules.
- */
- public void addAlias(String attributeName, String propertyName) {
-
- // this is a bit tricky.
- // we'll need to resize the array.
- // probably should be synchronized but digester's not thread safe anyway
- if (attributeNames == null) {
-
- attributeNames = new String[1];
- attributeNames[0] = attributeName;
- propertyNames = new String[1];
- propertyNames[0] = propertyName;
-
- } else {
- int length = attributeNames.length;
- String [] tempAttributes = new String[length + 1];
- for (int i=0; i<length; i++) {
- tempAttributes[i] = attributeNames[i];
- }
- tempAttributes[length] = attributeName;
-
- String [] tempProperties = new String[length + 1];
- for (int i=0; i<length && i< propertyNames.length; i++) {
- tempProperties[i] = propertyNames[i];
- }
- tempProperties[length] = propertyName;
-
- propertyNames = tempProperties;
- attributeNames = tempAttributes;
- }
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("SetPropertiesRule[");
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/SetPropertyRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/SetPropertyRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/SetPropertyRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,155 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.apache.tomcat.util.IntrospectionUtils;
-import org.xml.sax.Attributes;
-
-
-/**
- * Rule implementation that sets an individual property on the object at the
- * top of the stack, based on attributes with specified names.
- */
-
-public class SetPropertyRule extends Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a "set property" rule with the specified name and value
- * attributes.
- *
- * @param digester The digester with which this rule is associated
- * @param name Name of the attribute that will contain the name of the
- * property to be set
- * @param value Name of the attribute that will contain the value to which
- * the property should be set
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetPropertyRule(String name, String value)} instead.
- */
- public SetPropertyRule(Digester digester, String name, String value) {
-
- this(name, value);
-
- }
-
- /**
- * Construct a "set property" rule with the specified name and value
- * attributes.
- *
- * @param name Name of the attribute that will contain the name of the
- * property to be set
- * @param value Name of the attribute that will contain the value to which
- * the property should be set
- */
- public SetPropertyRule(String name, String value) {
-
- this.name = name;
- this.value = value;
-
- }
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The attribute that will contain the property name.
- */
- protected String name = null;
-
-
- /**
- * The attribute that will contain the property value.
- */
- protected String value = null;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * Process the beginning of this element.
- *
- * @param attributes The attribute list of this element
- *
- * @exception NoSuchMethodException if the bean does not
- * have a writeable property of the specified name
- */
- public void begin(Attributes attributes) throws Exception {
-
- // Identify the actual property name and value to be used
- String actualName = null;
- String actualValue = null;
- for (int i = 0; i < attributes.getLength(); i++) {
- String name = attributes.getLocalName(i);
- if ("".equals(name)) {
- name = attributes.getQName(i);
- }
- String value = attributes.getValue(i);
- if (name.equals(this.name)) {
- actualName = value;
- } else if (name.equals(this.value)) {
- actualValue = value;
- }
- }
-
- // Get a reference to the top object
- Object top = digester.peek();
-
- // Log some debugging information
- if (digester.log.isDebugEnabled()) {
- digester.log.debug("[SetPropertyRule]{" + digester.match +
- "} Set " + top.getClass().getName() + " property " +
- actualName + " to " + actualValue);
- }
-
- // Set the property (with conversion as necessary)
- if (!digester.isFakeAttribute(top, actualName)
- && !IntrospectionUtils.setProperty(top, actualName, actualValue)
- && digester.getRulesValidation()) {
- digester.log.warn("[SetPropertyRule]{" + digester.match +
- "} Setting property '" + name + "' to '" +
- value + "' did not find a matching property.");
- }
-
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("SetPropertyRule[");
- sb.append("name=");
- sb.append(name);
- sb.append(", value=");
- sb.append(value);
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/SetRootRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/SetRootRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/SetRootRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,216 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import org.apache.tomcat.util.IntrospectionUtils;
-
-
-/**
- * <p>Rule implementation that calls a method on the root object on the stack,
- * passing the top object (child) as an argument.
- * It is important to remember that this rule acts on <code>end</code>.</p>
- *
- * <p>This rule now supports more flexible method matching by default.
- * It is possible that this may break (some) code
- * written against release 1.1.1 or earlier.
- * See {@link #isExactMatch()} for more details.</p>
- */
-
-public class SetRootRule extends Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a "set root" rule with the specified method name. The
- * method's argument type is assumed to be the class of the
- * child object.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetRootRule(String methodName)} instead.
- */
- public SetRootRule(Digester digester, String methodName) {
-
- this(methodName);
-
- }
-
-
- /**
- * Construct a "set root" rule with the specified method name.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the parent method to call
- * @param paramType Java class of the parent method's argument
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetRootRule(String methodName,String paramType)} instead.
- */
- public SetRootRule(Digester digester, String methodName,
- String paramType) {
-
- this(methodName, paramType);
-
- }
-
- /**
- * Construct a "set root" rule with the specified method name. The
- * method's argument type is assumed to be the class of the
- * child object.
- *
- * @param methodName Method name of the parent method to call
- */
- public SetRootRule(String methodName) {
-
- this(methodName, null);
-
- }
-
-
- /**
- * Construct a "set root" rule with the specified method name.
- *
- * @param methodName Method name of the parent method to call
- * @param paramType Java class of the parent method's argument
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- */
- public SetRootRule(String methodName,
- String paramType) {
-
- this.methodName = methodName;
- this.paramType = paramType;
-
- }
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The method name to call on the parent object.
- */
- protected String methodName = null;
-
-
- /**
- * The Java class name of the parameter type expected by the method.
- */
- protected String paramType = null;
-
- /**
- * Should we use exact matching. Default is no.
- */
- protected boolean useExactMatch = false;
-
-
- // --------------------------------------------------------- Public Methods
-
-
- /**
- * <p>Is exact matching being used.</p>
- *
- * <p>This rule uses <code>org.apache.commons.beanutils.MethodUtils</code>
- * to introspect the relevent objects so that the right method can be called.
- * Originally, <code>MethodUtils.invokeExactMethod</code> was used.
- * This matches methods very strictly
- * and so may not find a matching method when one exists.
- * This is still the behaviour when exact matching is enabled.</p>
- *
- * <p>When exact matching is disabled, <code>MethodUtils.invokeMethod</code> is used.
- * This method finds more methods but is less precise when there are several methods
- * with correct signatures.
- * So, if you want to choose an exact signature you might need to enable this property.</p>
- *
- * <p>The default setting is to disable exact matches.</p>
- *
- * @return true iff exact matching is enabled
- * @since Digester Release 1.1.1
- */
- public boolean isExactMatch() {
-
- return useExactMatch;
- }
-
-
- /**
- * <p>Set whether exact matching is enabled.</p>
- *
- * <p>See {@link #isExactMatch()}.</p>
- *
- * @param useExactMatch should this rule use exact method matching
- * @since Digester Release 1.1.1
- */
- public void setExactMatch(boolean useExactMatch) {
-
- this.useExactMatch = useExactMatch;
- }
-
- /**
- * Process the end of this element.
- */
- public void end() throws Exception {
-
- // Identify the objects to be used
- Object child = digester.peek(0);
- Object parent = digester.root;
- if (digester.log.isDebugEnabled()) {
- if (parent == null) {
- digester.log.debug("[SetRootRule]{" + digester.match +
- "} Call [NULL ROOT]." +
- methodName + "(" + child + ")");
- } else {
- digester.log.debug("[SetRootRule]{" + digester.match +
- "} Call " + parent.getClass().getName() + "." +
- methodName + "(" + child + ")");
- }
- }
-
- // Call the specified method
- IntrospectionUtils.callMethod1(parent, methodName,
- child, paramType, digester.getClassLoader());
-
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("SetRootRule[");
- sb.append("methodName=");
- sb.append(methodName);
- sb.append(", paramType=");
- sb.append(paramType);
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/SetTopRule.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/SetTopRule.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/SetTopRule.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,216 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-
-import org.apache.tomcat.util.IntrospectionUtils;
-
-
-/**
- * <p>Rule implementation that calls a "set parent" method on the top (child)
- * object, passing the (top-1) (parent) object as an argument.</p>
- *
- * <p>This rule now supports more flexible method matching by default.
- * It is possible that this may break (some) code
- * written against release 1.1.1 or earlier.
- * See {@link #isExactMatch()} for more details.</p>
- */
-
-public class SetTopRule extends Rule {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a "set parent" rule with the specified method name. The
- * "set parent" method's argument type is assumed to be the class of the
- * parent object.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the "set parent" method to call
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetTopRule(String methodName)} instead.
- */
- public SetTopRule(Digester digester, String methodName) {
-
- this(methodName);
-
- }
-
-
- /**
- * Construct a "set parent" rule with the specified method name.
- *
- * @param digester The associated Digester
- * @param methodName Method name of the "set parent" method to call
- * @param paramType Java class of the "set parent" method's argument
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- *
- * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
- * Use {@link #SetTopRule(String methodName, String paramType)} instead.
- */
- public SetTopRule(Digester digester, String methodName,
- String paramType) {
-
- this(methodName, paramType);
-
- }
-
- /**
- * Construct a "set parent" rule with the specified method name. The
- * "set parent" method's argument type is assumed to be the class of the
- * parent object.
- *
- * @param methodName Method name of the "set parent" method to call
- */
- public SetTopRule(String methodName) {
-
- this(methodName, null);
-
- }
-
-
- /**
- * Construct a "set parent" rule with the specified method name.
- *
- * @param methodName Method name of the "set parent" method to call
- * @param paramType Java class of the "set parent" method's argument
- * (if you wish to use a primitive type, specify the corresonding
- * Java wrapper class instead, such as <code>java.lang.Boolean</code>
- * for a <code>boolean</code> parameter)
- */
- public SetTopRule(String methodName,
- String paramType) {
-
- this.methodName = methodName;
- this.paramType = paramType;
-
- }
-
-
- // ----------------------------------------------------- Instance Variables
-
-
- /**
- * The method name to call on the child object.
- */
- protected String methodName = null;
-
-
- /**
- * The Java class name of the parameter type expected by the method.
- */
- protected String paramType = null;
-
- /**
- * Should we use exact matching. Default is no.
- */
- protected boolean useExactMatch = false;
-
-
- // --------------------------------------------------------- Public Methods
-
- /**
- * <p>Is exact matching being used.</p>
- *
- * <p>This rule uses <code>org.apache.commons.beanutils.MethodUtils</code>
- * to introspect the relevent objects so that the right method can be called.
- * Originally, <code>MethodUtils.invokeExactMethod</code> was used.
- * This matches methods very strictly
- * and so may not find a matching method when one exists.
- * This is still the behaviour when exact matching is enabled.</p>
- *
- * <p>When exact matching is disabled, <code>MethodUtils.invokeMethod</code> is used.
- * This method finds more methods but is less precise when there are several methods
- * with correct signatures.
- * So, if you want to choose an exact signature you might need to enable this property.</p>
- *
- * <p>The default setting is to disable exact matches.</p>
- *
- * @return true iff exact matching is enabled
- * @since Digester Release 1.1.1
- */
- public boolean isExactMatch() {
-
- return useExactMatch;
- }
-
- /**
- * <p>Set whether exact matching is enabled.</p>
- *
- * <p>See {@link #isExactMatch()}.</p>
- *
- * @param useExactMatch should this rule use exact method matching
- * @since Digester Release 1.1.1
- */
- public void setExactMatch(boolean useExactMatch) {
-
- this.useExactMatch = useExactMatch;
- }
-
- /**
- * Process the end of this element.
- */
- public void end() throws Exception {
-
- // Identify the objects to be used
- Object child = digester.peek(0);
- Object parent = digester.peek(1);
-
- if (digester.log.isDebugEnabled()) {
- if (child == null) {
- digester.log.debug("[SetTopRule]{" + digester.match +
- "} Call [NULL CHILD]." +
- methodName + "(" + parent + ")");
- } else {
- digester.log.debug("[SetTopRule]{" + digester.match +
- "} Call " + child.getClass().getName() + "." +
- methodName + "(" + parent + ")");
- }
- }
-
- // Call the specified method
- IntrospectionUtils.callMethod1(child, methodName,
- parent, paramType, digester.getClassLoader());
-
- }
-
-
- /**
- * Render a printable version of this Rule.
- */
- public String toString() {
-
- StringBuilder sb = new StringBuilder("SetTopRule[");
- sb.append("methodName=");
- sb.append(methodName);
- sb.append(", paramType=");
- sb.append(paramType);
- sb.append("]");
- return (sb.toString());
-
- }
-
-
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/WithDefaultsRulesWrapper.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/WithDefaultsRulesWrapper.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/WithDefaultsRulesWrapper.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,164 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * <p><code>Rules</code> <em>Decorator</em> that returns default rules
- * when no matches are returned by the wrapped implementation.</p>
- *
- * <p>This allows default <code>Rule</code> instances to be added to any
- * existing <code>Rules</code> implementation. These default <code>Rule</code>
- * instances will be returned for any match for which the wrapped
- * implementation does not return any matches.</p>
- * <p> For example,
- * <pre>
- * Rule alpha;
- * ...
- * WithDefaultsRulesWrapper rules = new WithDefaultsRulesWrapper(new BaseRules());
- * rules.addDefault(alpha);
- * ...
- * digester.setRules(rules);
- * ...
- * </pre>
- * when a pattern does not match any other rule, then rule alpha will be called.
- * </p>
- * <p><code>WithDefaultsRulesWrapper</code> follows the <em>Decorator</em> pattern.</p>
- *
- * @since 1.6
- */
-
-public class WithDefaultsRulesWrapper implements Rules {
-
- // --------------------------------------------------------- Fields
-
- /** The Rules implementation that this class wraps. */
- private Rules wrappedRules;
- /** Rules to be fired when the wrapped implementations returns none. */
- private List defaultRules = new ArrayList();
- /** All rules (preserves order in which they were originally added) */
- private List allRules = new ArrayList();
-
- // --------------------------------------------------------- Constructor
-
- /**
- * Base constructor.
- *
- * @param wrappedRules the wrapped <code>Rules</code> implementation, not null
- * @throws IllegalArgumentException when <code>wrappedRules</code> is null
- */
- public WithDefaultsRulesWrapper(Rules wrappedRules) {
- if (wrappedRules == null) {
- throw new IllegalArgumentException("Wrapped rules must not be null");
- }
- this.wrappedRules = wrappedRules;
- }
-
- // --------------------------------------------------------- Properties
-
- /** Gets digester using these Rules */
- public Digester getDigester() {
- return wrappedRules.getDigester();
- }
-
- /** Sets digeseter using these Rules */
- public void setDigester(Digester digester) {
- wrappedRules.setDigester(digester);
- Iterator it = defaultRules.iterator();
- while (it.hasNext()) {
- Rule rule = (Rule) it.next();
- rule.setDigester(digester);
- }
- }
-
- /** Gets namespace to apply to Rule's added */
- public String getNamespaceURI() {
- return wrappedRules.getNamespaceURI();
- }
-
- /** Sets namespace to apply to Rule's added subsequently */
- public void setNamespaceURI(String namespaceURI) {
- wrappedRules.setNamespaceURI(namespaceURI);
- }
-
- /** Gets Rule's which will be fired when the wrapped implementation returns no matches */
- public List getDefaults() {
- return defaultRules;
- }
-
- // --------------------------------------------------------- Public Methods
-
- public List match(String pattern) {
- return match("", pattern);
- }
-
- /**
- * Return list of rules matching given pattern.
- * If wrapped implementation returns any matches return those.
- * Otherwise, return default matches.
- */
- public List match(String namespaceURI, String pattern) {
- List matches = wrappedRules.match(namespaceURI, pattern);
- if (matches == null || matches.isEmpty()) {
- // a little bit of defensive programming
- return new ArrayList(defaultRules);
- }
- // otherwise
- return matches;
- }
-
- /** Adds a rule to be fired when wrapped implementation returns no matches */
- public void addDefault(Rule rule) {
- // set up rule
- if (wrappedRules.getDigester() != null) {
- rule.setDigester(wrappedRules.getDigester());
- }
-
- if (wrappedRules.getNamespaceURI() != null) {
- rule.setNamespaceURI(wrappedRules.getNamespaceURI());
- }
-
- defaultRules.add(rule);
- allRules.add(rule);
- }
-
- /** Gets all rules */
- public List rules() {
- return allRules;
- }
-
- /** Clears all Rule's */
- public void clear() {
- wrappedRules.clear();
- allRules.clear();
- defaultRules.clear();
- }
-
- /**
- * Adds a Rule to be fired on given pattern.
- * Pattern matching is delegated to wrapped implementation.
- */
- public void add(String pattern, Rule rule) {
- wrappedRules.add(pattern, rule);
- allRules.add(rule);
- }
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/XercesParser.java
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/XercesParser.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/XercesParser.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,190 +0,0 @@
-/* $Id$
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.digester;
-
-import java.lang.reflect.Method;
-import java.util.Properties;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-
-/**
- * Create a <code>SAXParser</code> based on the underlying Xerces version.
- * Currently, Xerces 2.3 and up doesn't implement schema validation the same way
- * 2.1 was. In other to support schema validation in a portable way between
- * parser, some features/properties need to be set.
- *
- * @since 1.6
- */
-
-public class XercesParser{
-
- /**
- * The Log to which all SAX event related logging calls will be made.
- */
- protected static Logger log =
- Logger.getLogger("org.apache.commons.digester.Digester.sax");
-
-
- /**
- * The JAXP 1.2 property required to set up the schema location.
- */
- private static final String JAXP_SCHEMA_SOURCE =
- "http://java.sun.com/xml/jaxp/properties/schemaSource";
-
-
- /**
- * The JAXP 1.2 property to set up the schemaLanguage used.
- */
- protected static String JAXP_SCHEMA_LANGUAGE =
- "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
-
-
- /**
- * Xerces dynamic validation property
- */
- protected static String XERCES_DYNAMIC =
- "http://apache.org/xml/features/validation/dynamic";
-
-
- /**
- * Xerces schema validation property
- */
- protected static String XERCES_SCHEMA =
- "http://apache.org/xml/features/validation/schema";
-
-
- /**
- * A <code>float</code> representing the underlying Xerces version
- */
- protected static float version;
-
-
- /**
- * The current Xerces version.
- */
- protected static String versionNumber = null;
-
-
- /**
- * Return the current Xerces version.
- * @return the current Xerces version.
- */
- private static String getXercesVersion() {
- // If for some reason we can't get the version, set it to 1.0.
- String versionNumber = "1.0";
- try{
- // Use reflection to avoid a build dependency with Xerces.
- Class versionClass =
- Class.forName("org.apache.xerces.impl.Version");
- // Will return Xerces-J 2.x.0
- Method method =
- versionClass.getMethod("getVersion", (Class[]) null);
- String version = (String)method.invoke(null, (Object[]) null);
- versionNumber = version.substring( "Xerces-J".length() ,
- version.lastIndexOf(".") );
- } catch (Exception ex){
- // Do nothing.
- }
- return versionNumber;
- }
-
-
- /**
- * Create a <code>SAXParser</code> based on the underlying
- * <code>Xerces</code> version.
- * @param properties parser specific properties/features
- * @return an XML Schema/DTD enabled <code>SAXParser</code>
- */
- public static SAXParser newSAXParser(Properties properties)
- throws ParserConfigurationException,
- SAXException,
- SAXNotSupportedException {
-
- SAXParserFactory factory =
- (SAXParserFactory)properties.get("SAXParserFactory");
-
- if (versionNumber == null){
- versionNumber = getXercesVersion();
- version = new Float( versionNumber ).floatValue();
- }
-
- // Note: 2.2 is completely broken (with XML Schema).
- if (version > 2.1) {
-
- configureXerces(factory);
- return factory.newSAXParser();
- } else {
- SAXParser parser = factory.newSAXParser();
- configureOldXerces(parser,properties);
- return parser;
- }
- }
-
-
- /**
- * Configure schema validation as recommended by the JAXP 1.2 spec.
- * The <code>properties</code> object may contains information about
- * the schema local and language.
- * @param properties parser optional info
- */
- private static void configureOldXerces(SAXParser parser,
- Properties properties)
- throws ParserConfigurationException,
- SAXNotSupportedException {
-
- String schemaLocation = (String)properties.get("schemaLocation");
- String schemaLanguage = (String)properties.get("schemaLanguage");
-
- try{
- if (schemaLocation != null) {
- parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
- parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
- }
- } catch (SAXNotRecognizedException e){
- log.info(parser.getClass().getName() + ": "
- + e.getMessage() + " not supported.");
- }
-
- }
-
-
- /**
- * Configure schema validation as recommended by the Xerces spec.
- * Both DTD and Schema validation will be enabled simultaneously.
- * @param factory SAXParserFactory to be configured
- */
- private static void configureXerces(SAXParserFactory factory)
- throws ParserConfigurationException,
- SAXNotRecognizedException,
- SAXNotSupportedException {
-
- factory.setFeature(XERCES_DYNAMIC, true);
- factory.setFeature(XERCES_SCHEMA, true);
-
- }
-}
Deleted: trunk/java/org/apache/tomcat/util/digester/package.html
===================================================================
--- trunk/java/org/apache/tomcat/util/digester/package.html 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/digester/package.html 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,1275 +0,0 @@
-<html>
-<head>
-<title>Package Documentation for org.apache.commons.digester Package</title>
-</head>
-<body bgcolor="white">
-The Digester package provides for rules-based processing of arbitrary
-XML documents.
-<br><br>
-<a name="doc.Description"></a>
-<div align="center">
-<a href="#doc.Depend">[Dependencies]</a>
-<a href="#doc.Intro">[Introduction]</a>
-<a href="#doc.Properties">[Configuration Properties]</a>
-<a href="#doc.Stack">[The Object Stack]</a>
-<a href="#doc.Patterns">[Element Matching Patterns]</a>
-<a href="#doc.Rules">[Processing Rules]</a>
-<a href="#doc.Logging">[Logging]</a>
-<a href="#doc.Usage">[Usage Example]</a>
-<a href="#doc.Namespace">[Namespace Aware Parsing]</a>
-<a href="#doc.Pluggable">[Pluggable Rules Processing]</a>
-<a href="#doc.RuleSets">[Encapsulated Rule Sets]</a>
-<a href="#doc.NamedStacks">[Using Named Stacks For Inter-Rule Communication]</a>
-<a href="#doc.RegisteringDTDs">[Registering DTDs]</a>
-<a href="#doc.troubleshooting">[Troubleshooting]</a>
-<a href="#doc.FAQ">[FAQ]</a>
-<a href="#doc.Limits">[Known Limitations]</a>
-</div>
-
-<a name="doc.Depend"></a>
-<h3>External Dependencies</h3>
-
-<ul>
- <li>An XML parser conforming to
- <a href="http://java.sun.com/products/xml">JAXP
- </a>, version 1.1 or later (the first one to support SAX 2.0)
- </li>
- <li>
- <a href="http://jakarta.apache.org/builds/jakarta-commons/release/commons-beanutils">
-Beanutils Package (Jakarta Commons)</a>, version 1.5 or later
- </li>
- <li>
- <a href="http://jakarta.apache.org/builds/jakarta-commons/release/commons-collections">
-Collections Package (Jakarta Commons)</a>, version 2.1 or later
- </li>
- <li>
- <a href="http://jakarta.apache.org/builds/jakarta-commons/release/commons-logging">
-Commons Logging Package (Jakarta Commons)</a>, version 1.0.2 or later
- </li>
-</ul>
-
-<a name="doc.Intro"></a>
-<h3>Introduction</h3>
-
-<p>In many application environments that deal with XML-formatted data, it is
-useful to be able to process an XML document in an "event driven" manner,
-where particular Java objects are created (or methods of existing objects
-are invoked) when particular patterns of nested XML elements have been
-recognized. Developers familiar with the Simple API for XML Parsing (SAX)
-approach to processing XML documents will recognize that the Digester provides
-a higher level, more developer-friendly interface to SAX events, because most
-of the details of navigating the XML element hierarchy are hidden -- allowing
-the developer to focus on the processing to be performed.</p>
-
-<p>In order to use a Digester, the following basic steps are required:</p>
-<ul>
-<li>Create a new instance of the
- <code>org.apache.commons.digester.Digester</code> class. Previously
- created Digester instances may be safely reused, as long as you have
- completed any previously requested parse, and you do not try to utilize
- a particular Digester instance from more than one thread at a time.</li>
-<li>Set any desired <a href="#doc.Properties">configuration properties</a>
- that will customize the operation of the Digester when you next initiate
- a parse operation.</li>
-<li>Optionally, push any desired initial object(s) onto the Digester's
- <a href="#doc.Stack">object stack</a>.</li>
-<li>Register all of the <a href="#doc.Patterns">element matching patterns</a>
- for which you wish to have <a href="#doc.Rules">processing rules</a>
- fired when this pattern is recognized in an input document. You may
- register as many rules as you like for any particular pattern. If there
- is more than one rule for a given pattern, the rules will be executed in
- the order that they were listed.</li>
-<li>Call the <code>digester.parse()</code> method, passing a reference to the
- XML document to be parsed in one of a variety of forms. See the
- <a href="Digester.html#parse(java.io.File)">Digester.parse()</a>
- documentation for details. Note that you will need to be prepared to
- catch any <code>IOException</code> or <code>SAXException</code> that is
- thrown by the parser, or any runtime expression that is thrown by one of
- the processing rules.</li>
-</ul>
-
-<p>For example code, see <a href="#doc.Usage"> the usage
-examples</a>, and <a href="#doc.FAQ.Examples"> the FAQ </a>. </p>
-
-<a name="doc.Properties"></a>
-<h3>Digester Configuration Properties</h3>
-
-<p>A <code>org.apache.commons.digester.Digester</code> instance contains several
-configuration properties that can be used to customize its operation. These
-properties <strong>must</strong> be configured before you call one of the
-<code>parse()</code> variants, in order for them to take effect on that
-parse.</p>
-
-<blockquote>
- <table border="1">
- <tr>
- <th width="15%">Property</th>
- <th width="85%">Description</th>
- </tr>
- <tr>
- <td align="center">classLoader</td>
- <td>You can optionally specify the class loader that will be used to
- load classes when required by the <code>ObjectCreateRule</code>
- and <code>FactoryCreateRule</code> rules. If not specified,
- application classes will be loaded from the thread's context
- class loader (if the <code>useContextClassLoader</code> property
- is set to <code>true</code>) or the same class loader that was
- used to load the <code>Digester</code> class itself.</td>
- </tr>
- <tr>
- <td align="center">errorHandler</td>
- <td>You can optionally specify a SAX <code>ErrorHandler</code> that
- is notified when parsing errors occur. By default, any parsing
- errors that are encountered are logged, but Digester will continue
- processing as well.</td>
- </tr>
- <tr>
- <td align="center">namespaceAware</td>
- <td>A boolean that is set to <code>true</code> to perform parsing in a
- manner that is aware of XML namespaces. Among other things, this
- setting affects how elements are matched to processing rules. See
- <a href="#doc.Namespace">Namespace Aware Parsing</a> for more
- information.</td>
- </tr>
- <tr>
- <td align="center">ruleNamespaceURI</td>
- <td>The public URI of the namespace for which all subsequently added
- rules are associated, or <code>null</code> for adding rules that
- are not associated with any namespace. See
- <a href="#doc.Namespace">Namespace Aware Parsing</a> for more
- information.</td>
- </tr>
- <tr>
- <td align="center">rules</td>
- <td>The <code>Rules</code> component that actually performs matching of
- <code>Rule</code> instances against the current element nesting
- pattern is pluggable. By default, Digester includes a
- <code>Rules</code> implementation that behaves as described in this
- document. See
- <a href="#doc.Pluggable">Pluggable Rules Processing</a> for
- more information.</td>
- </tr>
- <tr>
- <td align="center">useContextClassLoader</code>
- <td>A boolean that is set to <code>true</code> if you want application
- classes required by <code>FactoryCreateRule</code> and
- <code>ObjectCreateRule</code> to be loaded from the context class
- loader of the current thread. By default, classes will be loaded
- from the class loader that loaded this <code>Digester</code> class.
- <strong>NOTE</strong> - This property is ignored if you set a
- value for the <code>classLoader</code> property; that class loader
- will be used unconditionally.</td>
- </tr>
- <tr>
- <td align="center">validating</td>
- <td>A boolean that is set to <code>true</code> if you wish to validate
- the XML document against a Document Type Definition (DTD) that is
- specified in its <code>DOCTYPE</code> declaration. The default
- value of <code>false</code> requests a parse that only detects
- "well formed" XML documents, rather than "valid" ones.</td>
- </tr>
- </table>
-</blockquote>
-
-<p>In addition to the scalar properties defined above, you can also register
-a local copy of a Document Type Definition (DTD) that is referenced in a
-<code>DOCTYPE</code> declaration. Such a registration tells the XML parser
-that, whenever it encounters a <code>DOCTYPE</code> declaration with the
-specified public identifier, it should utilize the actual DTD content at the
-registered system identifier (a URL), rather than the one in the
-<code>DOCTYPE</code> declaration.</p>
-
-<p>For example, the Struts framework controller servlet uses the following
-registration in order to tell Struts to use a local copy of the DTD for the
-Struts configuration file. This allows usage of Struts in environments that
-are not connected to the Internet, and speeds up processing even at Internet
-connected sites (because it avoids the need to go across the network).</p>
-
-<pre>
- URL url = new URL("/org/apache/struts/resources/struts-config_1_0.dtd");
- digester.register
- ("-//Apache Software Foundation//DTD Struts Configuration 1.0//EN",
- url.toString());
-</pre>
-
-<p>As a side note, the system identifier used in this example is the path
-that would be passed to <code>java.lang.ClassLoader.getResource()</code>
-or <code>java.lang.ClassLoader.getResourceAsStream()</code>. The actual DTD
-resource is loaded through the same class loader that loads all of the Struts
-classes -- typically from the <code>struts.jar</code> file.</p>
-
-<a name="doc.Stack"></a>
-<h3>The Object Stack</h3>
-
-<p>One very common use of <code>org.apache.commons.digester.Digester</code>
-technology is to dynamically construct a tree of Java objects, whose internal
-organization, as well as the details of property settings on these objects,
-are configured based on the contents of the XML document. In fact, the
-primary reason that the Digester package was created (it was originally part
-of Struts, and then moved to the Commons project because it was recognized
-as being generally useful) was to facilitate the
-way that the Struts controller servlet configures itself based on the contents
-of your application's <code>struts-config.xml</code> file.</p>
-
-<p>To facilitate this usage, the Digester exposes a stack that can be
-manipulated by processing rules that are fired when element matching patterns
-are satisfied. The usual stack-related operations are made available,
-including the following:</p>
-<ul>
-<li><a href="Digester.html#clear()">clear()</a> - Clear the current contents
- of the object stack.</li>
-<li><a href="Digester.html#peek()">peek()</a> - Return a reference to the top
- object on the stack, without removing it.</li>
-<li><a href="Digester.html#pop()">pop()</a> - Remove the top object from the
- stack and return it.</li>
-<li><a href="Digester.html#push(java.lang.Object)">push()</a> - Push a new
- object onto the top of the stack.</li>
-</ul>
-
-<p>A typical design pattern, then, is to fire a rule that creates a new object
-and pushes it on the stack when the beginning of a particular XML element is
-encountered. The object will remain there while the nested content of this
-element is processed, and it will be popped off when the end of the element
-is encountered. As we will see, the standard "object create" processing rule
-supports exactly this functionalility in a very convenient way.</p>
-
-<p>Several potential issues with this design pattern are addressed by other
-features of the Digester functionality:</p>
-<ul>
-<li><em>How do I relate the objects being created to each other?</em> - The
- Digester supports standard processing rules that pass the top object on
- the stack as an argument to a named method on the next-to-top object on
- the stack (or vice versa). This rule makes it easy to establish
- parent-child relationships between these objects. One-to-one and
- one-to-many relationships are both easy to construct.</li>
-<li><em>How do I retain a reference to the first object that was created?</em>
- As you review the description of what the "object create" processing rule
- does, it would appear that the first object you create (i.e. the object
- created by the outermost XML element you process) will disappear from the
- stack by the time that XML parsing is completed, because the end of the
- element would have been encountered. However, Digester will maintain a
- reference to the very first object ever pushed onto the object stack,
- and will return it to you
- as the return value from the <code>parse()</code> call. Alternatively,
- you can push a reference to some application object onto the stack before
- calling <code>parse()</code>, and arrange that a parent-child relationship
- be created (by appropriate processing rules) between this manually pushed
- object and the ones that are dynamically created. In this way,
- the pushed object will retain a reference to the dynamically created objects
- (and therefore all of their children), and will be returned to you after
- the parse finishes as well.</li>
-</ul>
-
-<a name="doc.Patterns"></a>
-<h3>Element Matching Patterns</h3>
-
-<p>A primary feature of the <code>org.apache.commons.digester.Digester</code>
-parser is that the Digester automatically navigates the element hierarchy of
-the XML document you are parsing for you, without requiring any developer
-attention to this process. Instead, you focus on deciding what functions you
-would like to have performed whenver a certain arrangement of nested elements
-is encountered in the XML document being parsed. The mechanism for specifying
-such arrangements are called <em>element matching patterns</em>.
-
-<p>A very simple element matching pattern is a simple string like "a". This
-pattern is matched whenever an <code><a></code> top-level element is
-encountered in the XML document, no matter how many times it occurs. Note that
-nested <code><a></code> elements will <strong>not</strong> match this
-pattern -- we will describe means to support this kind of matching later.</li>
-
-<p>The next step up in matching pattern complexity is "a/b". This pattern will
-be matched when a <code><b></code> element is found nested inside a
-top-level <code><a></code> element. Again, this match can occur as many
-times as desired, depending on the content of the XML document being parsed.
-You can use multiple slashes to define a hierarchy of any desired depth that
-will be matched appropriately.</p>
-
-<p>For example, assume you have registered processing rules that match patterns
-"a", "a/b", and "a/b/c". For an input XML document with the following
-contents, the indicated patterns will be matched when the corresponding element
-is parsed:</p>
-<pre>
- <a> -- Matches pattern "a"
- <b> -- Matches pattern "a/b"
- <c/> -- Matches pattern "a/b/c"
- <c/> -- Matches pattern "a/b/c"
- </b>
- <b> -- Matches pattern "a/b"
- <c/> -- Matches pattern "a/b/c"
- <c/> -- Matches pattern "a/b/c"
- <c/> -- Matches pattern "a/b/c"
- </b>
- </a>
-</pre>
-
-<p>It is also possible to match a particular XML element, no matter how it is
-nested (or not nested) in the XML document, by using the "*" wildcard character
-in your matching pattern strings. For example, an element matching pattern
-of "*/a" will match an <code><a></code> element at any nesting position
-within the document.</p>
-
-<p>It is quite possible that, when a particular XML element is being parsed,
-the pattern for more than one registered processing rule will be matched
- either because you registered more than one processing rule with the same
-matching pattern, or because one more more exact pattern matches and wildcard
-pattern matches are satisfied by the same element.</p>
-
-<p>When this occurs, the corresponding processing rules will all be fired in order.
-<code>begin</code> (and <code>body</code>) method calls are executed in the
-order that the <code>Rules</code> where initially registered with the
-<code>Digester</code>, whilst <code>end</code> method calls are execute in
-reverse order. In other words - the order is first in, last out.</p>
-
-<a name="doc.Rules"></a>
-<h3>Processing Rules</h3>
-
-<p>The <a href="#doc.Patterns">previous section</a> documented how you identify
-<strong>when</strong> you wish to have certain actions take place. The purpose
-of processing rules is to define <strong>what</strong> should happen when the
-patterns are matched.</p>
-
-<p>Formally, a processing rule is a Java class that subclasses the
-<a href="Rule.html">org.apache.commons.digester.Rule</a> interface. Each Rule
-implements one or more of the following event methods that are called at
-well-defined times when the matching patterns corresponding to this rule
-trigger it:</p>
-<ul>
-<li><a href="Rule.html#begin(org.xml.sax.AttributeList)">begin()</a> -
- Called when the beginning of the matched XML element is encountered. A
- data structure containing all of the attributes corresponding to this
- element are passed as well.</li>
-<li><a href="Rule.html#body(java.lang.String)">body()</a> -
- Called when nested content (that is not itself XML elements) of the
- matched element is encountered. Any leading or trailing whitespace will
- have been removed as part of the parsing process.</li>
-<li><a href="Rule.html#end()">end()</a> - Called when the ending of the matched
- XML element is encountered. If nested XML elements that matched other
- processing rules was included in the body of this element, the appropriate
- processing rules for the matched rules will have already been completed
- before this method is called.</li>
-<li><a href="Rule.html#finish()">finish()</a> - Called when the parse has
- been completed, to give each rule a chance to clean up any temporary data
- they might have created and cached.</li>
-</ul>
-
-<p>As you are configuring your digester, you can call the
-<code>addRule()</code> method to register a specific element matching pattern,
-along with an instance of a <code>Rule</code> class that will have its event
-handling methods called at the appropriate times, as described above. This
-mechanism allows you to create <code>Rule</code> implementation classes
-dynamically, to implement any desired application specific functionality.</p>
-
-<p>In addition, a set of processing rule implementation classes are provided,
-which deal with many common programming scenarios. These classes include the
-following:</p>
-<ul>
-<li><a href="ObjectCreateRule.html">ObjectCreateRule</a> - When the
- <code>begin()</code> method is called, this rule instantiates a new
- instance of a specified Java class, and pushes it on the stack. The
- class name to be used is defaulted according to a parameter passed to
- this rule's constructor, but can optionally be overridden by a classname
- passed via the specified attribute to the XML element being processed.
- When the <code>end()</code> method is called, the top object on the stack
- (presumably, the one we added in the <code>begin()</code> method) will
- be popped, and any reference to it (within the Digester) will be
- discarded.</li>
-<li><a href="FactoryCreateRule.html">FactoryCreateRule</a> - A variation of
- <code>ObjectCreateRule</code> that is useful when the Java class with
- which you wish to create an object instance does not have a no-arguments
- constructor, or where you wish to perform other setup processing before
- the object is handed over to the Digester.</li>
-<li><a href="SetPropertiesRule.html">SetPropertiesRule</a> - When the
- <code>begin()</code> method is called, the digester uses the standard
- Java Reflection API to identify any JavaBeans property setter methods
- (on the object at the top of the digester's stack)
- who have property names that match the attributes specified on this XML
- element, and then call them individually, passing the corresponding
- attribute values. These natural mappings can be overridden. This allows
- (for example) a <code>class</code> attribute to be mapped correctly.
- It is recommended that this feature should not be overused - in most cases,
- it's better to use the standard <code>BeanInfo</code> mechanism.
- A very common idiom is to define an object create
- rule, followed by a set properties rule, with the same element matching
- pattern. This causes the creation of a new Java object, followed by
- "configuration" of that object's properties based on the attributes
- of the same XML element that created this object.</li>
-<li><a href="SetPropertyRule.html">SetPropertyRule</a> - When the
- <code>begin()</code> method is called, the digester calls a specified
- property setter (where the property itself is named by an attribute)
- with a specified value (where the value is named by another attribute),
- on the object at the top of the digester's stack.
- This is useful when your XML file conforms to a particular DTD, and
- you wish to configure a particular property that does not have a
- corresponding attribute in the DTD.</li>
-<li><a href="SetNextRule.html">SetNextRule</a> - When the
- <code>end()</code> method is called, the digester analyzes the
- next-to-top element on the stack, looking for a property setter method
- for a specified property. It then calls this method, passing the object
- at the top of the stack as an argument. This rule is commonly used to
- establish one-to-many relationships between the two objects, with the
- method name commonly being something like "addChild".</li>
-<li><a href="SetTopRule.html">SetTopRule</a> - When the
- <code>end()</code> method is called, the digester analyzes the
- top element on the stack, looking for a property setter method for a
- specified property. It then calls this method, passing the next-to-top
- object on the stack as an argument. This rule would be used as an
- alternative to a SetNextRule, with a typical method name "setParent",
- if the API supported by your object classes prefers this approach.</li>
-<li><a href="CallMethodRule.html">CallMethodRule</a> - This rule sets up a
- method call to a named method of the top object on the digester's stack,
- which will actually take place when the <code>end()</code> method is
- called. You configure this rule by specifying the name of the method
- to be called, the number of arguments it takes, and (optionally) the
- Java class name(s) defining the type(s) of the method's arguments.
- The actual parameter values, if any, will typically be accumulated from
- the body content of nested elements within the element that triggered
- this rule, using the CallParamRule discussed next.</li>
-<li><a href="CallParamRule.html">CallParamRule</a> - This rule identifies
- the source of a particular numbered (zero-relative) parameter for a
- CallMethodRule within which we are nested. You can specify that the
- parameter value be taken from a particular named attribute, or from the
- nested body content of this element.</li>
-<li><a href="NodeCreateRule.html">NodeCreateRule</a> - A specialized rule
- that converts part of the tree into a <code>DOM Node</code> and then
- pushes it onto the stack.</li>
-</ul>
-
-<p>You can create instances of the standard <code>Rule</code> classes and
-register them by calling <code>digester.addRule()</code>, as described above.
-However, because their usage is so common, shorthand registration methods are
-defined for each of the standard rules, directly on the <code>Digester</code>
-class. For example, the following code sequence:</p>
-<pre>
- Rule rule = new SetNextRule(digester, "addChild",
- "com.mycompany.mypackage.MyChildClass");
- digester.addRule("a/b/c", rule);
-</pre>
-<p>can be replaced by:</p>
-<pre>
- digester.addSetNext("a/b/c", "addChild",
- "com.mycompany.mypackage.MyChildClass");
-</pre>
-
-<a name="doc.Logging"></a>
-<h3>Logging</h3>
-
-<p>Logging is a vital tool for debugging Digester rulesets. Digester can log
-copious amounts of debugging information. So, you need to know how logging
-works before you start using Digester seriously.</p>
-
-<p>Digester uses
-<a href="http://jakarta.apache.org/commons/logging.html">Jakarta Commons
-Logging</a>. This component is not really a logging framework - rather
-an extensible, configurable bridge. It can be configured to swallow all log
-messages, to provide very basic logging by itself or to pass logging messages
-on to more sophisticated logging frameworks. Commons-Logging comes with
-connectors for many popular logging frameworks. Consult the commons-logging
-documentation for more information.</p>
-
-<p>Two main logs are used by Digester:</p>
-<ul>
-<li>SAX-related messages are logged to
- <strong><code>org.apache.commons.digester.Digester.sax</code></strong>.
- This log gives information about the basic SAX events received by
- Digester.</li>
-<li><strong><code>org.apache.commons.digester.Digester</code></strong> is used
- for everything else. You'll probably want to have this log turned up during
- debugging but turned down during production due to the high message
- volume.</li>
-</ul>
-
-<p>Complete documentation of how to configure Commons-Logging can be found
-in the Commons Logging package documentation. However, as a simple example,
-let's assume that you want to use the <code>SimpleLog</code> implementation
-that is included in Commons-Logging, and set up Digester to log events from
-the <code>Digester</code> logger at the DEBUG level, while you want to log
-events from the <code>Digester.log</code> logger at the INFO level. You can
-accomplish this by creating a <code>commons-logging.properties</code> file
-in your classpath (or setting corresponding system properties on the command
-line that starts your application) with the following contents:</p>
-<pre>
- org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
- org.apache.commons.logging.simplelog.log.org.apache.commons.digester.Digester=debug
- org.apache.commons.logging.simplelog.log.org.apache.commons.digester.Digester.sax=info
-</pre>
-
-<a name="doc.Usage"></a>
-<h3>Usage Examples</h3>
-
-
-<h5>Creating a Simple Object Tree</h5>
-
-<p>Let's assume that you have two simple JavaBeans, <code>Foo</code> and
-<code>Bar</code>, with the following method signatures:</p>
-<pre>
- package mypackage;
- public class Foo {
- public void addBar(Bar bar);
- public Bar findBar(int id);
- public Iterator getBars();
- public String getName();
- public void setName(String name);
- }
-
- public mypackage;
- public class Bar {
- public int getId();
- public void setId(int id);
- public String getTitle();
- public void setTitle(String title);
- }
-</pre>
-
-<p>and you wish to use Digester to parse the following XML document:</p>
-
-<pre>
- <foo name="The Parent">
- <bar id="123" title="The First Child"/>
- <bar id="456" title="The Second Child"/>
- </foo>
-</pre>
-
-<p>A simple approach will be to use the following Digester in the following way
-to set up the parsing rules, and then process an input file containing this
-document:</p>
-
-<pre>
- Digester digester = new Digester();
- digester.setValidating(false);
- digester.addObjectCreate("foo", "mypackage.Foo");
- digester.addSetProperties("foo");
- digester.addObjectCreate("foo/bar", "mypackage.Bar");
- digester.addSetProperties("foo/bar");
- digester.addSetNext("foo/bar", "addBar", "mypackage.Bar");
- Foo foo = (Foo) digester.parse();
-</pre>
-
-<p>In order, these rules do the following tasks:</p>
-<ol>
-<li>When the outermost <code><foo></code> element is encountered,
- create a new instance of <code>mypackage.Foo</code> and push it
- on to the object stack. At the end of the <code><foo></code>
- element, this object will be popped off of the stack.</li>
-<li>Cause properties of the top object on the stack (i.e. the <code>Foo</code>
- object that was just created and pushed) to be set based on the values
- of the attributes of this XML element.</li>
-<li>When a nested <code><bar></code> element is encountered,
- create a new instance of <code>mypackage.Bar</code> and push it
- on to the object stack. At the end of the <code><bar></code>
- element, this object will be popped off of the stack (i.e. after the
- remaining rules matching <code>foo/bar</code> are processed).</li>
-<li>Cause properties of the top object on the stack (i.e. the <code>Bar</code>
- object that was just created and pushed) to be set based on the values
- of the attributes of this XML element. Note that type conversions
- are automatically performed (such as String to int for the <code>id</code>
- property), for all converters registered with the <code>ConvertUtils</code>
- class from <code>commons-beanutils</code> package.</li>
-<li>Cause the <code>addBar</code> method of the next-to-top element on the
- object stack (which is why this is called the "set <em>next</em>" rule)
- to be called, passing the element that is on the top of the stack, which
- must be of type <code>mypackage.Bar</code>. This is the rule that causes
- the parent/child relationship to be created.</li>
-</ol>
-
-<p>Once the parse is completed, the first object that was ever pushed on to the
-stack (the <code>Foo</code> object in this case) is returned to you. It will
-have had its properties set, and all of its child <code>Bar</code> objects
-created for you.</p>
-
-
-<h5>Processing A Struts Configuration File</h5>
-
-<p>As stated earlier, the primary reason that the
-<code>Digester</code> package was created is because the
-Struts controller servlet itself needed a robust, flexible, easy to extend
-mechanism for processing the contents of the <code>struts-config.xml</code>
-configuration that describes nearly every aspect of a Struts-based application.
-Because of this, the controller servlet contains a comprehensive, real world,
-example of how the Digester can be employed for this type of a use case.
-See the <code>initDigester()</code> method of class
-<code>org.apache.struts.action.ActionServlet</code> for the code that creates
-and configures the Digester to be used, and the <code>initMapping()</code>
-method for where the parsing actually takes place.</p>
-
-<p>(Struts binary and source distributions can be acquired at
-<a href="http://jakarta.apache.org/struts/">http://jakarta.apache.org/struts/</a>.)</p>
-
-<p>The following discussion highlights a few of the matching patterns and
-processing rules that are configured, to illustrate the use of some of the
-Digester features. First, let's look at how the Digester instance is
-created and initialized:</p>
-<pre>
- Digester digester = new Digester();
- digester.push(this); // Push controller servlet onto the stack
- digester.setValidating(true);
-</pre>
-
-<p>We see that a new Digester instance is created, and is configured to use
-a validating parser. Validation will occur against the struts-config_1_0.dtd
-DTD that is included with Struts (as discussed earlier). In order to provide
-a means of tracking the configured objects, the controller servlet instance
-itself will be added to the digester's stack.</p>
-
-<pre>
- digester.addObjectCreate("struts-config/global-forwards/forward",
- forwardClass, "className");
- digester.addSetProperties("struts-config/global-forwards/forward");
- digester.addSetNext("struts-config/global-forwards/forward",
- "addForward",
- "org.apache.struts.action.ActionForward");
- digester.addSetProperty
- ("struts-config/global-forwards/forward/set-property",
- "property", "value");
-</pre>
-
-<p>The rules created by these lines are used to process the global forward
-declarations. When a <code><forward></code> element is encountered,
-the following actions take place:</p>
-<ul>
-<li>A new object instance is created -- the <code>ActionForward</code>
- instance that will represent this definition. The Java class name
- defaults to that specified as an initialization parameter (which
- we have stored in the String variable <code>forwardClass</code>), but can
- be overridden by using the "className" attribute (if it is present in the
- XML element we are currently parsing). The new <code>ActionForward</code>
- instance is pushed onto the stack.</li>
-<li>The properties of the <code>ActionForward</code> instance (at the top of
- the stack) are configured based on the attributes of the
- <code><forward></code> element.</li>
-<li>Nested occurrences of the <code><set-property></code> element
- cause calls to additional property setter methods to occur. This is
- required only if you have provided a custom implementation of the
- <code>ActionForward</code> class with additional properties that are
- not included in the DTD.</li>
-<li>The <code>addForward()</code> method of the next-to-top object on
- the stack (i.e. the controller servlet itself) will be called, passing
- the object at the top of the stack (i.e. the <code>ActionForward</code>
- instance) as an argument. This causes the global forward to be
- registered, and as a result of this it will be remembered even after
- the stack is popped.</li>
-<li>At the end of the <code><forward></code> element, the top element
- (i.e. the <code>ActionForward</code> instance) will be popped off the
- stack.</li>
-</ul>
-
-<p>Later on, the digester is actually executed as follows:</p>
-<pre>
- InputStream input =
- getServletContext().getResourceAsStream(config);
- ...
- try {
- digester.parse(input);
- input.close();
- } catch (SAXException e) {
- ... deal with the problem ...
- }
-</pre>
-
-<p>As a result of the call to <code>parse()</code>, all of the configuration
-information that was defined in the <code>struts-config.xml</code> file is
-now represented as collections of objects cached within the Struts controller
-servlet, as well as being exposed as servlet context attributes.</p>
-
-
-<h5>Parsing Body Text In XML Files</h5>
-
-<p>The Digester module also allows you to process the nested body text in an
-XML file, not just the elements and attributes that are encountered. The
-following example is based on an assumed need to parse the web application
-deployment descriptor (<code>/WEB-INF/web.xml</code>) for the current web
-application, and record the configuration information for a particular
-servlet. To record this information, assume the existence of a bean class
-with the following method signatures (among others):</p>
-<pre>
- package com.mycompany;
- public class ServletBean {
- public void setServletName(String servletName);
- public void setServletClass(String servletClass);
- public void addInitParam(String name, String value);
- }
-</pre>
-
-<p>We are going to process the <code>web.xml</code> file that declares the
-controller servlet in a typical Struts-based application (abridged for
-brevity in this example):</p>
-<pre>
- <web-app>
- ...
- <servlet>
- <servlet-name>action</servlet-name>
- <servlet-class>org.apache.struts.action.ActionServlet<servlet-class>
- <init-param>
- <param-name>application</param-name>
- <param-value>org.apache.struts.example.ApplicationResources<param-value>
- </init-param>
- <init-param>
- <param-name>config</param-name>
- <param-value>/WEB-INF/struts-config.xml<param-value>
- </init-param>
- </servlet>
- ...
- </web-app>
-</pre>
-
-<p>Next, lets define some Digester processing rules for this input file:</p>
-<pre>
- digester.addObjectCreate("web-app/servlet",
- "com.mycompany.ServletBean");
- digester.addCallMethod("web-app/servlet/servlet-name", "setServletName", 0);
- digester.addCallMethod("web-app/servlet/servlet-class",
- "setServletClass", 0);
- digester.addCallMethod("web-app/servlet/init-param",
- "addInitParam", 2);
- digester.addCallParam("web-app/servlet/init-param/param-name", 0);
- digester.addCallParam("web-app/servlet/init-param/param-value", 1);
-</pre>
-
-<p>Now, as elements are parsed, the following processing occurs:</p>
-<ul>
-<li><em><servlet></em> - A new <code>com.mycompany.ServletBean</code>
- object is created, and pushed on to the object stack.</li>
-<li><em><servlet-name></em> - The <code>setServletName()</code> method
- of the top object on the stack (our <code>ServletBean</code>) is called,
- passing the body content of this element as a single parameter.</li>
-<li><em><servlet-class></em> - The <code>setServletClass()</code> method
- of the top object on the stack (our <code>ServletBean</code>) is called,
- passing the body content of this element as a single parameter.</li>
-<li><em><init-param></em> - A call to the <code>addInitParam</code>
- method of the top object on the stack (our <code>ServletBean</code>) is
- set up, but it is <strong>not</strong> called yet. The call will be
- expecting two <code>String</code> parameters, which must be set up by
- subsequent call parameter rules.</li>
-<li><em><param-name></em> - The body content of this element is assigned
- as the first (zero-relative) argument to the call we are setting up.</li>
-<li><em><param-value></em> - The body content of this element is assigned
- as the second (zero-relative) argument to the call we are setting up.</li>
-<li><em></init-param></em> - The call to <code>addInitParam()</code>
- that we have set up is now executed, which will cause a new name-value
- combination to be recorded in our bean.</li>
-<li><em><init-param></em> - The same set of processing rules are fired
- again, causing a second call to <code>addInitParam()</code> with the
- second parameter's name and value.</li>
-<li><em></servlet></em> - The element on the top of the object stack
- (which should be the <code>ServletBean</code> we pushed earlier) is
- popped off the object stack.</li>
-</ul>
-
-
-<a name="doc.Namespace"></a>
-<h3>Namespace Aware Parsing</h3>
-
-<p>For digesting XML documents that do not use XML namespaces, the default
-behavior of <code>Digester</code>, as described above, is generally sufficient.
-However, if the document you are processing uses namespaces, it is often
-convenient to have sets of <code>Rule</code> instances that are <em>only</em>
-matched on elements that use the prefix of a particular namespace. This
-approach, for example, makes it possible to deal with element names that are
-the same in different namespaces, but where you want to perform different
-processing for each namespace. </p>
-
-<p>Digester does not provide full support for namespaces, but does provide
-sufficient to accomplish most tasks. Enabling digester's namespace support
-is done by following these steps:</p>
-
-<ol>
-<li>Tell <code>Digester</code> that you will be doing namespace
- aware parsing, by adding this statement in your initalization
- of the Digester's properties:
- <pre>
- digester.setNamespaceAware(true);
- </pre></li>
-<li>Declare the public namespace URI of the namespace with which
- following rules will be associated. Note that you do <em>not</em>
- make any assumptions about the prefix - the XML document author
- is free to pick whatever prefix they want:
- <pre>
- digester.setRuleNamespaceURI("http://www.mycompany.com/MyNamespace");
- </pre></li>
-<li>Add the rules that correspond to this namespace, in the usual way,
- by calling methods like <code>addObjectCreate()</code> or
- <code>addSetProperties()</code>. In the matching patterns you specify,
- use only the <em>local name</em> portion of the elements (i.e. the
- part after the prefix and associated colon (":") character:
- <pre>
- digester.addObjectCreate("foo/bar", "com.mycompany.MyFoo");
- digester.addSetProperties("foo/bar");
- </pre></li>
-<li>Repeat the previous two steps for each additional public namespace URI
- that should be recognized on this <code>Digester</code> run.</li>
-</ol>
-
-<p>Now, consider that you might wish to digest the following document, using
-the rules that were set up in the steps above:</p>
-<pre>
-<m:foo
- xmlns:m="http://www.mycompany.com/MyNamespace"
- xmlns:y="http://www.yourcompany.com/YourNamespace">
-
- <m:bar name="My Name" value="My Value"/>
-
- <y:bar id="123" product="Product Description"/>L
-
-</x:foo>
-</pre>
-
-<p>Note that your object create and set properties rules will be fired for the
-<em>first</em> occurrence of the <code>bar</code> element, but not the
-<em>second</em> one. This is because we declared that our rules only matched
-for the particular namespace we are interested in. Any elements in the
-document that are associated with other namespaces (or no namespaces at all)
-will not be processed. In this way, you can easily create rules that digest
-only the portions of a compound document that they understand, without placing
-any restrictions on what other content is present in the document.</p>
-
-<p>You might also want to look at <a href="#doc.RuleSets">Encapsulated
-Rule Sets</a> if you wish to reuse a particular set of rules, associated
-with a particular namespace, in more than one application context.</p>
-
-<h4>Using Namespace Prefixes In Pattern Matching</h4>
-
-<p>Using rules with namespaces is very useful when you have orthogonal rulesets.
-One ruleset applies to a namespace and is independent of other rulesets applying
-to other namespaces. However, if your rule logic requires mixed namespaces, then
-matching namespace prefix patterns might be a better strategy.</p>
-
-<p>When you set the <code>NamespaceAware</code> property to false, digester uses
-the qualified element name (which includes the namespace prefix) rather than the
-local name as the patten component for the element. This means that your pattern
-matches can include namespace prefixes as well as element names. So, rather than
-create namespace-aware rules, create pattern matches including the namespace
-prefixes.</p>
-
-<p>For example, (with <code>NamespaceAware</code> false), the pattern <code>
-'foo:bar'</code> will match a top level element named <code>'bar'</code> in the
-namespace with (local) prefix <code>'foo'</code>.</p>
-
-<h4>Limitations of Digester Namespace support</h4>
-<p>Digester does not provide general "xpath-compliant" matching;
-only the namespace attached to the <i>last</i> element in the match path
-is involved in the matching process. Namespaces attached to parent
-elements are ignored for matching purposes.</p>
-
-
-<a name="doc.Pluggable"></a>
-<h3>Pluggable Rules Processing</h3>
-
-<p>By default, <code>Digester</code> selects the rules that match a particular
-pattern of nested elements as described under
-<a href="#doc.Patterns">Element Matching Patterns</a>. If you prefer to use
-different selection policies, however, you can create your own implementation
-of the <a href="Rules.html">org.apache.commons.digester.Rules</a> interface,
-or subclass the corresponding convenience base class
-<a href="RulesBase.html">org.apache.commons.digester.RulesBase</a>.
-Your implementation of the <code>match()</code> method will be called when the
-processing for a particular element is started or ended, and you must return
-a <code>List</code> of the rules that are relevant for the current nesting
-pattern. The order of the rules you return <strong>is</strong> significant,
-and should match the order in which rules were initally added.</p>
-
-<p>Your policy for rule selection should generally be sensitive to whether
-<a href="#doc.Namespace">Namespace Aware Parsing</a> is taking place. In
-general, if <code>namespaceAware</code> is true, you should select only rules
-that:</p>
-<ul>
-<li>Are registered for the public namespace URI that corresponds to the
- prefix being used on this element.</li>
-<li>Match on the "local name" portion of the element (so that the document
- creator can use any prefix that they like).</li>
-</ul>
-
-<h4>ExtendedBaseRules</h4>
-<p><a href="ExtendedBaseRules.html">ExtendedBaseRules</a>,
-adds some additional expression syntax for pattern matching
-to the default mechanism, but it also executes more slowly. See the
-JavaDocs for more details on the new pattern matching syntax, and suggestions
-on when this implementation should be used. To use it, simply do the
-following as part of your Digester initialization:</p>
-
-<pre>
- Digester digester = ...
- ...
- digester.setRules(new ExtendedBaseRules());
- ...
-</pre>
-
-<h4>RegexRules</h4>
-<p><a href="RegexRules.html">RegexRules</a> is an advanced <code>Rules</code>
-implementation which does not build on the default pattern matching rules.
-It uses a pluggable <a href="RegexMatcher.html">RegexMatcher</a> implementation to test
-if a path matches the pattern for a Rule. All matching rules are returned
-(note that this behaviour differs from longest matching rule of the default
- pattern matching rules). See the Java Docs for more details.
-</p>
-<p>
-Example usage:
-</p>
-
-<pre>
- Digester digester = ...
- ...
- digester.setRules(new RegexRules(new SimpleRegexMatcher()));
- ...
-</pre>
-<h5>RegexMatchers</h5>
-<p>
-<code>Digester</code> ships only with one <code>RegexMatcher</code>
-implementation: <a href='SimpleRegexMatcher.html'>SimpleRegexMatcher</a>.
-This implementation is unsophisticated and lacks many good features
-lacking in more power Regex libraries. There are some good reasons
-why this approach was adopted. The first is that <code>SimpleRegexMatcher</code>
-is simple, it is easy to write and runs quickly. The second has to do with
-the way that <code>RegexRules</code> is intended to be used.
-</p>
-<p>
-There are many good regex libraries available. (For example
-<a href='http://jakarta.apache.org/oro/index.html'>Jakarta ORO</a>,
-<a href='http://jakarta.apache.org/regexp/index.html'>Jakarta Regex</a>,
-<a href='http://www.cacas.org/java/gnu/regexp/'>GNU Regex</a> and
-<a href='http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/package-summary.html'>
-Java 1.4 Regex</a>)
-Not only do different people have different personal tastes when it comes to
-regular expression matching but these products all offer different functionality
-and different strengths.
-</p>
-<p>
-The pluggable <code>RegexMatcher</code> is a thin bridge
-designed to adapt other Regex systems. This allows any Regex library the user
-desires to be plugged in and used just by creating one class.
-<code>Digester</code> does not (currently) ship with bridges to the major
-regex (to allow the dependencies required by <code>Digester</code>
-to be kept to a minimum).
-</p>
-
-<h4>WithDefaultsRulesWrapper</h4>
-<p>
-<a href="WithDefaultsRulesWrapper.html"> WithDefaultsRulesWrapper</a> allows
-default <code>Rule</code> instances to be added to any existing
-<code>Rules</code> implementation. These default <code>Rule</code> instances
-will be returned for any match for which the wrapped implementation does not
-return any matches.
-</p>
-<p>
-For example,
-<pre>
- Rule alpha;
- ...
- WithDefaultsRulesWrapper rules = new WithDefaultsRulesWrapper(new BaseRules());
- rules.addDefault(alpha);
- ...
- digester.setRules(rules);
- ...
-</pre>
-when a pattern does not match any other rule, then rule alpha will be called.
-</p>
-<p>
-<code>WithDefaultsRulesWrapper</code> follows the <em>Decorator</em> pattern.
-</p>
-
-<a name="doc.RuleSets"></a>
-<h3>Encapsulated Rule Sets</h3>
-
-<p>All of the examples above have described a scenario where the rules to be
-processed are registered with a <code>Digester</code> instance immediately
-after it is created. However, this approach makes it difficult to reuse the
-same set of rules in more than one application environment. Ideally, one
-could package a set of rules into a single class, which could be easily
-loaded and registered with a <code>Digester</code> instance in one easy step.
-</p>
-
-<p>The <a href="RuleSet.html">RuleSet</a> interface (and the convenience base
-class <a href="RuleSetBase.html">RuleSetBase</a>) make it possible to do this.
-In addition, the rule instances registered with a particular
-<code>RuleSet</code> can optionally be associated with a particular namespace,
-as described under <a href="#doc.Namespace">Namespace Aware Processing</a>.</p>
-
-<p>An example of creating a <code>RuleSet</code> might be something like this:
-</p>
-<pre>
-public class MyRuleSet extends RuleSetBase {
-
- public MyRuleSet() {
- this("");
- }
-
- public MyRuleSet(String prefix) {
- super();
- this.prefix = prefix;
- this.namespaceURI = "http://www.mycompany.com/MyNamespace";
- }
-
- protected String prefix = null;
-
- public void addRuleInstances(Digester digester) {
- digester.addObjectCreate(prefix + "foo/bar",
- "com.mycompany.MyFoo");
- digester.addSetProperties(prefix + "foo/bar");
- }
-
-}
-</pre>
-
-<p>You might use this <code>RuleSet</code> as follow to initialize a
-<code>Digester</code> instance:</p>
-<pre>
- Digester digester = new Digester();
- ... configure Digester properties ...
- digester.addRuleSet(new MyRuleSet("baz/"));
-</pre>
-
-<p>A couple of interesting notes about this approach:</p>
-<ul>
-<li>The application that is using these rules does not need to know anything
- about the fact that the <code>RuleSet</code> being used is associated
- with a particular namespace URI. That knowledge is emedded inside the
- <code>RuleSet</code> class itself.</li>
-<li>If desired, you could make a set of rules work for more than one
- namespace URI by providing constructors on the <code>RuleSet</code> to
- allow this to be specified dynamically.</li>
-<li>The <code>MyRuleSet</code> example above illustrates another technique
- that increases reusability -- you can specify (as an argument to the
- constructor) the leading portion of the matching pattern to be used.
- In this way, you can construct a <code>Digester</code> that recognizes
- the same set of nested elements at different nesting levels within an
- XML document.</li>
-</ul>
-<a name="doc.NamedStacks"></a>
-<h3>Using Named Stacks For Inter-Rule Communication</h3>
-<p>
-<code>Digester</code> is based on <code>Rule</code> instances working together
-to process xml. For anything other than the most trival processing,
-communication between <code>Rule</code> instances is necessary. Since <code>Rule</code>
-instances are processed in sequence, this usually means storing an Object
-somewhere where later instances can retrieve it.
-</p>
-<p>
-<code>Digester</code> is based on SAX. The most natural data structure to use with
-SAX based xml processing is the stack. This allows more powerful processes to be
-specified more simply since the pushing and popping of objects can mimic the
-nested structure of the xml.
-</p>
-<p>
-<code>Digester</code> uses two basic stacks: one for the main beans and the other
-for parameters for method calls. These are inadequate for complex processing
-where many different <code>Rule</code> instances need to communicate through
-different channels.
-</p>
-<p>
-In this case, it is recommended that named stacks are used. In addition to the
-two basic stacks, <code>Digester</code> allows rules to use an unlimited number
-of other stacks referred two by an identifying string (the name). (That's where
-the term <em>named stack</em> comes from.) These stacks are
-accessed through calls to:
-</p>
-<ul>
- <li><a href='Digester.html#push(java.lang.String, java.lang.Object)'>
- void push(String stackName, Object value)</a></li>
- <li><a href='Digester.html#pop(java.lang.String)'>
- Object pop(String stackName)</a></li>
- <li><a href='Digester.html#peek(java.lang.String)'>
- Object peek(String stackName)</a></li>
-</ul>
-<p>
-<strong>Note:</strong> all stack names beginning with <code>org.apache.commons.digester</code>
-are reserved for future use by the <code>Digester</code> component. It is also recommended
-that users choose stack names perfixed by the name of their own domain to avoid conflicts
-with other <code>Rule</code> implementations.
-</p>
-<a name="doc.RegisteringDTDs"></a>
-<h3>Registering DTDs</h3>
-
-<h4>Brief (But Still Too Long) Introduction To System and Public Identifiers</h4>
-<p>A definition for an external entity comes in one of two forms:
-</p>
-<ol>
- <li><code>SYSTEM <em>system-identifier</em></code></li>
- <li><code>PUBLIC <em>public-identifier</em> <em>system-identifier</em></code></li>
-</ol>
-<p>
-The <code><em>system-identifier</em></code> is an URI from which the resource can be obtained
-(either directly or indirectly). Many valid URIs may identify the same resource.
-The <code><em>public-identifier</em></code> is an additional free identifier which may be used
-(by the parser) to locate the resource.
-</p>
-<p>
-In practice, the weakness with a <code><em>system-identifier</em></code> is that most parsers
-will attempt to interprete this URI as an URL, try to download the resource directly
-from the URL and stop the parsing if this download fails. So, this means that
-almost always the URI will have to be an URL from which the declaration
-can be downloaded.
-</p>
-<p>
-URLs may be local or remote but if the URL is chosen to be local, it is likely only
-to function correctly on a small number of machines (which are configured precisely
-to allow the xml to be parsed). This is usually unsatisfactory and so a universally
-accessable URL is preferred. This usually means an internet URL.
-</p>
-<p>
-To recap, in practice the <code><em>system-identifier</em></code> will (most likely) be an
-internet URL. Unfortunately downloading from an internet URL is not only slow
-but unreliable (since successfully downloading a document from the internet
-relies on the client being connect to the internet and the server being
-able to satisfy the request).
-</p>
-<p>
-The <code><em>public-identifier</em></code> is a freely defined name but (in practice) it is
-strongly recommended that a unique, readable and open format is used (for reasons
-that should become clear later). A Formal Public Identifier (FPI) is a very
-common choice. This public identifier is often used to provide a unique and location
-independent key which can be used to subsistute local resources for remote ones
-(hint: this is why ;).
-</p>
-<p>
-By using the second (<code>PUBLIC</code>) form combined with some form of local
-catalog (which matches <code><em>public-identifiers</em></code> to local resources) and where
-the <code><em>public-identifier</em></code> is a unique name and the <code><em>system-identifier</em></code>
-is an internet URL, the practical disadvantages of specifying just a
-<code><em>system-identifier</em></code> can be avoided. Those external entities which have been
-store locally (on the machine parsing the document) can be identified and used.
-Only when no local copy exists is it necessary to download the document
-from the internet URL. This naming scheme is recommended when using <code>Digester</code>.
-</p>
-
-<h4>External Entity Resolution Using Digester</h4>
-<p>
-SAX factors out the resolution of external entities into an <code>EntityResolver</code>.
-<code>Digester</code> supports the use of custom <code>EntityResolver</code>
-but ships with a simple internal implementation. This implementation allows local URLs
-to be easily associated with <code><em>public-identifiers</em></code>.
-</p>
-<p>For example:</p>
-<code><pre>
- digester.register("-//Example Dot Com //DTD Sample Example//EN", "assets/sample.dtd");
-</pre></code>
-<p>
-will make digester return the relative file path <code>assets/sample.dtd</code>
-whenever an external entity with public id
-<code>-//Example Dot Com //DTD Sample Example//EN</code> is needed.
-</p>
-<p><strong>Note:</strong> This is a simple (but useful) implementation.
-Greater sophistication requires a custom <code>EntityResolver</code>.</p>
-
-<a name="doc.troubleshooting"></a>
-<h3>Troubleshooting</h3>
-<h4>Debugging Exceptions</h4>
-<p>
-<code>Digester</code> is based on <a href='http://www.saxproject.org'>SAX</a>.
-Digestion throws two kinds of <code>Exception</code>:
-</p>
-<ul>
- <li><code>java.io.IOException</code></li>
- <li><code>org.xml.sax.SAXException</code></li>
-</ul>
-<p>
-The first is rarely thrown and indicates the kind of fundemental IO exception
-that developers know all about. The second is thrown by SAX parsers when the processing
-of the XML cannot be completed. So, to diagnose the cause a certain familiarity with
-the way that SAX error handling works is very useful.
-</p>
-<h5>Diagnosing SAX Exceptions</h5>
-<p>
-This is a short, potted guide to SAX error handling strategies. It's not intended as a
-proper guide to error handling in SAX.
-</p>
-<p>
-When a SAX parser encounters a problem with the xml (well, ok - sometime after it
-encounters a problem) it will throw a
-<a href='http://www.saxproject.org/apidoc/org/xml/sax/SAXParseException.html'>
-SAXParseException</a>. This is a subclass of <code>SAXException</code> and contains
-a bit of extra information about what exactly when wrong - and more importantly,
-where it went wrong. If you catch an exception of this sort, you can be sure that
-the problem is with the XML and not <code>Digester</code> or your rules.
-It is usually a good idea to catch this exception and log the extra information
-to help with diagnosing the reason for the failure.
-</p>
-<p>
-General <a href='http://www.saxproject.org/apidoc/org/xml/sax/SAXException.html'>
-SAXException</a> instances may wrap a causal exception. When exceptions are
-throw by <code>Digester</code> each of these will be wrapped into a
-<code>SAXException</code> and rethrown. So, catch these and examine the wrapped
-exception to diagnose what went wrong.
-</p>
-<a name="doc.FAQ"></a>
-<h3>Frequently Asked Questions</h3>
-<p><ul>
-<li><strong>Why do I get warnings when using a JAXP 1.1 parser?</strong>
-<p>If you're using a JAXP 1.1 parser, you might see the following warning (in your log):
-<code><pre>
-[WARN] Digester - -Error: JAXP SAXParser property not recognized: http://java.sun.com/xml/jaxp/properties/schemaLanguage
-</pre></code>
-This property is needed for JAXP 1.2 (XML Schema support) as required
-for the Servlet Spec. 2.4 but is not recognized by JAXP 1.1 parsers.
-This warning is harmless.</p>
-<p>
-</li>
-<li><strong>Why Doesn't Schema Validation Work With Parser XXX Out Of The Box?</strong>
-<p>
-Schema location and language settings are often need for validation using schemas.
-Unfortunately, there isn't a single standard approach to how these properties are
-configured on a parser.
-Digester tries to guess the parser being used and configure it appropriately
-but it's not infallible.
-You might need to grab an instance, configure it and pass it to Digester.
-</p>
-<p>
-If you want to support more than one parser in a portable manner,
-then you'll probably want to take a look at the
-<code>org.apache.commons.digester.parsers</code> package
-and add a new class to support the particular parser that's causing problems.
-</p>
-</li>
-<li><strong>Help!
-I'm Validating Against Schema But Digester Ignores Errors!</strong>
-<p>
-Digester is based on <a href='http://www.saxproject.org'>SAX</a>. The convention for
-SAX parsers is that all errors are reported (to any registered
-<code>ErrorHandler</code>) but processing continues. Digester (by default)
-registers its own <code>ErrorHandler</code> implementation. This logs details
-but does not stop the processing (following the usual convention for SAX
-based processors).
-</p>
-<p>
-This means that the errors reported by the validation of the schema will appear in the
-Digester logs but the processing will continue. To change this behaviour, call
-<code>digester.setErrorHandler</code> with a more suitable implementation.
-</p>
-
-<li><strong>Where Can I Find Example Code?</strong>
-<a name="doc.FAQ.Examples">
-<p>Digester ships with a sample application: a mapping for the <em>Rich Site
-Summary</em> format used by many newsfeeds. Download the source distribution
-to see how it works.</p>
-<p>Digester also ships with a set of examples demonstrating most of the
-features described in this document. See the "src/examples" subdirectory
-of the source distribution.</p>
-</li>
-<li><strong>When Are You Going To Support <em>Rich Site Summary</em> Version x.y.z?</strong>
-<p>
-The <em>Rich Site Summary</em> application is intended to be a sample application.
-It works but we have no plans to add support for other versions of the format.
-</p>
-<p>
-We would consider donations of standard digester applications but it's unlikely that
-these would ever be shipped with the base digester distribution.
-If you want to discuss this, please post to <a href='http://jakarta.apache.org/site/mail.html'>
-common-dev mailing list</a>
-</p>
-</li>
-</ul>
-<a name="doc.Limits"></a>
-<h3>Known Limitations</h3>
-<h4>Accessing Public Methods In A Default Access Superclass</h4>
-<p>There is an issue when invoking public methods contained in a default access superclass.
-Reflection locates these methods fine and correctly assigns them as public.
-However, an <code>IllegalAccessException</code> is thrown if the method is invoked.</p>
-
-<p><code>MethodUtils</code> contains a workaround for this situation.
-It will attempt to call <code>setAccessible</code> on this method.
-If this call succeeds, then the method can be invoked as normal.
-This call will only succeed when the application has sufficient security privilages.
-If this call fails then a warning will be logged and the method may fail.</p>
-
-<p><code>Digester</code> uses <code>MethodUtils</code> and so there may be an issue accessing methods
-of this kind from a high security environment. If you think that you might be experiencing this
-problem, please ask on the mailing list.</p>
-</body>
-</html>
Modified: trunk/java/org/apache/tomcat/util/modeler/Registry.java
===================================================================
--- trunk/java/org/apache/tomcat/util/modeler/Registry.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/modeler/Registry.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -747,7 +747,7 @@
}
if( sourceType==null ) {
- sourceType="MbeansDescriptorsDigesterSource";
+ sourceType="MbeansDescriptorsDOMSource";
}
ModelerSource ds=getModelerSource(sourceType);
List mbeans=ds.loadDescriptors(this, location, type, inputsource);
@@ -760,7 +760,7 @@
return "MbeansDescriptorsSerSource";
}
else if( s.endsWith(".xml")) {
- return "MbeansDescriptorsDigesterSource";
+ return "MbeansDescriptorsDOMSource";
}
return null;
}
@@ -842,7 +842,7 @@
searchedPaths.put( packageName, dURL );
try {
if( descriptors.endsWith(".xml" ))
- loadDescriptors("MbeansDescriptorsDigesterSource", dURL, null);
+ loadDescriptors("MbeansDescriptorsDOMSource", dURL, null);
else
loadDescriptors("MbeansDescriptorsSerSource", dURL, null);
return;
@@ -914,7 +914,7 @@
private ModelerSource getModelerSource( String type )
throws Exception
{
- if( type==null ) type="MbeansDescriptorsDigesterSource";
+ if( type==null ) type="MbeansDescriptorsDOMSource";
if( type.indexOf( ".") < 0 ) {
type="org.apache.tomcat.util.modeler.modules." + type;
}
@@ -988,7 +988,7 @@
public void loadDescriptors( Object source )
throws Exception
{
- loadDescriptors("MbeansDescriptorsDigesterSource", source, null );
+ loadDescriptors("MbeansDescriptorsDOMSource", source, null );
}
/** @deprecated - may still be used in code using pre-1.1 builds
Deleted: trunk/java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java
===================================================================
--- trunk/java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/apache/tomcat/util/modeler/modules/MbeansDescriptorsDigesterSource.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,243 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.tomcat.util.modeler.modules;
-
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.tomcat.util.digester.Digester;
-import org.apache.tomcat.util.modeler.Registry;
-import org.jboss.logging.Logger;
-import org.jboss.logging.Logger;
-
-public class MbeansDescriptorsDigesterSource extends ModelerSource
-{
- private static Logger log =
- Logger.getLogger(MbeansDescriptorsDigesterSource.class);
-
- Registry registry;
- String location;
- String type;
- Object source;
- List mbeans=new ArrayList();
- protected static Digester digester = null;
-
- protected static Digester createDigester(Registry registry) {
-
- Digester digester = new Digester();
- digester.setNamespaceAware(false);
- digester.setValidating(false);
- URL url = Registry.getRegistry(null, null).getClass().getResource
- ("/org/apache/tomcat/util/modeler/mbeans-descriptors.dtd");
- digester.register
- ("-//Apache Software Foundation//DTD Model MBeans Configuration File",
- url.toString());
-
- // Configure the parsing rules
- digester.addObjectCreate
- ("mbeans-descriptors/mbean",
- "org.apache.tomcat.util.modeler.ManagedBean");
- digester.addSetProperties
- ("mbeans-descriptors/mbean");
- digester.addSetNext
- ("mbeans-descriptors/mbean",
- "add",
- "java.lang.Object");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/attribute",
- "org.apache.tomcat.util.modeler.AttributeInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/attribute");
- digester.addSetNext
- ("mbeans-descriptors/mbean/attribute",
- "addAttribute",
- "org.apache.tomcat.util.modeler.AttributeInfo");
-
- /*digester.addObjectCreate
- ("mbeans-descriptors/mbean/attribute/descriptor/field",
- "org.apache.tomcat.util.modeler.FieldInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/attribute/descriptor/field");
- digester.addSetNext
- ("mbeans-descriptors/mbean/attribute/descriptor/field",
- "addField",
- "org.apache.tomcat.util.modeler.FieldInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/constructor",
- "org.apache.tomcat.util.modeler.ConstructorInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/constructor");
- digester.addSetNext
- ("mbeans-descriptors/mbean/constructor",
- "addConstructor",
- "org.apache.tomcat.util.modeler.ConstructorInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/constructor/descriptor/field",
- "org.apache.tomcat.util.modeler.FieldInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/constructor/descriptor/field");
- digester.addSetNext
- ("mbeans-descriptors/mbean/constructor/descriptor/field",
- "addField",
- "org.apache.tomcat.util.modeler.FieldInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/constructor/parameter",
- "org.apache.tomcat.util.modeler.ParameterInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/constructor/parameter");
- digester.addSetNext
- ("mbeans-descriptors/mbean/constructor/parameter",
- "addParameter",
- "org.apache.tomcat.util.modeler.ParameterInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/descriptor/field",
- "org.apache.tomcat.util.modeler.FieldInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/descriptor/field");
- digester.addSetNext
- ("mbeans-descriptors/mbean/descriptor/field",
- "addField",
- "org.apache.tomcat.util.modeler.FieldInfo");
- */
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/notification",
- "org.apache.tomcat.util.modeler.NotificationInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/notification");
- digester.addSetNext
- ("mbeans-descriptors/mbean/notification",
- "addNotification",
- "org.apache.tomcat.util.modeler.NotificationInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/notification/descriptor/field",
- "org.apache.tomcat.util.modeler.FieldInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/notification/descriptor/field");
- digester.addSetNext
- ("mbeans-descriptors/mbean/notification/descriptor/field",
- "addField",
- "org.apache.tomcat.util.modeler.FieldInfo");
-
- digester.addCallMethod
- ("mbeans-descriptors/mbean/notification/notification-type",
- "addNotifType", 0);
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/operation",
- "org.apache.tomcat.util.modeler.OperationInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/operation");
- digester.addSetNext
- ("mbeans-descriptors/mbean/operation",
- "addOperation",
- "org.apache.tomcat.util.modeler.OperationInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/operation/descriptor/field",
- "org.apache.tomcat.util.modeler.FieldInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/operation/descriptor/field");
- digester.addSetNext
- ("mbeans-descriptors/mbean/operation/descriptor/field",
- "addField",
- "org.apache.tomcat.util.modeler.FieldInfo");
-
- digester.addObjectCreate
- ("mbeans-descriptors/mbean/operation/parameter",
- "org.apache.tomcat.util.modeler.ParameterInfo");
- digester.addSetProperties
- ("mbeans-descriptors/mbean/operation/parameter");
- digester.addSetNext
- ("mbeans-descriptors/mbean/operation/parameter",
- "addParameter",
- "org.apache.tomcat.util.modeler.ParameterInfo");
-
- return digester;
-
- }
-
- public void setRegistry(Registry reg) {
- this.registry=reg;
- }
-
- public void setLocation( String loc ) {
- this.location=loc;
- }
-
- /** Used if a single component is loaded
- *
- * @param type
- */
- public void setType( String type ) {
- this.type=type;
- }
-
- public void setSource( Object source ) {
- this.source=source;
- }
-
- public List loadDescriptors( Registry registry, String location,
- String type, Object source)
- throws Exception
- {
- setRegistry(registry);
- setLocation(location);
- setType(type);
- setSource(source);
- execute();
- return mbeans;
- }
-
- public void execute() throws Exception {
- if (registry == null) {
- registry = Registry.getRegistry(null, null);
- }
-
- InputStream stream = (InputStream) source;
-
- if (digester == null) {
- digester = createDigester(registry);
- }
-
- synchronized (digester) {
-
- // Process the input file to configure our registry
- try {
- // Push our registry object onto the stack
- digester.push(mbeans);
- digester.parse(stream);
- } catch (Exception e) {
- log.error("Error digesting Registry data", e);
- throw e;
- } finally {
- digester.reset();
- }
-
- }
-
- }
-}
Deleted: trunk/java/org/jboss/web/cluster/ClusterListener.java
===================================================================
--- trunk/java/org/jboss/web/cluster/ClusterListener.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/ClusterListener.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,1567 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-
-package org.jboss.web.cluster;
-
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.StringTokenizer;
-
-import javax.management.ObjectName;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.ContainerEvent;
-import org.apache.catalina.ContainerListener;
-import org.apache.catalina.Context;
-import org.apache.catalina.Engine;
-import org.apache.catalina.Host;
-import org.apache.catalina.Lifecycle;
-import org.apache.catalina.LifecycleEvent;
-import org.apache.catalina.LifecycleListener;
-import org.apache.catalina.Server;
-import org.apache.catalina.Service;
-import org.apache.catalina.connector.Connector;
-import org.apache.catalina.core.StandardContext;
-import org.apache.catalina.core.StandardServer;
-import org.apache.catalina.util.StringManager;
-import org.apache.tomcat.util.IntrospectionUtils;
-import org.apache.tomcat.util.buf.CharChunk;
-import org.apache.tomcat.util.buf.UEncoder;
-import org.apache.tomcat.util.modeler.Registry;
-import org.jboss.logging.Logger;
-import org.jboss.web.cluster.advertise.AdvertiseListener;
-
-
-
-/**
- * This listener communicates with a front end mod_cluster enabled proxy to
- * automatically maintain the node configuration according to what is
- * deployed.
- */
-public class ClusterListener
- implements LifecycleListener, ContainerListener {
-
- protected static Logger log = Logger.getLogger(ClusterListener.class);
-
- /**
- * The string manager for this package.
- */
- protected StringManager sm =
- StringManager.getManager(Constants.Package);
-
-
- // -------------------------------------------------------------- Constants
-
-
- protected enum State { OK, ERROR, DOWN };
-
-
- // ----------------------------------------------------------------- Fields
-
-
- /**
- * Associated server.
- */
- protected Server server = null;
-
-
- /**
- * URL encoder used to generate requests bodies.
- */
- protected UEncoder encoder = new UEncoder();
-
-
- /**
- * JMX registration information.
- */
- protected ObjectName oname;
-
-
- /**
- * Proxies.
- */
- protected Proxy[] proxies = new Proxy[0];
-
-
- /**
- * Socket factory.
- */
- protected JSSESocketFactory sslSocketFactory = null;
-
-
- /**
- * Active connections.
- */
- protected Socket[] connections = null;
-
-
- /**
- * Connection readers.
- */
- protected BufferedReader[] connectionReaders = null;
-
-
- /**
- * Connection writers.
- */
- protected BufferedWriter[] connectionWriters = null;
-
-
- /**
- * Initialization flag.
- */
- protected boolean init = false;
-
-
- /**
- * Add proxy list.
- */
- protected ArrayList<Proxy> addProxies = new ArrayList<Proxy>();
-
-
- /**
- * Remove proxy list.
- */
- protected ArrayList<Proxy> removeProxies = new ArrayList<Proxy>();
-
-
- /**
- * Advertise listener.
- */
- protected AdvertiseListener listener = null;
-
-
- // ------------------------------------------------------------- Properties
-
-
- /**
- * Receive advertisements from httpd proxies (default is to use advertisements
- * if the proxyList is not set).
- */
- protected int advertise = -1;
- public boolean getAdvertise() { return (advertise == 0) ? false : true; }
- public void setAdvertise(boolean advertise) { this.advertise = advertise ? 1 : 0; }
-
-
- /**
- * Advertise group.
- */
- protected String advertiseGroupAddress = null;
- public String getAdvertiseGroupAddress() { return advertiseGroupAddress; }
- public void setAdvertiseGroupAddress(String advertiseGroupAddress) { this.advertiseGroupAddress = advertiseGroupAddress; }
-
-
- /**
- * Advertise port.
- */
- protected int advertisePort = -1;
- public int getAdvertisePort() { return advertisePort; }
- public void setAdvertisePort(int advertisePort) { this.advertisePort = advertisePort; }
-
-
- /**
- * Advertise security key.
- */
- protected String advertiseSecurityKey = null;
- public String getAdvertiseSecurityKey() { return advertiseSecurityKey; }
- public void setAdvertiseSecurityKey(String advertiseSecurityKey) { this.advertiseSecurityKey = advertiseSecurityKey; }
-
-
- /**
- * Proxy list, format "address:port,address:port".
- */
- protected String proxyList = null;
- public String getProxyList() { return proxyList; }
- public void setProxyList(String proxyList) { this.proxyList = proxyList; }
-
-
- /**
- * URL prefix.
- */
- protected String proxyURL = null;
- public String getProxyURL() { return proxyURL; }
- public void setProxyURL(String proxyURL) { this.proxyURL = proxyURL; }
-
-
- /**
- * Connection timeout for communication with the proxy.
- */
- protected int socketTimeout = 20000;
- public int getSocketTimeout() { return socketTimeout; }
- public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; }
-
-
- /**
- * Domain parameter, which allows tying a jvmRoute to a particular domain.
- */
- protected String domain = null;
- public String getDomain() { return domain; }
- public void setDomain(String domain) { this.domain = domain; }
-
-
- /**
- * Allows controlling flushing of packets.
- */
- protected boolean flushPackets = false;
- public boolean getFlushPackets() { return flushPackets; }
- public void setFlushPackets(boolean flushPackets) { this.flushPackets = flushPackets; }
-
-
- /**
- * Time to wait before flushing packets.
- */
- protected int flushWait = -1;
- public int getFlushWait() { return flushWait; }
- public void setFlushWait(int flushWait) { this.flushWait = flushWait; }
-
-
- /**
- * Time to wait for a pong answer to a ping.
- */
- protected int ping = -1;
- public int getPing() { return ping; }
- public void setPing(int ping) { this.ping = ping; }
-
-
- /**
- * Soft maximum inactive connection count.
- */
- protected int smax = -1;
- public int getSmax() { return smax; }
- public void setSmax(int smax) { this.smax = smax; }
-
-
- /**
- * Maximum time on seconds for idle connections above smax.
- */
- protected int ttl = -1;
- public int getTtl() { return ttl; }
- public void setTtl(int ttl) { this.ttl = ttl; }
-
-
- /**
- * Maximum time on seconds for idle connections the proxy will wait to connect to the node.
- */
- protected int nodeTimeout = -1;
- public int getNodeTimeout() { return nodeTimeout; }
- public void setNodeTimeout(int nodeTimeout) { this.nodeTimeout = nodeTimeout; }
-
-
- /**
- * Name of the balancer.
- */
- protected String balancer = null;
- public String getBalancer() { return balancer; }
- public void setBalancer(String balancer) { this.balancer = balancer; }
-
-
- /**
- * Enables sticky sessions.
- */
- protected boolean stickySession = true;
- public boolean getStickySession() { return stickySession; }
- public void setStickySession(boolean stickySession) { this.stickySession = stickySession; }
-
-
- /**
- * Remove session when the request cannot be routed to the right node.
- */
- protected boolean stickySessionRemove = false;
- public boolean getStickySessionRemove() { return stickySessionRemove; }
- public void setStickySessionRemove(boolean stickySessionRemove) { this.stickySessionRemove = stickySessionRemove; }
-
-
- /**
- * Return an error when the request cannot be routed to the right node.
- */
- protected boolean stickySessionForce = true;
- public boolean getStickySessionForce() { return stickySessionForce; }
- public void setStickySessionForce(boolean stickySessionForce) { this.stickySessionForce = stickySessionForce; }
-
-
- /**
- * Timeout to wait for an available worker (default is no wait).
- */
- protected int workerTimeout = -1;
- public int getWorkerTimeout() { return workerTimeout; }
- public void setWorkerTimeout(int workerTimeout) { this.workerTimeout = workerTimeout; }
-
-
- /**
- * Maximum number of attempts to send the request to the backend server.
- */
- protected int maxAttempts = -1;
- public int getMaxAttempts() { return maxAttempts; }
- public void setMaxAttempts(int maxAttempts) { this.maxAttempts = maxAttempts; }
-
-
- /**
- * SSL client cert usage to connect to the proxy.
- */
- protected boolean ssl = false;
- public boolean isSsl() { return ssl; }
- public void setSsl(boolean ssl) { this.ssl = ssl; }
-
-
- /**
- * SSL ciphers.
- */
- protected String sslCiphers = null;
- public String getSslCiphers() { return sslCiphers; }
- public void setSslCiphers(String sslCiphers) { this.sslCiphers = sslCiphers; }
-
-
- /**
- * SSL protocol.
- */
- protected String sslProtocol = "TLS";
- public String getSslProtocol() { return sslProtocol; }
- public void setSslProtocol(String sslProtocol) { this.sslProtocol = sslProtocol; }
-
-
- /**
- * Certificate encoding algorithm.
- */
- protected String sslCertificateEncodingAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
- public String getSslCertificateEncodingAlgorithm() { return sslCertificateEncodingAlgorithm; }
- public void setSslCertificateEncodingAlgorithm(String sslCertificateEncodingAlgorithm) { this.sslCertificateEncodingAlgorithm = sslCertificateEncodingAlgorithm; }
-
-
- /**
- * SSL keystore.
- */
- protected String sslKeyStore = System.getProperty("user.home") + "/.keystore";
- public String getSslKeyStore() { return sslKeyStore; }
- public void setSslKeyStore(String sslKeyStore) { this.sslKeyStore = sslKeyStore; }
-
-
- /**
- * SSL keystore password.
- */
- protected String sslKeyStorePass = "changeit";
- public String getSslKeyStorePass() { return sslKeyStorePass; }
- public void setSslKeyStorePass(String sslKeyStorePass) { this.sslKeyStorePass = sslKeyStorePass; }
-
-
- /**
- * Keystore type.
- */
- protected String sslKeyStoreType = "JKS";
- public String getSslKeyStoreType() { return sslKeyStoreType; }
- public void setSslKeyStoreType(String sslKeyStoreType) { this.sslKeyStoreType = sslKeyStoreType; }
-
-
- /**
- * Keystore provider.
- */
- protected String sslKeyStoreProvider = null;
- public String getSslKeyStoreProvider() { return sslKeyStoreProvider; }
- public void setSslKeyStoreProvider(String sslKeyStoreProvider) { this.sslKeyStoreProvider = sslKeyStoreProvider; }
-
-
- /**
- * Truststore algorithm.
- */
- protected String sslTrustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
- public String getSslTrustAlgorithm() { return sslTrustAlgorithm; }
- public void setSslTrustAlgorithm(String sslTrustAlgorithm) { this.sslTrustAlgorithm = sslTrustAlgorithm; }
-
-
- /**
- * Key alias.
- */
- protected String sslKeyAlias = null;
- public String getSslKeyAlias() { return sslKeyAlias; }
- public void setSslKeyAlias(String sslKeyAlias) { this.sslKeyAlias = sslKeyAlias; }
-
-
- /**
- * Certificate revocation list.
- */
- protected String sslCrlFile = null;
- public String getSslCrlFile() { return sslCrlFile; }
- public void setSslCrlFile(String sslCrlFile) { this.sslCrlFile = sslCrlFile; }
-
-
- /**
- * Trust max certificate length.
- */
- protected int sslTrustMaxCertLength = 5;
- public int getSslTrustMaxCertLength() { return sslTrustMaxCertLength; }
- public void setSslTrustMaxCertLength(int sslTrustMaxCertLength) { this.sslTrustMaxCertLength = sslTrustMaxCertLength; }
-
-
- /**
- * Trust store file.
- */
- protected String sslTrustStore = System.getProperty("javax.net.ssl.trustStore");
- public String getSslTrustStore() { return sslTrustStore; }
- public void setSslTrustStore(String sslTrustStore) { this.sslTrustStore = sslTrustStore; }
-
-
- /**
- * Trust store password.
- */
- protected String sslTrustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
- public String getSslTrustStorePassword() { return sslTrustStorePassword; }
- public void setSslTrustStorePassword(String sslTrustStorePassword) { this.sslTrustStorePassword = sslTrustStorePassword; }
-
-
- /**
- * Trust store type.
- */
- protected String sslTrustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
- public String getSslTrustStoreType() { return sslTrustStoreType; }
- public void setSslTrustStoreType(String sslTrustStoreType) { this.sslTrustStoreType = sslTrustStoreType; }
-
-
- /**
- * Trust store provider.
- */
- protected String sslTrustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider");
- public String getSslTrustStoreProvider() { return sslTrustStoreProvider; }
- public void setSslTrustStoreProvider(String sslTrustStoreProvider) { this.sslTrustStoreProvider = sslTrustStoreProvider; }
-
-
- // ---------------------------------------------- LifecycleListener Methods
-
-
- /**
- * Acknowledge the occurrence of the specified event.
- * Note: Will never be called when the listener is associated to a Server,
- * since it is not a Container.
- *
- * @param event ContainerEvent that has occurred
- */
- public void containerEvent(ContainerEvent event) {
-
- Container container = event.getContainer();
- Object child = event.getData();
- String type = event.getType();
-
- if (type.equals(Container.ADD_CHILD_EVENT)) {
- if (container instanceof Host) {
- // Deploying a webapp
- ((Lifecycle) child).addLifecycleListener(this);
- addContext((Context) child, -1);
- } else if (container instanceof Engine) {
- // Deploying a host
- container.addContainerListener(this);
- }
- } else if (type.equals(Container.REMOVE_CHILD_EVENT)) {
- if (container instanceof Host) {
- // Undeploying a webapp
- ((Lifecycle) child).removeLifecycleListener(this);
- removeContext((Context) child, -1);
- } else if (container instanceof Engine) {
- // Undeploying a host
- container.removeContainerListener(this);
- }
- }
-
- }
-
-
- /**
- * Primary entry point for startup and shutdown events.
- *
- * @param event The event that has occurred
- */
- public void lifecycleEvent(LifecycleEvent event) {
-
- Object source = event.getLifecycle();
-
- if (Lifecycle.START_EVENT.equals(event.getType())) {
- if (source instanceof Context) {
- // Start a webapp
- startContext((Context) source, -1);
- } else {
- return;
- }
- } else if (Lifecycle.AFTER_START_EVENT.equals(event.getType())) {
- if (source instanceof Server) {
- server = (Server) source;
- if (this.proxyList == null) {
- if (advertise != 0) {
- proxies = new Proxy[0];
- startListener();
- } else {
- // Default to a httpd on localhost on the default port
- proxies = new Proxy[1];
- proxies[0] = new Proxy();
- }
- } else {
- ArrayList<Proxy> proxyList = new ArrayList<Proxy>();
- StringTokenizer tok = new StringTokenizer(this.proxyList, ",");
- while (tok.hasMoreTokens()) {
- String token = tok.nextToken().trim();
- Proxy proxy = new Proxy();
- int pos = token.indexOf(':');
- String address = null;
- if (pos < 0) {
- address = token;
- } else if (pos == 0) {
- address = null;
- proxy.port = Integer.parseInt(token.substring(1));
- } else {
- address = token.substring(0, pos);
- proxy.port = Integer.parseInt(token.substring(pos + 1));
- }
- try {
- if (address != null) {
- proxy.address = InetAddress.getByName(address);
- }
- } catch (Exception e) {
- log.error(sm.getString("clusterListener.error.invalidHost", address), e);
- continue;
- }
- proxyList.add(proxy);
- }
- proxies = proxyList.toArray(new Proxy[0]);
- }
-
- connections = new Socket[proxies.length];
- connectionReaders = new BufferedReader[proxies.length];
- connectionWriters = new BufferedWriter[proxies.length];
-
- sslInit();
- startServer((Server) source, -1);
-
- if (advertise == 1) {
- startListener();
- }
-
- init = true;
- } else {
- return;
- }
- } else if (Lifecycle.STOP_EVENT.equals(event.getType())) {
- if (source instanceof Context) {
- // Stop a webapp
- stopContext((Context) source, -1);
- } else if (source instanceof Server) {
- stopListener();
- stopServer((Server) source, -1);
- for (int i = 0; i < connections.length; i++) {
- closeConnection(i);
- }
- init = false;
- } else {
- return;
- }
- } else if (Lifecycle.PERIODIC_EVENT.equals(event.getType())) {
- if (init && source instanceof Engine) {
- status((Engine) source);
- }
- }
-
- }
-
-
- /**
- * Add proxy.
- */
- public void addProxy(String address) {
- int pos = address.indexOf(':');
- String host = null;
- int port = 0;
- if (pos < 0) {
- host = address;
- } else if (pos == 0) {
- host = null;
- port = Integer.parseInt(address.substring(1));
- } else {
- host = address.substring(0, pos);
- port = Integer.parseInt(address.substring(pos + 1));
- }
- addProxy(host, port);
- }
-
-
- /**
- * Add proxy.
- */
- public synchronized void addProxy(String host, int port) {
- Proxy proxy = new Proxy();
- try {
- proxy.address = InetAddress.getByName(host);
- } catch (Exception e) {
- throw new IllegalArgumentException(e);
- }
- if (port > 0) {
- proxy.port = port;
- }
- proxy.state = State.ERROR;
- addProxies.add(proxy);
- }
-
-
- /**
- * Remove proxy.
- */
- public synchronized void removeProxy(String host, int port) {
- Proxy proxy = new Proxy();
- try {
- proxy.address = InetAddress.getByName(host);
- } catch (Exception e) {
- throw new IllegalArgumentException(e);
- }
- if (port > 0) {
- proxy.port = port;
- }
- removeProxies.add(proxy);
- }
-
-
- /**
- * Retrieves the full proxy configuration. To be used through JMX or similar.
- *
- * response: HTTP/1.1 200 OK
- * response:
- * node: [1:1] JVMRoute: node1 Domain: [bla] Host: 127.0.0.1 Port: 8009 Type: ajp
- * host: 1 [] vhost: 1 node: 1
- * context: 1 [/] vhost: 1 node: 1 status: 1
- * context: 2 [/myapp] vhost: 1 node: 1 status: 1
- * context: 3 [/host-manager] vhost: 1 node: 1 status: 1
- * context: 4 [/docs] vhost: 1 node: 1 status: 1
- * context: 5 [/manager] vhost: 1 node: 1 status: 1
- *
- * @return the proxy confguration
- */
- public String getProxyConfiguration() {
- HashMap<String, String> parameters = new HashMap<String, String>();
- // Send DUMP * request
- Proxy[] local = proxies;
- StringBuffer result = new StringBuffer();
- for (int i = 0; i < local.length; i++) {
- result.append("Proxy[").append(i).append("]: [").append(local[i].address)
- .append(':').append(local[i].port).append("]: \r\n");
- result.append(sendRequest("DUMP", true, parameters, i));
- result.append("\r\n");
- }
- return result.toString();
- }
- /**
- * Retrieves the full proxy info message.
- *
- *
- * @return the proxy confguration
- */
- public String getProxyInfo() {
- HashMap<String, String> parameters = new HashMap<String, String>();
- // Send INFO * request
- Proxy[] local = proxies;
- StringBuffer result = new StringBuffer();
- for (int i = 0; i < local.length; i++) {
- result.append("Proxy[").append(i).append("]: [").append(local[i].address)
- .append(':').append(local[i].port).append("]: \r\n");
- result.append(sendRequest("INFO", true, parameters, i));
- result.append("\r\n");
- }
- return result.toString();
- }
-
-
- /**
- * Reset a DOWN connection to the proxy up to ERROR, where the configuration will
- * be refreshed. To be used through JMX or similar.
- */
- public void reset() {
- Proxy[] local = proxies;
- for (int i = 0; i < local.length; i++) {
- if (local[i].state == State.DOWN) {
- local[i].state = State.ERROR;
- }
- }
- }
-
-
- /**
- * Refresh configuration. To be used through JMX or similar.
- */
- public void refresh() {
- // Set as error, and the periodic event will refresh the configuration
- Proxy[] local = proxies;
- for (int i = 0; i < local.length; i++) {
- if (local[i].state == State.OK) {
- local[i].state = State.ERROR;
- }
- }
- }
-
-
- /**
- * Disable all webapps for all engines. To be used through JMX or similar.
- */
- public boolean disable() {
- Service[] services = server.findServices();
- for (int i = 0; i < services.length; i++) {
- Engine engine = (Engine) services[i].getContainer();
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", engine.getJvmRoute());
- // Send DISABLE-APP * request
- sendRequest("DISABLE-APP", true, parameters);
- }
- return (proxies[0].state == State.OK);
- }
-
-
- /**
- * Enable all webapps for all engines. To be used through JMX or similar.
- */
- public boolean enable() {
- Service[] services = server.findServices();
- for (int i = 0; i < services.length; i++) {
- Engine engine = (Engine) services[i].getContainer();
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", engine.getJvmRoute());
- // Send ENABLE-APP * request
- sendRequest("ENABLE-APP", true, parameters);
- }
- return (proxies[0].state == State.OK);
- }
-
-
- /**
- * Start the advertise listener.
- */
- protected void startListener() {
- listener = new AdvertiseListener(this);
- if (advertiseGroupAddress != null) {
- listener.setGroupAddress(advertiseGroupAddress);
- }
- if (advertisePort > 0) {
- listener.setAdvertisePort(advertisePort);
- }
- try {
- if (advertiseSecurityKey != null) {
- listener.setSecurityKey(advertiseSecurityKey);
- }
- listener.start();
- } catch (IOException e) {
- log.error(sm.getString("clusterListener.error.startListener"), e);
- } catch (NoSuchAlgorithmException e) {
- // Should never happen
- log.error(sm.getString("clusterListener.error.startListener"), e);
- }
- }
-
-
- /**
- * Stop the advertise listener.
- */
- protected void stopListener() {
- if (listener != null) {
- try {
- listener.destroy();
- } catch (IOException e) {
- log.error(sm.getString("clusterListener.error.stopListener"), e);
- }
- listener = null;
- }
- }
-
-
- /**
- * Send commands to the front end server assocaited with the startup of the
- * node.
- */
- protected void startServer(Server server, int pos) {
-
- // JMX registration
- if (oname==null) {
- try {
- oname = new ObjectName(((StandardServer) server).getDomain() + ":type=ClusterListener");
- Registry.getRegistry(null, null).registerComponent(this, oname, null);
- } catch (Exception e) {
- log.error(sm.getString("clusterListener.error.jmxRegister"), e);
- }
- }
-
- Service[] services = server.findServices();
- for (int i = 0; i < services.length; i++) {
- services[i].getContainer().addContainerListener(this);
-
- Engine engine = (Engine) services[i].getContainer();
- ((Lifecycle) engine).addLifecycleListener(this);
- Connector connector = findProxyConnector(engine.getService().findConnectors());
- InetAddress localAddress =
- (InetAddress) IntrospectionUtils.getProperty(connector.getProtocolHandler(), "address");
- if ((engine.getJvmRoute() == null || localAddress == null) && proxies.length > 0) {
- // Automagical JVM route (address + port + engineName)
- try {
- if (localAddress == null) {
- Socket connection = getConnection(0);
- localAddress = connection.getLocalAddress();
- if (localAddress != null) {
- IntrospectionUtils.setProperty(connector.getProtocolHandler(), "address", localAddress.getHostAddress());
- log.info(sm.getString("clusterListener.address", localAddress.getHostAddress()));
- } else {
- // Should not happen
- IntrospectionUtils.setProperty(connector.getProtocolHandler(), "address", "127.0.0.1");
- log.info(sm.getString("clusterListener.address", "127.0.0.1"));
- }
- }
- if (engine.getJvmRoute() == null) {
- String hostName = null;
- if (localAddress != null) {
- hostName = localAddress.getHostName();
- } else {
- // Fallback
- hostName = "127.0.0.1";
- }
- String jvmRoute = hostName + ":" + connector.getPort() + ":" + engine.getName();
- engine.setJvmRoute(jvmRoute);
- log.info(sm.getString("clusterListener.jvmRoute", engine.getName(), jvmRoute));
- }
- } catch (Exception e) {
- proxies[0].state = State.ERROR;
- log.info(sm.getString("clusterListener.error.addressJvmRoute"), e);
- return;
- }
- }
-
- config(engine, pos);
- Container[] children = engine.findChildren();
- for (int j = 0; j < children.length; j++) {
- children[j].addContainerListener(this);
- Container[] children2 = children[j].findChildren();
- for (int k = 0; k < children2.length; k++) {
- ((Lifecycle) children2[k]).addLifecycleListener(this);
- addContext((Context) children2[k], pos);
- }
- }
- }
- }
-
-
- /**
- * Send commands to the front end server associated with the shutdown of the
- * node.
- */
- protected void stopServer(Server server, int pos) {
-
- // JMX unregistration
- if (oname==null) {
- try {
- Registry.getRegistry(null, null).unregisterComponent(oname);
- } catch (Exception e) {
- log.error(sm.getString("clusterListener.error.jmxUnregister"), e);
- }
- }
-
- Service[] services = server.findServices();
- for (int i = 0; i < services.length; i++) {
- services[i].getContainer().removeContainerListener(this);
- ((Lifecycle) services[i].getContainer()).removeLifecycleListener(this);
- removeAll((Engine) services[i].getContainer(), pos);
- Container[] children = services[i].getContainer().findChildren();
- for (int j = 0; j < children.length; j++) {
- children[j].removeContainerListener(this);
- Container[] children2 = children[j].findChildren();
- for (int k = 0; k < children2.length; k++) {
- ((Lifecycle) children2[k]).removeLifecycleListener(this);
- removeContext((Context) children2[k], pos);
- }
- }
- }
- }
-
-
- /**
- * Reset configuration for a particular proxy following an error.
- */
- protected void reset(int pos) {
-
- Service[] services = server.findServices();
- for (int i = 0; i < services.length; i++) {
- Engine engine = (Engine) services[i].getContainer();
- removeAll((Engine) services[i].getContainer(), pos);
- config(engine, pos);
- Container[] children = engine.findChildren();
- for (int j = 0; j < children.length; j++) {
- Container[] children2 = children[j].findChildren();
- for (int k = 0; k < children2.length; k++) {
- addContext((Context) children2[k], pos);
- }
- }
- }
-
- }
-
-
- /**
- * Send the configuration for the specified engine to the proxy.
- *
- * @param engine
- */
- protected void config(Engine engine, int pos) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.config", engine.getName()));
- }
- // Collect configuration from the connectors and service and call CONFIG
- Connector connector = findProxyConnector(engine.getService().findConnectors());
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", engine.getJvmRoute());
- boolean reverseConnection =
- Boolean.TRUE.equals(IntrospectionUtils.getProperty(connector.getProtocolHandler(), "reverseConnection"));
- boolean ssl =
- Boolean.TRUE.equals(IntrospectionUtils.getProperty(connector.getProtocolHandler(), "SSLEnabled"));
- boolean ajp = ((String) IntrospectionUtils.getProperty(connector.getProtocolHandler(), "name")).startsWith("ajp-");
-
- if (reverseConnection) {
- parameters.put("Reversed", "true");
- }
- parameters.put("Host", getAddress(connector));
- parameters.put("Port", "" + connector.getPort());
- if (ajp) {
- parameters.put("Type", "ajp");
- } else if (ssl) {
- parameters.put("Type", "https");
- } else {
- parameters.put("Type", "http");
- }
-
- // Other configuration parameters
- if (domain != null) {
- parameters.put("Domain", domain);
- }
- if (flushPackets) {
- parameters.put("flushpackets", "On");
- }
- if (flushWait != -1) {
- parameters.put("flushwait", "" + flushWait);
- }
- if (ping != -1) {
- parameters.put("ping", "" + ping);
- }
- if (smax != -1) {
- parameters.put("smax", "" + smax);
- }
- if (ttl != -1) {
- parameters.put("ttl", "" + ttl);
- }
- if (nodeTimeout != -1) {
- parameters.put("Timeout", "" + nodeTimeout);
- }
- if (balancer != null) {
- parameters.put("Balancer", balancer);
- }
- if (!stickySession) {
- parameters.put("StickySession", "No");
- }
- if (!org.apache.catalina.Globals.SESSION_COOKIE_NAME.equals("JSESSIONID")) {
- parameters.put("StickySessionCookie", org.apache.catalina.Globals.SESSION_COOKIE_NAME);
- }
- if (!org.apache.catalina.Globals.SESSION_PARAMETER_NAME.equals("jsessionid")) {
- parameters.put("StickySessionPath", org.apache.catalina.Globals.SESSION_PARAMETER_NAME);
- }
- if (stickySessionRemove) {
- parameters.put("StickSessionRemove", "Yes");
- }
- if (!stickySessionForce) {
- parameters.put("StickySessionForce", "No");
- }
- if (workerTimeout != -1) {
- parameters.put("WaitWorker", "" + workerTimeout);
- }
- if (maxAttempts != -1) {
- parameters.put("Maxattempts", "" + maxAttempts);
- }
-
- // Send CONFIG request
- sendRequest("CONFIG", false, parameters, pos);
- }
-
-
- /**
- * Remove all contexts from the specified engine.
- *
- * @param engine
- */
- protected void removeAll(Engine engine, int pos) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.stop", engine.getName()));
- }
-
- // JVMRoute can be null here if nothing was ever initialized
- if (engine.getJvmRoute() != null) {
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", engine.getJvmRoute());
-
- // Send REMOVE-APP * request
- sendRequest("REMOVE-APP", true, parameters, pos);
- }
- }
-
-
- /**
- * Send a periodic status request. If in error state, the listener will attempt to refresh
- * the configuration on the front end server.
- *
- * @param engine
- */
- protected synchronized void status(Engine engine) {
-
- // Check to add or remove proxies, and rebuild a new list if needed
- if (!addProxies.isEmpty() || !removeProxies.isEmpty()) {
- ArrayList<Proxy> currentProxies = new ArrayList<Proxy>();
- for (int i = 0; i < proxies.length; i++) {
- currentProxies.add(proxies[i]);
- }
- for (int i = 0; i < addProxies.size(); i++) {
- if (!currentProxies.contains(addProxies.get(i))) {
- currentProxies.add(addProxies.get(i));
- }
- }
- for (int i = 0; i < removeProxies.size(); i++) {
- if (currentProxies.contains(removeProxies.get(i))) {
- currentProxies.remove(removeProxies.get(i));
- }
- }
- addProxies.clear();
- removeProxies.clear();
- proxies = currentProxies.toArray(new Proxy[0]);
- // Reset all connections
- if (connections != null) {
- for (int i = 0; i < connections.length; i++) {
- closeConnection(i);
- }
- }
- connections = new Socket[proxies.length];
- connectionReaders = new BufferedReader[proxies.length];
- connectionWriters = new BufferedWriter[proxies.length];
- }
-
- Proxy[] local = proxies;
- for (int i = 0; i < local.length; i++) {
- if (local[i].state == State.ERROR) {
- local[i].state = State.OK;
- // Something went wrong in a status at some point, so fully restore the configuration
- reset(i);
- } else if (local[i].state == State.OK) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.status", engine.getName()));
- }
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", engine.getJvmRoute());
- parameters.put("Load", "1");
- // Send STATUS request
- sendRequest("STATUS", false, parameters, i);
- }
- }
- }
-
-
- /**
- * Add a new context.
- *
- * @param context
- */
- protected void addContext(Context context, int pos) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.context.enable", context.getPath(), context.getParent().getName(), ((StandardContext) context).getState()));
- }
-
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", getJvmRoute(context));
- parameters.put("Context", ("".equals(context.getPath())) ? "/" : context.getPath());
- parameters.put("Alias", getHost(context));
-
- // Send ENABLE-APP if state is started
- if (context.isStarted()) {
- sendRequest("ENABLE-APP", false, parameters, pos);
- }
- }
-
-
- /**
- * Remove a context.
- *
- * @param context
- */
- protected void removeContext(Context context, int pos) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.context.disable", context.getPath(), context.getParent().getName(), ((StandardContext) context).getState()));
- }
-
- HashMap<String, String> parameters = new HashMap<String, String>();
- String jvmRoute = getJvmRoute(context);
- // JVMRoute can be null here if nothing was ever initialized
- if (jvmRoute != null) {
- parameters.put("JVMRoute", jvmRoute);
- parameters.put("Context", ("".equals(context.getPath())) ? "/" : context.getPath());
- parameters.put("Alias", getHost(context));
-
- // Send REMOVE-APP
- sendRequest("REMOVE-APP", false, parameters, pos);
- }
- }
-
-
- /**
- * Start a context.
- *
- * @param context
- */
- protected void startContext(Context context, int pos) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.context.start", context.getPath(), context.getParent().getName()));
- }
-
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", getJvmRoute(context));
- parameters.put("Context", ("".equals(context.getPath())) ? "/" : context.getPath());
- parameters.put("Alias", getHost(context));
-
- // Send ENABLE-APP
- sendRequest("ENABLE-APP", false, parameters, pos);
- }
-
-
- /**
- * Stop a context.
- *
- * @param context
- */
- protected void stopContext(Context context, int pos) {
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.context.stop", context.getPath(), context.getParent().getName()));
- }
-
- HashMap<String, String> parameters = new HashMap<String, String>();
- parameters.put("JVMRoute", getJvmRoute(context));
- parameters.put("Context", ("".equals(context.getPath())) ? "/" : context.getPath());
- parameters.put("Alias", getHost(context));
-
- // Send STOP-APP
- sendRequest("STOP-APP", false, parameters, pos);
- }
-
-
- /**
- * Return the JvmRoute for the specified context.
- *
- * @param context
- * @return
- */
- protected String getJvmRoute(Context context) {
- return ((Engine) context.getParent().getParent()).getJvmRoute();
- }
-
-
- /**
- * Return the host and its alias list with which the context is associated.
- *
- * @param context
- * @return
- */
- protected String getHost(Context context) {
- StringBuffer result = new StringBuffer();
- Host host = (Host) context.getParent();
- result.append(host.getName());
- String[] aliases = host.findAliases();
- for (int i = 0; i < aliases.length; i++) {
- result.append(',');
- result.append(aliases[i]);
- }
- return result.toString();
- }
-
-
- /**
- * Find the most likely connector the proxy server should connect to, or
- * accept connections from.
- *
- * @param connectors
- * @return
- */
- protected Connector findProxyConnector(Connector[] connectors) {
- int pos = 0;
- int maxThreads = 0;
- for (int i = 0; i < connectors.length; i++) {
- if (connectors[i].getProtocol().startsWith("AJP")) {
- // Return any AJP connector found
- return connectors[i];
- }
- if (Boolean.TRUE.equals(IntrospectionUtils.getProperty(connectors[i].getProtocolHandler(), "reverseConnection"))) {
- return connectors[i];
- }
- Integer mt = (Integer) IntrospectionUtils.getProperty(connectors[i].getProtocolHandler(), "maxThreads");
- if (mt.intValue() > maxThreads) {
- maxThreads = mt.intValue();
- pos = i;
- }
- }
- // If no AJP connector and no reverse, return the connector with the most threads
- return connectors[pos];
- }
-
-
- /**
- * Return the address on which the connector is bound.
- *
- * @param connector
- * @return
- */
- protected String getAddress(Connector connector) {
- InetAddress inetAddress =
- (InetAddress) IntrospectionUtils.getProperty(connector.getProtocolHandler(), "address");
- if (inetAddress == null) {
- // Should not happen
- return "127.0.0.1";
- } else {
- return inetAddress.getHostAddress();
- }
- }
-
-
- /**
- * Send HTTP request, with the specified list of parameters. If an IO error occurs, the error state will
- * be set. If the front end server reports an error, will mark as error state. Other unexpected exceptions
- * will be thrown and the error state will be set.
- *
- * @param command
- * @param wildcard
- * @param parameters
- * @return the response body as a String; null if in error state or a normal error occurs
- */
- protected void sendRequest(String command, boolean wildcard, HashMap<String, String> parameters) {
- sendRequest(command, wildcard, parameters, -1);
- }
-
- protected synchronized String sendRequest(String command, boolean wildcard, HashMap<String, String> parameters, int pos) {
-
- BufferedReader reader = null;
- BufferedWriter writer = null;
- CharChunk body = null;
-
- // First, encode the POST body
- try {
- body = encoder.encodeURL("", 0, 0);
- body.recycle();
- Iterator<String> keys = parameters.keySet().iterator();
- while (keys.hasNext()) {
- String key = keys.next();
- String value = parameters.get(key);
- if (value == null) {
- throw new IllegalArgumentException(sm.getString("clusterListener.error.nullAttribute", key));
- }
- body = encoder.encodeURL(key, 0, key.length());
- body.append('=');
- if (value != null) {
- body = encoder.encodeURL(value, 0, value.length());
- }
- if (keys.hasNext()) {
- body.append('&');
- }
- }
- } catch (IOException e) {
- body.recycle();
- // Error encoding URL, should not happen
- throw new IllegalArgumentException(e);
- }
-
- int start = 0;
- int end = proxies.length;
- if (pos != -1) {
- start = pos;
- end = pos + 1;
- }
-
- for (int i = start; i < end; i++) {
-
- // If there was an error, do nothing until the next periodic event, where the whole configuration
- // will be refreshed
- if (proxies[i].state != State.OK) {
- continue;
- }
-
- if (log.isDebugEnabled()) {
- log.debug(sm.getString("clusterListener.request", command, wildcard, proxies[i]));
- }
-
- try {
-
- // Then, connect to the proxy
- getConnection(i);
- writer = getConnectionWriter(i);
- // Check connection to see if it is still alive (not really allowed,
- // but httpd deals with the extra CRLF)
- try {
- writer.write("\r\n");
- writer.flush();
- } catch (IOException e) {
- // Get a new connection; if it fails this second time, it is an error
- closeConnection(i);
- getConnection(i);
- writer = getConnectionWriter(i);
- }
-
- // Generate and write request
- String url = proxyURL;
- if (url == null) {
- url = (wildcard) ? "/*" : "/";
- } else {
- if (url.endsWith("/") && wildcard) {
- url = url + "*";
- } else if (wildcard) {
- url = url + "/*";
- }
- }
- String requestLine = command + " " + url + " HTTP/1.0";
- writer.write(requestLine);
- writer.write("\r\n");
- writer.write("Content-Length: " + body.getLength() + "\r\n");
- writer.write("User-Agent: ClusterListener/1.0\r\n");
- writer.write("Connection: Keep-Alive\r\n");
- writer.write("\r\n");
- writer.write(body.getBuffer(), body.getStart(), body.getLength());
- writer.write("\r\n");
- writer.flush();
-
- // Read the response to a string
- reader = getConnectionReader(i);
- // Read the first response line and skip the rest of the HTTP header
- String responseStatus = reader.readLine();
- // Parse the line, which is formed like HTTP/1.x YYY Message
- int status = 500;
- String version = "0";
- String message = null;
- String errorType = null;
- int contentLength = 0;
- if (responseStatus != null) {
- try {
- responseStatus = responseStatus.substring(responseStatus.indexOf(' ') + 1, responseStatus.indexOf(' ', responseStatus.indexOf(' ') + 1));
- status = Integer.parseInt(responseStatus);
- String header = reader.readLine();
- while (!"".equals(header)) {
- int colon = header.indexOf(':');
- String headerName = header.substring(0, colon).trim();
- String headerValue = header.substring(colon + 1).trim();
- if ("version".equalsIgnoreCase(headerName)) {
- version = headerValue;
- } else if ("type".equalsIgnoreCase(headerName)) {
- errorType = headerValue;
- } else if ("mess".equalsIgnoreCase(headerName)) {
- message = headerValue;
- } else if ("content-length".equalsIgnoreCase(headerName)) {
- contentLength = Integer.parseInt(headerValue);
- }
- header = reader.readLine();
- }
- } catch (Exception e) {
- log.info(sm.getString("clusterListener.error.parse", command), e);
- }
- }
-
- // Mark as error if the front end server did not return 200; the configuration will
- // be refreshed during the next periodic event
- if (status == 200) {
- // Read the request body
- StringBuffer result = new StringBuffer();
- if (contentLength > 0) {
- int thisTime = contentLength;
- char[] buf = new char[512];
- while (contentLength > 0) {
- thisTime = (contentLength > buf.length) ? buf.length : contentLength;
- int n = reader.read(buf, 0, thisTime);
- if (n <= 0) {
- break;
- } else {
- result.append(buf, 0, n);
- contentLength -= n;
- }
- }
- }
- if (pos != -1) {
- return result.toString();
- }
- } else {
- if ("SYNTAX".equals(errorType)) {
- // Syntax error means the protocol is incorrect, which cannot be automatically fixed
- proxies[i].state = State.DOWN;
- log.error(sm.getString("clusterListener.error.syntax", command, proxies[i], errorType, message));
- } else {
- proxies[i].state = State.ERROR;
- log.error(sm.getString("clusterListener.error.other", command, proxies[i], errorType, message));
- }
- }
-
- } catch (IOException e) {
- // Most likely this is a connection error with the proxy
- proxies[i].state = State.ERROR;
- log.info(sm.getString("clusterListener.error.io", command, proxies[i]), e);
- } finally {
- // If there's an error of any sort, or if the proxy did not return 200, it is an error
- if (proxies[i].state != State.OK) {
- closeConnection(i);
- }
- }
-
- }
-
- return null;
-
- }
-
-
- /**
- * SSL init.
- */
- protected void sslInit() {
- if (ssl) {
- sslSocketFactory = new JSSESocketFactory(this);
- }
- }
-
-
- /**
- * Return a reader to the proxy.
- */
- protected Socket getConnection(int i)
- throws IOException {
- if (connections[i] == null) {
- InetAddress address = (proxies[i].address == null) ? InetAddress.getLocalHost() : proxies[i].address;
- if (ssl) {
- connections[i] = sslSocketFactory.createSocket(address, proxies[i].port);
- } else {
- connections[i] = new Socket(address, proxies[i].port);
- }
- connections[i].setSoTimeout(socketTimeout);
- }
- return connections[i];
- }
-
-
- /**
- * Return a reader to the proxy.
- */
- protected BufferedReader getConnectionReader(int i)
- throws IOException {
- if (connectionReaders[i] == null) {
- connectionReaders[i] = new BufferedReader(new InputStreamReader(connections[i].getInputStream()));
- }
- return connectionReaders[i];
- }
-
-
- /**
- * Return a writer to the proxy.
- */
- protected BufferedWriter getConnectionWriter(int i)
- throws IOException {
- if (connectionWriters[i] == null) {
- connectionWriters[i] = new BufferedWriter(new OutputStreamWriter(connections[i].getOutputStream()));
- }
- return connectionWriters[i];
- }
-
-
- /**
- * Close connection.
- */
- protected void closeConnection(int i) {
- try {
- if (connectionReaders[i] != null) {
- connectionReaders[i].close();
- }
- } catch (IOException e) {
- // Ignore
- }
- connectionReaders[i] = null;
- try {
- if (connectionWriters[i] != null) {
- connectionWriters[i].close();
- }
- } catch (IOException e) {
- // Ignore
- }
- connectionWriters[i] = null;
- try {
- if (connections[i] != null) {
- connections[i].close();
- }
- } catch (IOException e) {
- // Ignore
- }
- connections[i] = null;
- }
-
-
- // ------------------------------------------------------ Proxy Inner Class
-
-
- /**
- * This class represents a front-end httpd server.
- */
- protected static class Proxy {
- public InetAddress address = null;
- public int port = 8000;
- public State state = State.OK;
-
- public String toString() {
- if (address == null) {
- return ":" + port;
- } else {
- return address.getHostAddress() + ":" + port;
- }
- }
-
- public int hashCode() {
- return (address + ":" + port + "-" + state).hashCode();
- }
-
- public boolean equals(Object o) {
- if (o instanceof Proxy) {
- Proxy compare = (Proxy) o;
- if (port != compare.port) {
- return false;
- }
- if (compare.address == null) {
- if (address == null) {
- return true;
- }
- } else if ((compare.address.equals(address)) && port == compare.port) {
- return true;
- }
- }
- return false;
- }
-
- }
-
-
-}
Deleted: trunk/java/org/jboss/web/cluster/Constants.java
===================================================================
--- trunk/java/org/jboss/web/cluster/Constants.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/Constants.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,31 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2006, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-
-package org.jboss.web.cluster;
-
-
-public class Constants {
-
- public static final String Package = "org.jboss.web.cluster";
-
-}
Deleted: trunk/java/org/jboss/web/cluster/JSSEKeyManager.java
===================================================================
--- trunk/java/org/jboss/web/cluster/JSSEKeyManager.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/JSSEKeyManager.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,144 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.jboss.web.cluster;
-
-import java.net.Socket;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.X509KeyManager;
-
-/**
- * X509KeyManager which allows selection of a specific keypair and certificate
- * chain (identified by their keystore alias name) to be used by the server to
- * authenticate itself to SSL clients.
- *
- * @author Jan Luehe
- */
-public final class JSSEKeyManager implements X509KeyManager {
-
- private X509KeyManager delegate;
- private String serverKeyAlias;
-
- /**
- * Constructor.
- *
- * @param mgr The X509KeyManager used as a delegate
- * @param serverKeyAlias The alias name of the server's keypair and
- * supporting certificate chain
- */
- public JSSEKeyManager(X509KeyManager mgr, String serverKeyAlias) {
- this.delegate = mgr;
- this.serverKeyAlias = serverKeyAlias;
- }
-
- /**
- * Choose an alias to authenticate the client side of a secure socket,
- * given the public key type and the list of certificate issuer authorities
- * recognized by the peer (if any).
- *
- * @param keyType The key algorithm type name(s), ordered with the
- * most-preferred key type first
- * @param issuers The list of acceptable CA issuer subject names, or null
- * if it does not matter which issuers are used
- * @param socket The socket to be used for this connection. This parameter
- * can be null, in which case this method will return the most generic
- * alias to use
- *
- * @return The alias name for the desired key, or null if there are no
- * matches
- */
- public String chooseClientAlias(String[] keyType, Principal[] issuers,
- Socket socket) {
- return delegate.chooseClientAlias(keyType, issuers, socket);
- }
-
- /**
- * Returns this key manager's server key alias that was provided in the
- * constructor.
- *
- * @param keyType The key algorithm type name (ignored)
- * @param issuers The list of acceptable CA issuer subject names, or null
- * if it does not matter which issuers are used (ignored)
- * @param socket The socket to be used for this connection. This parameter
- * can be null, in which case this method will return the most generic
- * alias to use (ignored)
- *
- * @return Alias name for the desired key
- */
- public String chooseServerAlias(String keyType, Principal[] issuers,
- Socket socket) {
- return serverKeyAlias;
- }
-
- /**
- * Returns the certificate chain associated with the given alias.
- *
- * @param alias The alias name
- *
- * @return Certificate chain (ordered with the user's certificate first
- * and the root certificate authority last), or null if the alias can't be
- * found
- */
- public X509Certificate[] getCertificateChain(String alias) {
- return delegate.getCertificateChain(alias);
- }
-
- /**
- * Get the matching aliases for authenticating the client side of a secure
- * socket, given the public key type and the list of certificate issuer
- * authorities recognized by the peer (if any).
- *
- * @param keyType The key algorithm type name
- * @param issuers The list of acceptable CA issuer subject names, or null
- * if it does not matter which issuers are used
- *
- * @return Array of the matching alias names, or null if there were no
- * matches
- */
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return delegate.getClientAliases(keyType, issuers);
- }
-
- /**
- * Get the matching aliases for authenticating the server side of a secure
- * socket, given the public key type and the list of certificate issuer
- * authorities recognized by the peer (if any).
- *
- * @param keyType The key algorithm type name
- * @param issuers The list of acceptable CA issuer subject names, or null
- * if it does not matter which issuers are used
- *
- * @return Array of the matching alias names, or null if there were no
- * matches
- */
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return delegate.getServerAliases(keyType, issuers);
- }
-
- /**
- * Returns the key associated with the given alias.
- *
- * @param alias The alias name
- *
- * @return The requested key, or null if the alias can't be found
- */
- public PrivateKey getPrivateKey(String alias) {
- return delegate.getPrivateKey(alias);
- }
-}
Deleted: trunk/java/org/jboss/web/cluster/JSSESocketFactory.java
===================================================================
--- trunk/java/org/jboss/web/cluster/JSSESocketFactory.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/JSSESocketFactory.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,551 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.jboss.web.cluster;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.security.cert.CRL;
-import java.security.cert.CRLException;
-import java.security.cert.CertPathParameters;
-import java.security.cert.CertStore;
-import java.security.cert.CertStoreParameters;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.CollectionCertStoreParameters;
-import java.security.cert.PKIXBuilderParameters;
-import java.security.cert.X509CertSelector;
-import java.util.Collection;
-import java.util.Vector;
-
-import javax.net.ssl.CertPathTrustManagerParameters;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509KeyManager;
-
-import org.apache.tomcat.util.res.StringManager;
-
-/*
- 1. Make the JSSE's jars available, either as an installed
- extension (copy them into jre/lib/ext) or by adding
- them to the Tomcat classpath.
- 2. keytool -genkey -alias tomcat -keyalg RSA
- Use "changeit" as password ( this is the default we use )
- */
-
-/**
- * SSL server socket factory. It _requires_ a valid RSA key and
- * JSSE.
- *
- * @author Harish Prabandham
- * @author Costin Manolache
- * @author Stefan Freyr Stefansson
- * @author EKR -- renamed to JSSESocketFactory
- * @author Jan Luehe
- * @author Bill Barker
- */
-public class JSSESocketFactory {
-
- private static StringManager sm =
- StringManager.getManager("org.apache.tomcat.util.net.jsse.res");
-
- static org.jboss.logging.Logger log =
- org.jboss.logging.Logger.getLogger(JSSESocketFactory.class);
-
- protected boolean initialized;
- //protected String clientAuth = "false";
- protected SSLSocketFactory sslProxy = null;
- protected String[] enabledCiphers;
- protected ClusterListener listener = null;
-
- /**
- * Flag to state that we require client authentication.
- */
- //protected boolean requireClientAuth = false;
-
- /**
- * Flag to state that we would like client authentication.
- */
- //protected boolean wantClientAuth = false;
-
-
- public JSSESocketFactory (ClusterListener listener) {
- this.listener = listener;
- }
-
- public Socket createSocket (InetAddress ifAddress, int port)
- throws IOException
- {
- if (!initialized) init();
- Socket socket = sslProxy.createSocket(ifAddress, port);
- initSocket(socket);
- return socket;
- }
-
- public void handshake(Socket sock) throws IOException {
- ((SSLSocket)sock).startHandshake();
- }
-
- /*
- * Determines the SSL cipher suites to be enabled.
- *
- * @param requestedCiphers Comma-separated list of requested ciphers
- * @param supportedCiphers Array of supported ciphers
- *
- * @return Array of SSL cipher suites to be enabled, or null if none of the
- * requested ciphers are supported
- */
- protected String[] getEnabledCiphers(String requestedCiphers,
- String[] supportedCiphers) {
-
- String[] enabledCiphers = null;
-
- if (requestedCiphers != null) {
- Vector vec = null;
- String cipher = requestedCiphers;
- int index = requestedCiphers.indexOf(',');
- if (index != -1) {
- int fromIndex = 0;
- while (index != -1) {
- cipher = requestedCiphers.substring(fromIndex, index).trim();
- if (cipher.length() > 0) {
- /*
- * Check to see if the requested cipher is among the
- * supported ciphers, i.e., may be enabled
- */
- for (int i=0; supportedCiphers != null
- && i<supportedCiphers.length; i++) {
- if (supportedCiphers[i].equals(cipher)) {
- if (vec == null) {
- vec = new Vector();
- }
- vec.addElement(cipher);
- break;
- }
- }
- }
- fromIndex = index+1;
- index = requestedCiphers.indexOf(',', fromIndex);
- } // while
- cipher = requestedCiphers.substring(fromIndex);
- }
-
- if (cipher != null) {
- cipher = cipher.trim();
- if (cipher.length() > 0) {
- /*
- * Check to see if the requested cipher is among the
- * supported ciphers, i.e., may be enabled
- */
- for (int i=0; supportedCiphers != null
- && i<supportedCiphers.length; i++) {
- if (supportedCiphers[i].equals(cipher)) {
- if (vec == null) {
- vec = new Vector();
- }
- vec.addElement(cipher);
- break;
- }
- }
- }
- }
-
- if (vec != null) {
- enabledCiphers = new String[vec.size()];
- vec.copyInto(enabledCiphers);
- }
- } else {
- enabledCiphers = sslProxy.getDefaultCipherSuites();
- }
-
- return enabledCiphers;
- }
-
- /*
- * Gets the SSL server's keystore.
- */
- protected KeyStore getKeystore(String type, String provider, String pass)
- throws IOException {
- return getStore(type, provider, listener.getSslKeyStore(), pass);
- }
-
- /*
- * Gets the SSL server's truststore.
- */
- protected KeyStore getTrustStore(String keystoreType,
- String keystoreProvider) throws IOException {
- KeyStore trustStore = null;
-
- String truststorePassword = listener.getSslTrustStorePassword();
- if( truststorePassword == null ) {
- truststorePassword = listener.getSslKeyStorePass();
- } else if (truststorePassword.equals("")) {
- truststorePassword = null;
- }
- String truststoreType = listener.getSslTrustStoreType();
- if(truststoreType == null) {
- truststoreType = keystoreType;
- }
- String truststoreProvider = listener.getSslTrustStoreProvider();
- if (truststoreProvider == null) {
- truststoreProvider = keystoreProvider;
- }
-
- if (listener.getSslTrustStore() != null){
- trustStore = getStore(truststoreType, truststoreProvider,
- listener.getSslTrustStore(), truststorePassword);
- }
-
- return trustStore;
- }
-
- /*
- * Gets the key- or truststore with the specified type, path, and password.
- */
- private KeyStore getStore(String type, String provider, String path,
- String pass) throws IOException {
-
- KeyStore ks = null;
- InputStream istream = null;
- try {
- if (provider == null) {
- ks = KeyStore.getInstance(type);
- } else {
- ks = KeyStore.getInstance(type, provider);
- }
- if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) {
- File keyStoreFile = new File(path);
- if (!keyStoreFile.isAbsolute()) {
- keyStoreFile = new File(System.getProperty("catalina.base"),
- path);
- }
- istream = new FileInputStream(keyStoreFile);
- }
-
- if (pass == null)
- ks.load(istream, null);
- else
- ks.load(istream, pass.toCharArray());
- } catch (FileNotFoundException fnfe) {
- log.error(sm.getString("jsse.keystore_load_failed", type, path,
- fnfe.getMessage()), fnfe);
- throw fnfe;
- } catch (IOException ioe) {
- log.error(sm.getString("jsse.keystore_load_failed", type, path,
- ioe.getMessage()), ioe);
- throw ioe;
- } catch(Exception ex) {
- String msg = sm.getString("jsse.keystore_load_failed", type, path,
- ex.getMessage());
- log.error(msg, ex);
- throw new IOException(msg);
- } finally {
- if (istream != null) {
- try {
- istream.close();
- } catch (IOException ioe) {
- // Do nothing
- }
- }
- }
-
- return ks;
- }
-
- /**
- * Reads the keystore and initializes the SSL socket factory.
- */
- void init() throws IOException {
- try {
-
- /**
- String clientAuthStr = (String) attributes.get("clientauth");
- if("true".equalsIgnoreCase(clientAuthStr) ||
- "yes".equalsIgnoreCase(clientAuthStr)) {
- requireClientAuth = true;
- } else if("want".equalsIgnoreCase(clientAuthStr)) {
- wantClientAuth = true;
- }*/
-
- // Create and init SSLContext
- SSLContext context = SSLContext.getInstance(listener.getSslProtocol());
- context.init(getKeyManagers(listener.getSslKeyStoreType(),
- listener.getSslKeyStoreProvider(),
- listener.getSslCertificateEncodingAlgorithm(),
- listener.getSslKeyAlias()),
- getTrustManagers(listener.getSslKeyStoreType(), listener.getSslKeyStoreProvider(),
- listener.getSslTrustAlgorithm()),
- new SecureRandom());
-
- // create proxy
- sslProxy = context.getSocketFactory();
-
- // Determine which cipher suites to enable
- enabledCiphers = getEnabledCiphers(listener.getSslCiphers(),
- sslProxy.getSupportedCipherSuites());
-
- } catch(Exception e) {
- if( e instanceof IOException )
- throw (IOException)e;
- throw new IOException(e.getMessage());
- }
- }
-
- /**
- * Gets the initialized key managers.
- */
- protected KeyManager[] getKeyManagers(String keystoreType,
- String keystoreProvider,
- String algorithm,
- String keyAlias)
- throws Exception {
-
- KeyManager[] kms = null;
-
- KeyStore ks = getKeystore(keystoreType, keystoreProvider, listener.getSslKeyStorePass());
- if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
- throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
- }
-
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
- kmf.init(ks, listener.getSslKeyStorePass().toCharArray());
-
- kms = kmf.getKeyManagers();
- if (keyAlias != null) {
- if ("JKS".equals(keystoreType)) {
- keyAlias = keyAlias.toLowerCase();
- }
- for(int i=0; i<kms.length; i++) {
- kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], keyAlias);
- }
- }
-
- return kms;
- }
-
- /**
- * Gets the intialized trust managers.
- */
- protected TrustManager[] getTrustManagers(String keystoreType,
- String keystoreProvider, String algorithm)
- throws Exception {
- TrustManager[] tms = null;
-
- KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider);
- if (trustStore != null) {
- if (listener.getSslCrlFile() == null) {
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- tmf.init(trustStore);
- tms = tmf.getTrustManagers();
- } else {
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- CertPathParameters params = getParameters(algorithm, listener.getSslCrlFile(), trustStore);
- ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params);
- tmf.init(mfp);
- tms = tmf.getTrustManagers();
- }
- }
-
- return tms;
- }
-
- /**
- * Return the initialization parameters for the TrustManager.
- * Currently, only the default <code>PKIX</code> is supported.
- *
- * @param algorithm The algorithm to get parameters for.
- * @param crlf The path to the CRL file.
- * @param trustStore The configured TrustStore.
- * @return The parameters including the CRLs and TrustStore.
- */
- protected CertPathParameters getParameters(String algorithm,
- String crlf,
- KeyStore trustStore)
- throws Exception {
- CertPathParameters params = null;
- if("PKIX".equalsIgnoreCase(algorithm)) {
- PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore,
- new X509CertSelector());
- Collection crls = getCRLs(crlf);
- CertStoreParameters csp = new CollectionCertStoreParameters(crls);
- CertStore store = CertStore.getInstance("Collection", csp);
- xparams.addCertStore(store);
- xparams.setRevocationEnabled(true);
- xparams.setMaxPathLength(listener.getSslTrustMaxCertLength());
-
- params = xparams;
- } else {
- throw new CRLException("CRLs not supported for type: "+algorithm);
- }
- return params;
- }
-
-
- /**
- * Load the collection of CRLs.
- *
- */
- protected Collection<? extends CRL> getCRLs(String crlf)
- throws IOException, CRLException, CertificateException {
-
- File crlFile = new File(crlf);
- if( !crlFile.isAbsolute() ) {
- crlFile = new File(System.getProperty("catalina.base"), crlf);
- }
- Collection<? extends CRL> crls = null;
- InputStream is = null;
- try {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- is = new FileInputStream(crlFile);
- crls = cf.generateCRLs(is);
- } catch(IOException iex) {
- throw iex;
- } catch(CRLException crle) {
- throw crle;
- } catch(CertificateException ce) {
- throw ce;
- } finally {
- if(is != null) {
- try{
- is.close();
- } catch(Exception ex) {
- }
- }
- }
- return crls;
- }
-
- /**
- * Set the SSL protocol variants to be enabled.
- * @param socket the SSLServerSocket.
- * @param protocols the protocols to use.
- */
- protected void setEnabledProtocols(SSLSocket socket, String []protocols){
- if (protocols != null) {
- socket.setEnabledProtocols(protocols);
- }
- }
-
- /**
- * Determines the SSL protocol variants to be enabled.
- *
- * @param socket The socket to get supported list from.
- * @param requestedProtocols Comma-separated list of requested SSL
- * protocol variants
- *
- * @return Array of SSL protocol variants to be enabled, or null if none of
- * the requested protocol variants are supported
- */
- protected String[] getEnabledProtocols(SSLSocket socket,
- String requestedProtocols){
- String[] supportedProtocols = socket.getSupportedProtocols();
-
- String[] enabledProtocols = null;
-
- if (requestedProtocols != null) {
- Vector vec = null;
- String protocol = requestedProtocols;
- int index = requestedProtocols.indexOf(',');
- if (index != -1) {
- int fromIndex = 0;
- while (index != -1) {
- protocol = requestedProtocols.substring(fromIndex, index).trim();
- if (protocol.length() > 0) {
- /*
- * Check to see if the requested protocol is among the
- * supported protocols, i.e., may be enabled
- */
- for (int i=0; supportedProtocols != null
- && i<supportedProtocols.length; i++) {
- if (supportedProtocols[i].equals(protocol)) {
- if (vec == null) {
- vec = new Vector();
- }
- vec.addElement(protocol);
- break;
- }
- }
- }
- fromIndex = index+1;
- index = requestedProtocols.indexOf(',', fromIndex);
- } // while
- protocol = requestedProtocols.substring(fromIndex);
- }
-
- if (protocol != null) {
- protocol = protocol.trim();
- if (protocol.length() > 0) {
- /*
- * Check to see if the requested protocol is among the
- * supported protocols, i.e., may be enabled
- */
- for (int i=0; supportedProtocols != null
- && i<supportedProtocols.length; i++) {
- if (supportedProtocols[i].equals(protocol)) {
- if (vec == null) {
- vec = new Vector();
- }
- vec.addElement(protocol);
- break;
- }
- }
- }
- }
-
- if (vec != null) {
- enabledProtocols = new String[vec.size()];
- vec.copyInto(enabledProtocols);
- }
- }
-
- return enabledProtocols;
- }
-
- /**
- * Configures the given SSL server socket with the requested cipher suites,
- * protocol versions, and need for client authentication
- */
- private void initSocket(Socket ssocket) {
-
- SSLSocket socket = (SSLSocket) ssocket;
-
- if (enabledCiphers != null) {
- socket.setEnabledCipherSuites(enabledCiphers);
- }
-
- setEnabledProtocols(socket, getEnabledProtocols(socket,
- listener.getSslProtocol()));
-
- // we don't know if client auth is needed -
- // after parsing the request we may re-handshake
- //configureClientAuth(socket);
- }
-
-}
Deleted: trunk/java/org/jboss/web/cluster/LocalStrings.properties
===================================================================
--- trunk/java/org/jboss/web/cluster/LocalStrings.properties 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/LocalStrings.properties 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,24 +0,0 @@
-# Regular messages
-clusterListener.address=Detected local address [{0}]
-clusterListener.config=Sending configuration for engine [{0}]
-clusterListener.context.disable=Undeploy context [{0}] with state [{2}] to Host [{1}]
-clusterListener.context.enable=Deploy context [{0}] with state [{2}] to Host [{1}]
-clusterListener.context.start=Start context [{0}] in Host [{1}]
-clusterListener.context.stop=Stop context [{0}] in Host [{1}]
-clusterListener.jvmRoute=Engine [{0}] will use jvmRoute [{1}]
-clusterListener.request=Sending command [{0}] wildcard [{1}] to proxy [{2}]
-clusterListener.status=Check status for engine [{0}]
-clusterListener.stop=Stop all web applications for engine [{0}]
-
-# Error messages
-clusterListener.error.addressJvmRoute=Error connecting to proxy to determine Engine.JVMRoute or Connector.address
-clusterListener.error.invalidHost=Invalid host specified: {0}
-clusterListener.error.io=IO error sending command {0} to proxy {1}
-clusterListener.error.jmxRegister=Error during JMX registration
-clusterListener.error.jmxUnregister=Error during JMX unregistration
-clusterListener.error.nullAttribute=Value for attribute {0} cannot be null
-clusterListener.error.other=Error [{2}: {3}] sending command {0} to proxy {1}, configuration will be reset
-clusterListener.error.parse=Error parsing response header for command {0}
-clusterListener.error.startListener=Error starting advertise listener
-clusterListener.error.stopListener=Error stopping advertise listener
-clusterListener.error.syntax=Unrecoverable syntax error [{2}: {3}] sending command {0} to proxy {1}
Deleted: trunk/java/org/jboss/web/cluster/advertise/AdvertiseEventType.java
===================================================================
--- trunk/java/org/jboss/web/cluster/advertise/AdvertiseEventType.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/advertise/AdvertiseEventType.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,62 +0,0 @@
-/*
- *
- * Copyright(c) 2008 Red Hat Middleware, LLC,
- * and individual contributors as indicated by the @authors tag.
- * See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library in the file COPYING.LIB;
- * if not, write to the Free Software Foundation, Inc.,
- * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
- *
- */
-
-package org.jboss.web.cluster.advertise;
-
-/**
- * Set what type of event the AdvertiseEvent signals.
- * @param type The type of event. One of:
- * <PRE>
- * ON_NEW_SERVER -- New AdvertisedServer detected
- * ON_STATUS_CHANGE -- AdvertisedServer server changed status
- * </PRE>
- */
-public enum AdvertiseEventType
-{
- /** New AdvertisedServer detected */
- ON_NEW_SERVER( 0),
- /** AdvertisedServer server changed status */
- ON_STATUS_CHANGE( 1);
-
- private int value;
- private AdvertiseEventType(int v)
- {
- value = v;
- }
-
- public int valueOf()
- {
- return value;
- }
-
- public static AdvertiseEventType valueOf(int value)
- {
- for (AdvertiseEventType e : values()) {
- if (e.value == value)
- return e;
- }
- throw new IllegalArgumentException("Invalid initializer: " + value);
- }
-
-}
Deleted: trunk/java/org/jboss/web/cluster/advertise/AdvertiseListener.java
===================================================================
--- trunk/java/org/jboss/web/cluster/advertise/AdvertiseListener.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/advertise/AdvertiseListener.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,448 +0,0 @@
-/*
- *
- * Copyright(c) 2008 Red Hat Middleware, LLC,
- * and individual contributors as indicated by the @authors tag.
- * See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library in the file COPYING.LIB;
- * if not, write to the Free Software Foundation, Inc.,
- * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
- *
- */
-
-package org.jboss.web.cluster.advertise;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.InetAddress;
-import java.net.MulticastSocket;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Locale;
-
-import org.jboss.web.cluster.ClusterListener;
-
-
-/** AdvertiseListener
- * Listens for Advertise messages from mod_cluster
- *
- * @author Mladen Turk
- *
- */
-public class AdvertiseListener
-{
- /** Default port for listening Advertise messages.
- */
- public static int DEFAULT_PORT = 23364;
- /** Default Multicast group address for listening Advertise messages.
- */
- public static String DEFAULT_GROUP = "224.0.1.105";
-
- private static String RFC_822_FMT = "EEE, d MMM yyyy HH:mm:ss Z";
- private int advertisePort = DEFAULT_PORT;
- private String groupAddress = DEFAULT_GROUP;
- private MulticastSocket ms;
- private SimpleDateFormat df;
- private boolean listening = true;
- private boolean initialized = false;
- private boolean running = false;
- private boolean paused = false;
- private boolean daemon = true;
- private byte [] secure = new byte[16];
- private String securityKey = null;
- private MessageDigest md = null;
-
- private HashMap<String, AdvertisedServer> servers;
-
- private ClusterListener listener;
- private Thread workerThread;
-
-
- private static void digestString(MessageDigest md, String s)
- {
- int len = s.length();
- byte [] b = new byte[len];
- for (int i = 0; i < len; i++) {
- char c = s.charAt(i);
- if (c < 127)
- b[i] = (byte)c;
- else
- b[i] = '?';
- }
- md.update(b);
- }
-
- /** Create AdvertiseListener instance
- * @param eventHandler The event handler that will be used for
- * status and new server notifications.
- */
- public AdvertiseListener(ClusterListener listener)
- {
- df = new SimpleDateFormat(RFC_822_FMT, Locale.US);
- servers = new HashMap<String, AdvertisedServer>();
- this.listener = listener;
- }
-
- /**
- * The default is true - the control thread will be
- * in daemon mode. If set to false, the control thread
- * will not be daemon - and will keep the process alive.
- */
- public void setDaemon(boolean b)
- {
- daemon = b;
- }
-
- public boolean getDaemon()
- {
- return daemon;
- }
-
- /** Set Advertise security key
- * @param key The key to use.<br/>
- * Security key must match the AdvertiseKey
- * on the advertised server.
- */
- public void setSecurityKey(String key)
- throws NoSuchAlgorithmException
- {
- securityKey = key;
- if (md == null)
- md = MessageDigest.getInstance("MD5");
- }
-
- /** Set Advertise port
- * @param port The UDP port to use.
- */
- public void setAdvertisePort(int port)
- {
- advertisePort = port;
- }
-
- public int getAdvertisePort()
- {
- return advertisePort;
- }
-
- /** Set Advertise Multicaset group address
- * @param address The IP or host address to use.
- */
- public void setGroupAddress(String address)
- {
- groupAddress = address;
- }
-
- /** Get Advertise Multicaset group address
- */
- public String getGroupAddress()
- {
- return groupAddress;
- }
-
- /** Get Collection of all AdvertisedServer instances.
- */
- public Collection<AdvertisedServer> getServers()
- {
- return servers.values();
- }
-
- /** Get AdvertiseServer server.
- * @param name Server name to get.
- */
- public AdvertisedServer getServer(String name)
- {
- return servers.get(name);
- }
-
- /** Remove the AdvertisedServer from the collection.
- * @param server Server to remove.
- */
- public void removeServer(String name)
- {
- servers.remove(name);
- }
-
- private void init()
- throws IOException
- {
- ms = new MulticastSocket(advertisePort);
- ms.setTimeToLive(16);
- ms.joinGroup(InetAddress.getByName(groupAddress));
- initialized = true;
- }
-
- private void interruptDatagramReader()
- {
- if (!initialized)
- return;
- try {
- // Restrict to localhost.
- ms.setTimeToLive(0);
- DatagramPacket dp = new DatagramPacket(secure, secure.length,
- InetAddress.getByName(groupAddress),
- advertisePort);
- ms.send(dp);
- } catch (IOException e) {
- // Ignore
- }
- }
-
- /** Start the Listener, creating listener thread.
- */
- public void start()
- throws IOException
- {
- if (!initialized) {
- init();
- }
- if (!running) {
- SecureRandom random = new SecureRandom();
- random.nextBytes(secure);
- secure[0] = 0;
- running = true;
- paused = false;
- listening = true;
- AdvertiseListenerWorker aw = new AdvertiseListenerWorker();
- workerThread = new Thread(aw);
- workerThread.setDaemon(daemon);
- workerThread.start();
- }
- }
-
- /**
- * Pause the listener, which will make it stop accepting new advertise
- * messages.
- */
- public void pause()
- {
- if (running && !paused) {
- paused = true;
- interruptDatagramReader();
- }
- }
-
-
- /**
- * Resume the listener, which will make it start accepting new advertise
- * messages again.
- */
- public void resume()
- {
- if (running && paused) {
- // Genererate new private secure
- SecureRandom random = new SecureRandom();
- random.nextBytes(secure);
- secure[0] = 0;
- paused = false;
- }
- }
-
-
- /**
- * Stop the endpoint. This will cause all processing threads to stop.
- */
- public void stop()
- {
- if (running) {
- running = false;
- interruptDatagramReader();
- workerThread = null;
- }
- }
-
-
- /**
- * Deallocate listener and close sockets.
- */
- public void destroy()
- throws IOException
- {
- if (running) {
- stop();
- }
- if (initialized) {
- ms.leaveGroup(InetAddress.getByName(groupAddress));
- ms.close();
- initialized = false;
- ms = null;
- }
- }
-
- private boolean verifyDigest(String digest, String server, String date)
- {
- if (md == null)
- return true;
- md.reset();
- digestString(md, securityKey);
- digestString(md, date);
- digestString(md, server);
- byte [] our = md.digest();
- byte [] dst = new byte[digest.length() * 2];
- for (int i = 0, j = 0; i < digest.length(); i++) {
- char ch = digest.charAt(i);
- dst[j++] = (byte)((ch >= 'A') ? ((ch & 0xdf) - 'A') + 10 : (ch - '0'));
- }
- return true;
- }
-
- /**
- * True if listener is accepting the advetise messages.<br/>
- * If false it means that listener is experiencing some
- * network problems if running.
- */
- public boolean isListening()
- {
- return listening;
- }
-
-
- // ------------------------------------ AdvertiseListenerWorker Inner Class
- private class AdvertiseListenerWorker implements Runnable
- {
-
- protected AdvertiseListenerWorker()
- {
- // Nothing
- }
- /**
- * The background thread that listens for incoming Advertise packets
- * and hands them off to an appropriate AdvertiseEvent handler.
- */
- public void run() {
- byte[] buffer = new byte[512];
- // Loop until we receive a shutdown command
- while (running) {
- // Loop if endpoint is paused
- while (paused) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // Ignore
- }
- }
- try {
- DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
- ms.receive(dp);
- if (!running)
- break;
- byte [] data = dp.getData();
- boolean intr = false;
- if (dp.getLength() == secure.length) {
- int i;
- for (i = 0; i < secure.length; i++) {
- if (data[i] != secure[i])
- break;
- }
- if (i == secure.length)
- intr = true;
- }
- if (intr)
- continue;
- String s = new String(data, 0, dp.getLength(), "8859_1");
- if (!s.startsWith("HTTP/1."))
- continue;
-
- String [] headers = s.split("\r\n");
- String date_str = null;
- Date date = null;
- int status = 0;
- String status_desc = null;
- String digest = null;
- String server_name = null;
- AdvertisedServer server = null;
- boolean added = false;
- for (int i = 0; i < headers.length; i++) {
- if (i == 0) {
- String [] sline = headers[i].split(" ", 3);
- if (sline == null || sline.length != 3)
- break;
- status = Integer.parseInt(sline[1]);
- if (status < 100)
- break;
- status_desc = sline[2];
- }
- else {
- String [] hdrv = headers[i].split(": ", 2);
- if (hdrv == null || hdrv.length != 2)
- break;
- if (hdrv[0].equals("Date")) {
- date_str = hdrv[1];
- try {
- date = df.parse(date_str);
- } catch (ParseException e) {
- date = new Date();
- }
- }
- else if (hdrv[0].equals("Digest")) {
- digest = hdrv[1];
- }
- else if (hdrv[0].equals("Server")) {
- server_name = hdrv[1];
- server = servers.get(server_name);
- if (server == null) {
- server = new AdvertisedServer(server_name);
- added = true;
- }
- }
- else if (server != null) {
- server.setParameter(hdrv[0], hdrv[1]);
- }
- }
- }
- if (server != null && status > 0) {
- if (md != null) {
- /* We need a digest to match */
- if (!verifyDigest(digest, server_name, date_str)) {
- System.out.println("Digest mismatch");
- continue;
- }
- }
- server.setDate(date);
- boolean rc = server.setStatus(status, status_desc);
- if (added) {
- servers.put(server_name, server);
- // Call the new server callback
- //eventHandler.onEvent(AdvertiseEventType.ON_NEW_SERVER, server);
- String proxy = server.getParameter(AdvertisedServer.MANAGER_ADDRESS);
- if (proxy != null) {
- listener.addProxy(proxy);
- }
- }
- else if (rc) {
- // Call the status change callback
- //eventHandler.onEvent(AdvertiseEventType.ON_STATUS_CHANGE, server);
- }
- }
- listening = true;
- } catch (IOException e) {
- // Do not blow the CPU in case of communication error
- listening = false;
- try {
- Thread.sleep(100);
- } catch (InterruptedException x) {
- // Ignore
- }
- }
- }
- }
- }
-
-}
Deleted: trunk/java/org/jboss/web/cluster/advertise/AdvertisedServer.java
===================================================================
--- trunk/java/org/jboss/web/cluster/advertise/AdvertisedServer.java 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/advertise/AdvertisedServer.java 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,122 +0,0 @@
-/*
- *
- * Copyright(c) 2008 Red Hat Middleware, LLC,
- * and individual contributors as indicated by the @authors tag.
- * See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library in the file COPYING.LIB;
- * if not, write to the Free Software Foundation, Inc.,
- * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
- *
- */
-
-package org.jboss.web.cluster.advertise;
-
-import java.util.Date;
-import java.util.HashMap;
-
-/**
- * Advertised server instance
- *
- * @author Mladen Turk
- *
- */
-public class AdvertisedServer
-{
- private String server;
- private Date date;
- private int status;
- private String status_desc;
- private HashMap<String, String> headers;
-
- /** Manager-Address header */
- public static String MANAGER_ADDRESS = "X-Manager-Address";
- /** Manager-Url header */
- public static String MANAGER_URL = "X-Manager-Url";
- /** Manager-Protocol header */
- public static String MANAGER_PROTOCOL = "X-Manager-Protocol";
- /** Manager-Version header */
- public static String MANAGER_VERSION = "X-Manager-Version";
- /** Manager-Host header */
- public static String MANAGER_HOST = "X-Manager-Host";
-
- protected AdvertisedServer(String server)
- {
- this.server = server;
- headers = new HashMap<String, String>();
- }
-
- protected boolean setStatus(int status, String desc)
- {
- boolean rv = false;
- status_desc = desc;
- if (this.status == 0 ) {
- // First time
- this.status = status;
- }
- else if (this.status != status) {
- this.status = status;
- rv = true;
- }
- return rv;
- }
-
- /** Set the Date of the last Advertise message
- */
- protected void setDate(Date date)
- {
- this.date = date;
- }
-
- /** Set the Header
- */
- protected void setParameter(String name, String value)
- {
- headers.put(name, value);
- }
-
- /** Get Date of the last Advertise message
- */
- public Date getDate()
- {
- return date;
- }
-
- /** Get Status code of the last Advertise message
- */
- public int getStatusCode()
- {
- return status;
- }
-
- /** Get Status description of the last Advertise message
- */
- public String getStatusDescription()
- {
- return status_desc;
- }
-
- /** Get Advertise parameter
- */
- public String getParameter(String name)
- {
- return headers.get(name);
- }
-
- public String toString()
- {
- return server;
- }
-}
Deleted: trunk/java/org/jboss/web/cluster/mbeans-descriptors.xml
===================================================================
--- trunk/java/org/jboss/web/cluster/mbeans-descriptors.xml 2010-03-12 12:52:22 UTC (rev 1407)
+++ trunk/java/org/jboss/web/cluster/mbeans-descriptors.xml 2010-03-12 15:42:13 UTC (rev 1408)
@@ -1,138 +0,0 @@
-<?xml version="1.0"?>
-<mbeans-descriptors>
-
- <mbean name="ClusterListener"
- description="Cluster listener for mod_cluster"
- domain="Catalina"
- group="Listener"
- type="org.jboss.web.cluster.ClusterListener">
-
- <attribute name="className"
- description="Fully qualified class name of the managed object"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="containerName"
- description="Object name of the container"
- type="javax.management.ObjectName"/>
-
- <attribute name="proxyConfiguration"
- description="Get the mod_cluster configuration"
- type="java.lang.String"
- writeable="false"/>
-
- <attribute name="proxyList"
- description="Comma delimited list of proxy servers"
- type="java.lang.String"/>
-
- <attribute name="socketTimeout"
- description="Connection timeout for communication with the proxy"
- type="int"/>
-
- <attribute name="advertise"
- description="Enable autodiscovery of httpd servers"
- type="boolean"/>
-
- <attribute name="advertiseGroupAddress"
- description="Multicast address for discovery"
- type="java.lang.String"/>
-
- <attribute name="advertisePort"
- description="Multicast port for discovery"
- type="int"/>
-
- <attribute name="advertiseSecurityKey"
- description="Security key for discovery"
- type="java.lang.String"/>
-
- <attribute name="domain"
- description="Domain parameter, which allows tying a jvmRoute to a particular domain"
- type="java.lang.String"/>
-
- <attribute name="flushPackets"
- description="Allows controlling flushing of packets"
- type="boolean"/>
-
- <attribute name="flushWait"
- description="Time in ms to wait before flushing packets"
- type="int"/>
-
- <attribute name="ping"
- description="Time in s to wait for a pong answer to a ping"
- type="int"/>
-
- <attribute name="smax"
- description="Maximum time on seconds for idle connections above smax"
- type="int"/>
-
- <attribute name="balancer"
- description="Name of the balancer"
- type="java.lang.String"/>
-
- <attribute name="stickySession"
- description="Enables sticky sessions"
- type="boolean"/>
-
- <attribute name="stickySessionRemove"
- description="Remove session when the request cannot be routed to the right node"
- type="boolean"/>
-
- <attribute name="stickySessionForce"
- description="Return an error when the request cannot be routed to the right node"
- type="boolean"/>
-
- <attribute name="workerTimeout"
- description="Timeout to wait for an available worker (default is no wait)"
- type="int"/>
-
- <attribute name="maxAttempts"
- description="Maximum number of attempts to send the request to the backend server"
- type="int"/>
-
- <operation name="refresh"
- description="Refresh configuration"
- impact="ACTION"
- returnType="void"/>
-
- <operation name="reset"
- description="Move the node out of an error state"
- impact="ACTION"
- returnType="void"/>
-
- <operation name="disable"
- description="Disable all webapps for all engines"
- impact="ACTION"
- returnType="boolean"/>
-
- <operation name="enable"
- description="Enable all webapps for all engines"
- impact="ACTION"
- returnType="boolean"/>
-
- <operation name="addProxy"
- description="Add a proxy"
- impact="ACTION"
- returnType="void">
- <parameter name="host"
- description="Proxy address"
- type="java.lang.String"/>
- <parameter name="port"
- description="Proxy port"
- type="int"/>
- </operation>
-
- <operation name="removeProxy"
- description="Remove a proxy"
- impact="ACTION"
- returnType="void">
- <parameter name="host"
- description="Proxy address"
- type="java.lang.String"/>
- <parameter name="port"
- description="Proxy port"
- type="int"/>
- </operation>
-
- </mbean>
-
-</mbeans-descriptors>
14 years, 9 months