issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55,262
|
Bug 55262 Duplicate preludes and codas in same <jsp-property-group> are ignored
|
If a <jsp-property-group> contains multiple <include-prelude> elements that happen to refer to the same file only one include is performed. The same applies to codas. This happens because WebXml stores these in a LinkedHashSet rather than a List. When multiple <jsp-property-group>s are combined, JspConfig uses a Vector and so preserves duplicates as required by the JSP spec. I have a test case demonstrating this but before committing a fix I would like confirmation that WebXml's behaviour is incorrect.
|
resolved fixed
|
85f611e
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-20T20:46:58Z
| 2013-07-14T05:33:20Z
|
java/org/apache/tomcat/util/descriptor/web/JspPropertyGroup.java
|
/*
* 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.descriptor.web;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Representation of a jsp-property-group element in web.xml.
*/
public class JspPropertyGroup {
private Boolean deferredSyntax = null;
public void setDeferredSyntax(String deferredSyntax) {
this.deferredSyntax = Boolean.valueOf(deferredSyntax);
}
public Boolean getDeferredSyntax() { return deferredSyntax; }
private Boolean elIgnored = null;
public void setElIgnored(String elIgnored) {
this.elIgnored = Boolean.valueOf(elIgnored);
}
public Boolean getElIgnored() { return elIgnored; }
private final Set<String> includeCodas = new LinkedHashSet<>();
public void addIncludeCoda(String includeCoda) {
includeCodas.add(includeCoda);
}
public Set<String> getIncludeCodas() { return includeCodas; }
private final Set<String> includePreludes = new LinkedHashSet<>();
public void addIncludePrelude(String includePrelude) {
includePreludes.add(includePrelude);
}
public Set<String> getIncludePreludes() { return includePreludes; }
private Boolean isXml = null;
public void setIsXml(String isXml) {
this.isXml = Boolean.valueOf(isXml);
}
public Boolean getIsXml() { return isXml; }
private String pageEncoding = null;
public void setPageEncoding(String pageEncoding) {
this.pageEncoding = pageEncoding;
}
public String getPageEncoding() { return this.pageEncoding; }
private Boolean scriptingInvalid = null;
public void setScriptingInvalid(String scriptingInvalid) {
this.scriptingInvalid = Boolean.valueOf(scriptingInvalid);
}
public Boolean getScriptingInvalid() { return scriptingInvalid; }
private Boolean trimWhitespace = null;
public void setTrimWhitespace(String trimWhitespace) {
this.trimWhitespace = Boolean.valueOf(trimWhitespace);
}
public Boolean getTrimWhitespace() { return trimWhitespace; }
private LinkedHashSet<String> urlPattern = new LinkedHashSet<>();
public void addUrlPattern(String urlPattern) {
this.urlPattern.add(urlPattern);
}
public Set<String> getUrlPatterns() { return this.urlPattern; }
private String defaultContentType = null;
public void setDefaultContentType(String defaultContentType) {
this.defaultContentType = defaultContentType;
}
public String getDefaultContentType() { return this.defaultContentType; }
private Integer buffer = null;
public void setBuffer(String buffer) {
this.buffer = Integer.valueOf(buffer);
}
public Integer getBuffer() { return this.buffer; }
private Boolean errorOnUndeclaredNamespace = null;
public void setErrorOnUndeclaredNamespace(
String errorOnUndeclaredNamespace) {
this.errorOnUndeclaredNamespace =
Boolean.valueOf(errorOnUndeclaredNamespace);
}
public Boolean getErrorOnUndeclaredNamespace() {
return this.errorOnUndeclaredNamespace;
}
}
|
55,262
|
Bug 55262 Duplicate preludes and codas in same <jsp-property-group> are ignored
|
If a <jsp-property-group> contains multiple <include-prelude> elements that happen to refer to the same file only one include is performed. The same applies to codas. This happens because WebXml stores these in a LinkedHashSet rather than a List. When multiple <jsp-property-group>s are combined, JspConfig uses a Vector and so preserves duplicates as required by the JSP spec. I have a test case demonstrating this but before committing a fix I would like confirmation that WebXml's behaviour is incorrect.
|
resolved fixed
|
85f611e
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-20T20:46:58Z
| 2013-07-14T05:33:20Z
|
test/org/apache/jasper/compiler/TestCompiler.java
|
/*
* 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.jasper.compiler;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
public class TestCompiler extends TomcatBaseTest {
@Test
public void testBug49726a() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
Map<String,List<String>> headers = new HashMap<>();
getUrl("http://localhost:" + getPort() + "/test/bug49nnn/bug49726a.jsp",
res, headers);
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
// Check content type
assertTrue(headers.get("Content-Type").get(0).startsWith("text/html"));
}
@Test
public void testBug49726b() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
Map<String,List<String>> headers = new HashMap<>();
getUrl("http://localhost:" + getPort() + "/test/bug49nnn/bug49726b.jsp",
res, headers);
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
// Check content type
assertTrue(headers.get("Content-Type").get(0).startsWith("text/plain"));
}
@Test
public void testBug53257a() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
// foo;bar.jsp
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo%3bbar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257b() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo&bar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257c() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
// foo#bar.jsp
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo%23bar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257d() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
// foo%bar.jsp
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo%25bar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257e() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo+bar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257f() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo%20bar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257g() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo%20bar/foobar.jsp");
// Check request completed
String result = res.toString();
assertEcho(result, "OK");
}
@Test
public void testBug53257z() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
// Check that URL decoding is not done twice
ByteChunk res = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() +
"/test/bug53257/foo%2525bar.jsp", res, null);
assertEquals(404, rc);
}
@Test
public void testBug51584() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-fragments");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
// No further tests required. The bug triggers an infinite loop on
// context start so the test will crash before it reaches this point if
// it fails
}
/** Assertion for text printed by tags:echo */
private static void assertEcho(String result, String expected) {
assertTrue(result, result.indexOf("<p>" + expected + "</p>") > 0);
}
}
|
55,262
|
Bug 55262 Duplicate preludes and codas in same <jsp-property-group> are ignored
|
If a <jsp-property-group> contains multiple <include-prelude> elements that happen to refer to the same file only one include is performed. The same applies to codas. This happens because WebXml stores these in a LinkedHashSet rather than a List. When multiple <jsp-property-group>s are combined, JspConfig uses a Vector and so preserves duplicates as required by the JSP spec. I have a test case demonstrating this but before committing a fix I would like confirmation that WebXml's behaviour is incorrect.
|
resolved fixed
|
85f611e
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-20T20:46:58Z
| 2013-07-14T05:33:20Z
|
test/org/apache/jasper/servlet/TestJspCServletContext.java
|
/*
* 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.jasper.servlet;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.descriptor.JspConfigDescriptor;
import javax.servlet.descriptor.JspPropertyGroupDescriptor;
import org.junit.Assert;
import org.junit.Test;
public class TestJspCServletContext {
@Test
public void testWebapp() throws Exception {
File appDir = new File("test/webapp");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(3, context.getEffectiveMajorVersion());
Assert.assertEquals(1, context.getEffectiveMinorVersion());
JspConfigDescriptor jspConfigDescriptor =
context.getJspConfigDescriptor();
Assert.assertTrue(jspConfigDescriptor.getTaglibs().isEmpty());
Collection<JspPropertyGroupDescriptor> propertyGroups =
jspConfigDescriptor.getJspPropertyGroups();
Assert.assertEquals(1, propertyGroups.size());
JspPropertyGroupDescriptor groupDescriptor =
propertyGroups.iterator().next();
Assert.assertEquals("text/plain",
groupDescriptor.getDefaultContentType());
Collection<String> urlPatterns =groupDescriptor.getUrlPatterns();
Assert.assertEquals(2, urlPatterns.size());
Iterator<String> iterator = urlPatterns.iterator();
Assert.assertEquals("/bug49nnn/bug49726a.jsp", iterator.next());
Assert.assertEquals("/bug49nnn/bug49726b.jsp", iterator.next());
}
@Test
public void testWebapp_2_2() throws Exception {
File appDir = new File("test/webapp-2.2");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(2, context.getEffectiveMajorVersion());
Assert.assertEquals(2, context.getEffectiveMinorVersion());
}
@Test
public void testWebapp_2_3() throws Exception {
File appDir = new File("test/webapp-2.3");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(2, context.getEffectiveMajorVersion());
Assert.assertEquals(3, context.getEffectiveMinorVersion());
}
@Test
public void testWebapp_2_4() throws Exception {
File appDir = new File("test/webapp-2.4");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(2, context.getEffectiveMajorVersion());
Assert.assertEquals(4, context.getEffectiveMinorVersion());
}
@Test
public void testWebapp_2_5() throws Exception {
File appDir = new File("test/webapp-2.5");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(2, context.getEffectiveMajorVersion());
Assert.assertEquals(5, context.getEffectiveMinorVersion());
}
@Test
public void testWebapp_3_0() throws Exception {
File appDir = new File("test/webapp-3.0");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(3, context.getEffectiveMajorVersion());
Assert.assertEquals(0, context.getEffectiveMinorVersion());
}
@Test
public void testWebapp_3_1() throws Exception {
File appDir = new File("test/webapp-3.1");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(3, context.getEffectiveMajorVersion());
Assert.assertEquals(1, context.getEffectiveMinorVersion());
}
@Test
public void testWebresources() throws Exception {
File appDir = new File("test/webresources/dir1");
JspCServletContext context =
new JspCServletContext(null, appDir.toURI().toURL());
Assert.assertEquals(3, context.getEffectiveMajorVersion());
Assert.assertEquals(1, context.getEffectiveMinorVersion());
}
}
|
55,262
|
Bug 55262 Duplicate preludes and codas in same <jsp-property-group> are ignored
|
If a <jsp-property-group> contains multiple <include-prelude> elements that happen to refer to the same file only one include is performed. The same applies to codas. This happens because WebXml stores these in a LinkedHashSet rather than a List. When multiple <jsp-property-group>s are combined, JspConfig uses a Vector and so preserves duplicates as required by the JSP spec. I have a test case demonstrating this but before committing a fix I would like confirmation that WebXml's behaviour is incorrect.
|
resolved fixed
|
85f611e
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-20T20:46:58Z
| 2013-07-14T05:33:20Z
|
test/org/apache/tomcat/util/descriptor/web/TestJspPropertyGroup.java
| |
55,291
|
Bug 55291 Bug in WsServerContainer leading to NPE
| null |
resolved fixed
|
ab6f21d
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-22T14:26:57Z
| 2013-07-22T16:20:00Z
|
java/org/apache/tomcat/websocket/server/WsServerContainer.java
|
/*
* 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.websocket.server;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Encoder;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.WsSession;
import org.apache.tomcat.websocket.WsWebSocketContainer;
import org.apache.tomcat.websocket.pojo.PojoEndpointServer;
import org.apache.tomcat.websocket.pojo.PojoMethodMapping;
/**
* Provides a per class loader (i.e. per web application) instance of a
* ServerContainer. Web application wide defaults may be configured by setting
* the following servlet context initialisation parameters to the desired
* values.
* <ul>
* <li>{@link Constants#BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li>
* <li>{@link Constants#TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li>
* </ul>
*/
public class WsServerContainer extends WsWebSocketContainer
implements ServerContainer {
// Needs to be a WeakHashMap to prevent memory leaks when a context is
// stopped
private static final Map<ClassLoader,WsServerContainer>
classLoaderContainerMap = new WeakHashMap<>();
private static final Object classLoaderContainerMapLock = new Object();
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static final CloseReason AUTHENTICATED_HTTP_SESSION_CLOSED =
new CloseReason(CloseCodes.VIOLATED_POLICY,
"This connection was established under an authenticated " +
"HTTP session that has ended.");
public static WsServerContainer getServerContainer() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
WsServerContainer result = null;
synchronized (classLoaderContainerMapLock) {
result = classLoaderContainerMap.get(tccl);
if (result == null) {
result = new WsServerContainer();
classLoaderContainerMap.put(tccl, result);
}
}
return result;
}
// For unit testing
protected static void recycle() {
synchronized (classLoaderContainerMapLock) {
classLoaderContainerMap.clear();
}
}
private final WsWriteTimeout wsWriteTimeout = new WsWriteTimeout();
private volatile ServletContext servletContext = null;
private final Map<String,ServerEndpointConfig> configExactMatchMap =
new ConcurrentHashMap<>();
private final ConcurrentHashMap<Integer,SortedSet<TemplatePathMatch>>
configTemplateMatchMap = new ConcurrentHashMap<>();
private volatile boolean addAllowed = true;
private final ConcurrentHashMap<String,Set<WsSession>> authenticatedSessions =
new ConcurrentHashMap<>();
private WsServerContainer() {
// Hide default constructor
}
public void setServletContext(ServletContext servletContext) {
if (this.servletContext == servletContext) {
return;
}
this.servletContext = servletContext;
// Configure servlet context wide defaults
String value = servletContext.getInitParameter(
Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
if (value != null) {
setDefaultMaxBinaryMessageBufferSize(Integer.parseInt(value));
}
value = servletContext.getInitParameter(
Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
if (value != null) {
setDefaultMaxTextMessageBufferSize(Integer.parseInt(value));
}
FilterRegistration fr = servletContext.addFilter(
WsFilter.class.getName(), WsFilter.class);
EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.REQUEST,
DispatcherType.FORWARD);
fr.addMappingForUrlPatterns(types, true, "/*");
}
/**
* Published the provided endpoint implementation at the specified path with
* the specified configuration. {@link #setServletContext(ServletContext)}
* must be called before calling this method.
*
* @param sec The configuration to use when creating endpoint instances
* @throws DeploymentException
*/
@Override
public void addEndpoint(ServerEndpointConfig sec)
throws DeploymentException {
if (!addAllowed) {
throw new DeploymentException(
sm.getString("serverContainer.addNotAllowed"));
}
if (servletContext == null) {
throw new DeploymentException(
sm.getString("serverContainer.servletContextMissing"));
}
String path = sec.getPath();
UriTemplate uriTemplate = new UriTemplate(path);
if (uriTemplate.hasParameters()) {
Integer key = Integer.valueOf(uriTemplate.getSegmentCount());
SortedSet<TemplatePathMatch> templateMatches =
configTemplateMatchMap.get(key);
if (templateMatches == null) {
// Ensure that if concurrent threads execute this block they
// both end up using the same TreeSet instance
templateMatches = new TreeSet<>(
TemplatePathMatchComparator.getInstance());
configTemplateMatchMap.putIfAbsent(key, templateMatches);
templateMatches = configTemplateMatchMap.get(key);
}
if (!templateMatches.add(new TemplatePathMatch(sec, uriTemplate))) {
// Duplicate uriTemplate;
throw new DeploymentException(
sm.getString("serverContainer.duplicatePaths", path));
}
} else {
// Exact match
ServerEndpointConfig old = configExactMatchMap.put(path, sec);
if (old != null) {
// Duplicate path mappings
throw new DeploymentException(
sm.getString("serverContainer.duplicatePaths", path));
}
}
}
/**
* Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)}
* for publishing plain old java objects (POJOs) that have been annotated as
* WebSocket endpoints.
*
* @param pojo The annotated POJO
*/
@Override
public void addEndpoint(Class<?> pojo) throws DeploymentException {
ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
if (annotation == null) {
throw new DeploymentException(
sm.getString("serverContainer.missingAnnotation",
pojo.getName()));
}
String path = annotation.value();
// Validate encoders
validateEncoders(annotation.encoders());
// Method mapping
PojoMethodMapping methodMapping = new PojoMethodMapping(pojo,
annotation.decoders(), path);
// ServerEndpointConfig
ServerEndpointConfig sec;
Class<? extends Configurator> configuratorClazz =
annotation.configurator();
Configurator configurator = null;
if (!configuratorClazz.equals(Configurator.class)) {
try {
configurator = annotation.configurator().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new DeploymentException(sm.getString(
"serverContainer.configuratorFail",
annotation.configurator().getName(),
pojo.getClass().getName()), e);
}
}
sec = ServerEndpointConfig.Builder.create(pojo, path).
decoders(Arrays.asList(annotation.decoders())).
encoders(Arrays.asList(annotation.encoders())).
subprotocols(Arrays.asList(annotation.subprotocols())).
configurator(configurator).
build();
sec.getUserProperties().put(
PojoEndpointServer.POJO_METHOD_MAPPING_KEY,
methodMapping);
addEndpoint(sec);
}
public WsMappingResult findMapping(String path) {
// Prevent registering additional endpoints once the first attempt has
// been made to use one
if (addAllowed) {
addAllowed = false;
}
// Check an exact match. Simple case as there are no templates.
ServerEndpointConfig sec = configExactMatchMap.get(path);
if (sec != null) {
return new WsMappingResult(sec, Collections.EMPTY_MAP);
}
// No exact match. Need to look for template matches.
UriTemplate pathUriTemplate = null;
try {
pathUriTemplate = new UriTemplate(path);
} catch (DeploymentException e) {
// Path is not valid so can't be matched to a WebSocketEndpoint
return null;
}
// Number of segments has to match
Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount());
SortedSet<TemplatePathMatch> templateMatches =
configTemplateMatchMap.get(key);
if (templateMatches == null) {
// No templates with an equal number of segments so there will be
// no matches
return null;
}
// List is in alphabetical order of normalised templates.
// Correct match is the first one that matches.
Map<String,String> pathParams = null;
for (TemplatePathMatch templateMatch : templateMatches) {
pathParams = templateMatch.getUriTemplate().match(pathUriTemplate);
if (pathParams != null) {
sec = templateMatch.getConfig();
break;
}
}
if (sec == null) {
// No match
return null;
}
if (!PojoEndpointServer.class.isAssignableFrom(sec.getEndpointClass())) {
// Need to make path params available to POJO
sec.getUserProperties().put(
PojoEndpointServer.POJO_PATH_PARAM_KEY,
pathParams);
}
return new WsMappingResult(sec, pathParams);
}
protected WsWriteTimeout getTimeout() {
return wsWriteTimeout;
}
/**
* {@inheritDoc}
*
* Overridden to make it visible to other classes in this package.
*/
@Override
protected void registerSession(Endpoint endpoint, WsSession wsSession) {
super.registerSession(endpoint, wsSession);
if (wsSession.getUserPrincipal() != null &&
wsSession.getHttpSessionId() != null) {
registerAuthenticatedSession(wsSession,
wsSession.getHttpSessionId());
}
}
/**
* {@inheritDoc}
*
* Overridden to make it visible to other classes in this package.
*/
@Override
protected void unregisterSession(Endpoint endpoint, WsSession wsSession) {
if (wsSession.getUserPrincipal() != null &&
wsSession.getHttpSessionId() != null) {
unregisterAuthenticatedSession(wsSession,
wsSession.getHttpSessionId());
}
super.unregisterSession(endpoint, wsSession);
}
private void registerAuthenticatedSession(WsSession wsSession,
String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
if (wsSession == null) {
wsSessions = Collections.newSetFromMap(
new ConcurrentHashMap<WsSession,Boolean>());
authenticatedSessions.putIfAbsent(httpSessionId, wsSessions);
wsSessions = authenticatedSessions.get(httpSessionId);
}
wsSessions.add(wsSession);
}
private void unregisterAuthenticatedSession(WsSession wsSession,
String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
wsSessions.remove(wsSession);
}
public void closeAuthenticatedSession(String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.remove(httpSessionId);
if (wsSessions != null && !wsSessions.isEmpty()) {
for (WsSession wsSession : wsSessions) {
try {
wsSession.close(AUTHENTICATED_HTTP_SESSION_CLOSED);
} catch (IOException e) {
// Any IOExceptions during close will have been caught and the
// onError method called.
}
}
}
}
private static void validateEncoders(Class<? extends Encoder>[] encoders)
throws DeploymentException {
for (Class<? extends Encoder> encoder : encoders) {
// Need to instantiate decoder to ensure it is valid and that
// deployment can be failed if it is not
@SuppressWarnings("unused")
Encoder instance;
try {
encoder.newInstance();
} catch(InstantiationException | IllegalAccessException e) {
throw new DeploymentException(sm.getString(
"serverContainer.encoderFail", encoder.getName()), e);
}
}
}
private static class TemplatePathMatch {
private final ServerEndpointConfig config;
private final UriTemplate uriTemplate;
public TemplatePathMatch(ServerEndpointConfig config,
UriTemplate uriTemplate) {
this.config = config;
this.uriTemplate = uriTemplate;
}
public ServerEndpointConfig getConfig() {
return config;
}
public UriTemplate getUriTemplate() {
return uriTemplate;
}
}
/**
* This Comparator implementation is thread-safe so only create a single
* instance.
*/
private static class TemplatePathMatchComparator
implements Comparator<TemplatePathMatch> {
private static final TemplatePathMatchComparator INSTANCE =
new TemplatePathMatchComparator();
public static TemplatePathMatchComparator getInstance() {
return INSTANCE;
}
private TemplatePathMatchComparator() {
// Hide default constructor
}
@Override
public int compare(TemplatePathMatch tpm1, TemplatePathMatch tpm2) {
return tpm1.getUriTemplate().getNormalizedPath().compareTo(
tpm2.getUriTemplate().getNormalizedPath());
}
}
}
|
55,267
|
Bug 55267 NIO thread locked
|
Did some load test and thread got stuck, see dump. Basically I just simulate 100 users that connect and disconnect.
|
resolved fixed
|
11bf498
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-23T14:21:38Z
| 2013-07-15T14:53:20Z
|
java/org/apache/coyote/ajp/AjpNioProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import org.apache.coyote.ActionCode;
import org.apache.coyote.RequestInfo;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.NioChannel;
import org.apache.tomcat.util.net.NioEndpoint;
import org.apache.tomcat.util.net.NioEndpoint.KeyAttachment;
import org.apache.tomcat.util.net.NioSelectorPool;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapper;
/**
* Processes AJP requests using NIO.
*/
public class AjpNioProcessor extends AbstractAjpProcessor<NioChannel> {
/**
* Logger.
*/
private static final Log log = LogFactory.getLog(AjpNioProcessor.class);
@Override
protected Log getLog() {
return log;
}
// ----------------------------------------------------------- Constructors
public AjpNioProcessor(int packetSize, NioEndpoint endpoint) {
super(packetSize, endpoint);
response.setOutputBuffer(new SocketOutputBuffer());
pool = endpoint.getSelectorPool();
}
// ----------------------------------------------------- Instance Variables
/**
* Socket associated with the current connection.
*/
protected NioChannel socket;
/**
* Selector pool for the associated endpoint.
*/
protected final NioSelectorPool pool;
// --------------------------------------------------------- Public Methods
/**
* Process pipelined HTTP requests using the specified input and output
* streams.
*
* @throws IOException error during an I/O operation
*/
@Override
public SocketState process(SocketWrapper<NioChannel> socket)
throws IOException {
RequestInfo rp = request.getRequestProcessor();
rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);
// Setting up the socket
this.socket = socket.getSocket();
long soTimeout = endpoint.getSoTimeout();
boolean cping = false;
// Error flag
error = false;
while (!error && !endpoint.isPaused()) {
// Parsing the request header
try {
// Get first message of the request
int bytesRead = readMessage(requestHeaderMessage, false);
if (bytesRead == 0) {
break;
}
// Set back timeout if keep alive timeout is enabled
if (keepAliveTimeout > 0) {
socket.setTimeout(soTimeout);
}
// Check message type, process right away and break if
// not regular request processing
int type = requestHeaderMessage.getByte();
if (type == Constants.JK_AJP13_CPING_REQUEST) {
if (endpoint.isPaused()) {
recycle(true);
break;
}
cping = true;
try {
output(pongMessageArray, 0, pongMessageArray.length);
} catch (IOException e) {
error = true;
}
recycle(false);
continue;
} else if(type != Constants.JK_AJP13_FORWARD_REQUEST) {
// Unexpected packet type. Unread body packets should have
// been swallowed in finish().
if (log.isDebugEnabled()) {
log.debug("Unexpected message: " + type);
}
error = true;
recycle(true);
break;
}
request.setStartTime(System.currentTimeMillis());
} catch (IOException e) {
error = true;
break;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.debug(sm.getString("ajpprocessor.header.error"), t);
// 400 - Bad Request
response.setStatus(400);
getAdapter().log(request, response, 0);
error = true;
}
if (!error) {
// Setting up filters, and parse some request headers
rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE);
try {
prepareRequest();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.debug(sm.getString("ajpprocessor.request.prepare"), t);
// 400 - Internal Server Error
response.setStatus(400);
getAdapter().log(request, response, 0);
error = true;
}
}
if (!error && !cping && endpoint.isPaused()) {
// 503 - Service unavailable
response.setStatus(503);
getAdapter().log(request, response, 0);
error = true;
}
cping = false;
// Process the request in the adapter
if (!error) {
try {
rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
getAdapter().service(request, response);
} catch (InterruptedIOException e) {
error = true;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("ajpprocessor.request.process"), t);
// 500 - Internal Server Error
response.setStatus(500);
getAdapter().log(request, response, 0);
error = true;
}
}
if (isAsync() && !error) {
break;
}
// Finish the response if not done yet
if (!finished) {
try {
finish();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
error = true;
}
}
// If there was an error, make sure the request is counted as
// and error, and update the statistics counter
if (error) {
response.setStatus(500);
}
request.updateCounters();
rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE);
// Set keep alive timeout if enabled
if (keepAliveTimeout > 0) {
socket.setTimeout(keepAliveTimeout);
}
recycle(false);
}
rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
if (!error && !endpoint.isPaused()) {
if (isAsync()) {
return SocketState.LONG;
} else {
return SocketState.OPEN;
}
} else {
return SocketState.CLOSED;
}
}
// ----------------------------------------------------- ActionHook Methods
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
protected void actionInternal(ActionCode actionCode, Object param) {
if (actionCode == ActionCode.ASYNC_COMPLETE) {
if (asyncStateMachine.asyncComplete()) {
((NioEndpoint)endpoint).dispatchForEvent(socket, SocketStatus.OPEN_READ, false);
}
} else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) {
if (param == null) return;
long timeout = ((Long)param).longValue();
final KeyAttachment ka = (KeyAttachment)socket.getAttachment(false);
if (keepAliveTimeout > 0) {
ka.setTimeout(timeout);
}
} else if (actionCode == ActionCode.ASYNC_DISPATCH) {
if (asyncStateMachine.asyncDispatch()) {
((NioEndpoint)endpoint).dispatchForEvent(socket, SocketStatus.OPEN_READ, true); }
}
}
// ------------------------------------------------------ Protected Methods
@Override
protected void output(byte[] src, int offset, int length)
throws IOException {
NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
if ( att == null ) throw new IOException("Key must be cancelled");
ByteBuffer writeBuffer = socket.getBufHandler() .getWriteBuffer();
writeBuffer.put(src, offset, length);
writeBuffer.flip();
long writeTimeout = att.getTimeout();
Selector selector = null;
try {
selector = pool.get();
} catch ( IOException x ) {
//ignore
}
try {
pool.write(writeBuffer, socket, selector, writeTimeout, true);
}finally {
writeBuffer.clear();
if ( selector != null ) pool.put(selector);
}
}
/**
* Read the specified amount of bytes, and place them in the input buffer.
*/
protected int read(byte[] buf, int pos, int n, boolean blockFirstRead)
throws IOException {
int read = 0;
int res = 0;
boolean block = blockFirstRead;
while (read < n) {
res = readSocket(buf, read + pos, n, block);
if (res > 0) {
read += res;
} else if (res == 0 && !block) {
break;
} else {
throw new IOException(sm.getString("ajpprocessor.failedread"));
}
block = true;
}
return read;
}
private int readSocket(byte[] buf, int pos, int n, boolean block)
throws IOException {
int nRead = 0;
socket.getBufHandler().getReadBuffer().clear();
socket.getBufHandler().getReadBuffer().limit(n);
if ( block ) {
Selector selector = null;
try {
selector = pool.get();
} catch ( IOException x ) {
// Ignore
}
try {
NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
if ( att == null ) throw new IOException("Key must be cancelled.");
nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout());
} catch ( EOFException eof ) {
nRead = -1;
} finally {
if ( selector != null ) pool.put(selector);
}
} else {
nRead = socket.read(socket.getBufHandler().getReadBuffer());
}
if (nRead > 0) {
socket.getBufHandler().getReadBuffer().flip();
socket.getBufHandler().getReadBuffer().limit(nRead);
socket.getBufHandler().getReadBuffer().get(buf, pos, nRead);
return nRead;
} else if (nRead == -1) {
//return false;
throw new EOFException(sm.getString("iib.eof.error"));
} else {
return 0;
}
}
/** Receive a chunk of data. Called to implement the
* 'special' packet in ajp13 and to receive the data
* after we send a GET_BODY packet
*/
@Override
public boolean receive() throws IOException {
first = false;
bodyMessage.reset();
readMessage(bodyMessage, true);
// No data received.
if (bodyMessage.getLen() == 0) {
// just the header
// Don't mark 'end of stream' for the first chunk.
return false;
}
int blen = bodyMessage.peekInt();
if (blen == 0) {
return false;
}
bodyMessage.getBodyBytes(bodyBytes);
empty = false;
return true;
}
/**
* Read an AJP message.
*
* @return The number of bytes read
* @throws IOException any other failure, including incomplete reads
*/
protected int readMessage(AjpMessage message, boolean blockFirstRead)
throws IOException {
byte[] buf = message.getBuffer();
int headerLength = message.getHeaderLength();
int bytesRead = read(buf, 0, headerLength, blockFirstRead);
if (bytesRead == 0) {
return 0;
}
int messageLength = message.processHeader(true);
if (messageLength < 0) {
// Invalid AJP header signature
throw new IOException(sm.getString("ajpmessage.invalidLength",
Integer.valueOf(messageLength)));
}
else if (messageLength == 0) {
// Zero length message.
return bytesRead;
}
else {
if (messageLength > buf.length) {
// Message too long for the buffer
// Need to trigger a 400 response
throw new IllegalArgumentException(sm.getString(
"ajpprocessor.header.tooLong",
Integer.valueOf(messageLength),
Integer.valueOf(buf.length)));
}
bytesRead += read(buf, headerLength, messageLength, true);
return bytesRead;
}
}
}
|
55,267
|
Bug 55267 NIO thread locked
|
Did some load test and thread got stuck, see dump. Basically I just simulate 100 users that connect and disconnect.
|
resolved fixed
|
11bf498
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-23T14:21:38Z
| 2013-07-15T14:53:20Z
|
java/org/apache/coyote/http11/InternalNioOutputBuffer.java
|
/*
* 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.coyote.http11;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.coyote.OutputBuffer;
import org.apache.coyote.Response;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.NioChannel;
import org.apache.tomcat.util.net.NioEndpoint;
import org.apache.tomcat.util.net.NioSelectorPool;
import org.apache.tomcat.util.net.SocketWrapper;
/**
* Output buffer.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
* @author Filip Hanik
*/
public class InternalNioOutputBuffer extends AbstractOutputBuffer<NioChannel> {
// ----------------------------------------------------------- Constructors
/**
* Default constructor.
*/
public InternalNioOutputBuffer(Response response, int headerBufferSize) {
super(response, headerBufferSize);
outputStreamOutputBuffer = new SocketOutputBuffer();
}
/**
* Underlying socket.
*/
private NioChannel socket;
/**
* Selector pool, for blocking reads and blocking writes
*/
private NioSelectorPool pool;
/**
* Track if the byte buffer is flipped
*/
protected volatile boolean flipped = false;
private final AtomicLong bytesWritten = new AtomicLong(0);
// --------------------------------------------------------- Public Methods
/**
* Recycle the output buffer. This should be called when closing the
* connection.
*/
@Override
public void recycle() {
super.recycle();
if (socket != null) {
socket.getBufHandler().getWriteBuffer().clear();
socket = null;
}
flipped = false;
bytesWritten.set(0);
}
// ------------------------------------------------ HTTP/1.1 Output Methods
/**
* Send an acknowledgment.
*/
@Override
public void sendAck() throws IOException {
if (!committed) {
socket.getBufHandler().getWriteBuffer().put(
Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length);
writeToSocket(socket.getBufHandler().getWriteBuffer(), true, true);
}
}
/**
*
* @param bytebuffer ByteBuffer
* @param flip boolean
* @return int
* @throws IOException
*/
private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException {
if ( flip ) {
bytebuffer.flip();
flipped = true;
}
int written = 0;
NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
if ( att == null ) throw new IOException("Key must be cancelled");
long writeTimeout = att.getTimeout();
Selector selector = null;
try {
selector = pool.get();
} catch ( IOException x ) {
//ignore
}
try {
written = pool.write(bytebuffer, socket, selector, writeTimeout, block);
//make sure we are flushed
do {
if (socket.flush(true,selector,writeTimeout)) break;
}while ( true );
}finally {
if ( selector != null ) pool.put(selector);
}
if ( block || bytebuffer.remaining()==0) {
//blocking writes must empty the buffer
//and if remaining==0 then we did empty it
bytebuffer.clear();
flipped = false;
}
// If there is data left in the buffer the socket will be registered for
// write further up the stack. This is to ensure the socket is only
// registered for write once as both container and user code can trigger
// write registration.
return written;
}
// ------------------------------------------------------ Protected Methods
@Override
public void init(SocketWrapper<NioChannel> socketWrapper,
AbstractEndpoint endpoint) throws IOException {
socket = socketWrapper.getSocket();
pool = ((NioEndpoint)endpoint).getSelectorPool();
}
/**
* Commit the response.
*
* @throws IOException an underlying I/O error occurred
*/
@Override
protected void commit()
throws IOException {
// The response is now committed
committed = true;
response.setCommitted(true);
if (pos > 0) {
// Sending the response header buffer
addToBB(headerBuffer, 0, pos);
}
}
private synchronized void addToBB(byte[] buf, int offset, int length)
throws IOException {
if (length == 0) return;
// Try to flush any data in the socket's write buffer first
boolean dataLeft = flushBuffer(isBlocking());
// Keep writing until all the data is written or a non-blocking write
// leaves data in the buffer
while (!dataLeft && length>0) {
int thisTime = transfer(buf,offset,length,socket.getBufHandler().getWriteBuffer());
length = length - thisTime;
offset = offset + thisTime;
int written = writeToSocket(socket.getBufHandler().getWriteBuffer(),
isBlocking(), true);
if (written == 0) {
dataLeft = true;
} else {
dataLeft = flushBuffer(isBlocking());
}
}
NioEndpoint.KeyAttachment ka = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
if ( ka!= null ) ka.access();//prevent timeouts for just doing client writes
if (!isBlocking() && length>0) {
//we must buffer as long as it fits
//ByteBufferHolder tail = bufferedWrite.
addToBuffers(buf, offset, length);
}
}
private void addToBuffers(byte[] buf, int offset, int length) {
ByteBufferHolder holder = bufferedWrites.peekLast();
if (holder==null || holder.isFlipped() || holder.getBuf().remaining()<length) {
ByteBuffer buffer = ByteBuffer.allocate(Math.max(bufferedWriteSize,length));
holder = new ByteBufferHolder(buffer,false);
bufferedWrites.add(holder);
}
holder.getBuf().put(buf,offset,length);
}
/**
* Callback to write data from the buffer.
*/
@Override
protected boolean flushBuffer(boolean block) throws IOException {
//prevent timeout for async,
SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
if (key != null) {
NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment) key.attachment();
attach.access();
}
boolean dataLeft = hasMoreDataToFlush();
//write to the socket, if there is anything to write
if (dataLeft) {
writeToSocket(socket.getBufHandler().getWriteBuffer(),block, !flipped);
}
dataLeft = hasMoreDataToFlush();
if (!dataLeft && bufferedWrites.size() > 0) {
Iterator<ByteBufferHolder> bufIter = bufferedWrites.iterator();
while (!hasMoreDataToFlush() && bufIter.hasNext()) {
ByteBufferHolder buffer = bufIter.next();
buffer.flip();
while (!hasMoreDataToFlush() && buffer.getBuf().remaining()>0) {
transfer(buffer.getBuf(), socket.getBufHandler().getWriteBuffer());
if (buffer.getBuf().remaining() == 0) {
bufIter.remove();
}
writeToSocket(socket.getBufHandler().getWriteBuffer(),block, true);
//here we must break if we didn't finish the write
}
}
}
return hasMoreDataToFlush();
}
@Override
protected boolean hasMoreDataToFlush() {
return (flipped && socket.getBufHandler().getWriteBuffer().remaining()>0) ||
(!flipped && socket.getBufHandler().getWriteBuffer().position() > 0);
}
@Override
protected void registerWriteInterest() throws IOException {
NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
if (att == null) {
throw new IOException("Key must be cancelled");
}
att.getPoller().add(socket, SelectionKey.OP_WRITE);
}
private int transfer(byte[] from, int offset, int length, ByteBuffer to) {
int max = Math.min(length, to.remaining());
to.put(from, offset, max);
return max;
}
private void transfer(ByteBuffer from, ByteBuffer to) {
int max = Math.min(from.remaining(), to.remaining());
ByteBuffer tmp = from.duplicate ();
tmp.limit (tmp.position() + max);
to.put (tmp);
from.position(from.position() + max);
}
// ----------------------------------- OutputStreamOutputBuffer Inner Class
/**
* This class is an output buffer which will write data to an output
* stream.
*/
protected class SocketOutputBuffer implements OutputBuffer {
/**
* Write chunk.
*/
@Override
public int doWrite(ByteChunk chunk, Response res) throws IOException {
int len = chunk.getLength();
int start = chunk.getStart();
byte[] b = chunk.getBuffer();
addToBB(b, start, len);
byteCount += chunk.getLength();
return chunk.getLength();
}
@Override
public long getBytesWritten() {
return byteCount;
}
}
}
|
55,267
|
Bug 55267 NIO thread locked
|
Did some load test and thread got stuck, see dump. Basically I just simulate 100 users that connect and disconnect.
|
resolved fixed
|
11bf498
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-23T14:21:38Z
| 2013-07-15T14:53:20Z
|
java/org/apache/coyote/http11/upgrade/NioServletOutputStream.java
|
/*
* 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.coyote.http11.upgrade;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import org.apache.tomcat.util.net.NioChannel;
import org.apache.tomcat.util.net.NioEndpoint;
import org.apache.tomcat.util.net.NioSelectorPool;
import org.apache.tomcat.util.net.SocketWrapper;
public class NioServletOutputStream extends AbstractServletOutputStream {
private final NioChannel channel;
private final NioSelectorPool pool;
private final int maxWrite;
public NioServletOutputStream(
SocketWrapper<NioChannel> wrapper, NioSelectorPool pool) {
channel = wrapper.getSocket();
this.pool = pool;
maxWrite = channel.getBufHandler().getWriteBuffer().capacity();
}
@Override
protected int doWrite(boolean block, byte[] b, int off, int len)
throws IOException {
int leftToWrite = len;
int count = 0;
int offset = off;
while (leftToWrite > 0) {
int writeThisLoop;
int writtenThisLoop;
if (leftToWrite > maxWrite) {
writeThisLoop = maxWrite;
} else {
writeThisLoop = leftToWrite;
}
writtenThisLoop = doWriteInternal(block, b, offset, writeThisLoop);
count += writtenThisLoop;
leftToWrite -= writtenThisLoop;
if (writtenThisLoop < writeThisLoop) {
break;
}
}
return count;
}
private int doWriteInternal (boolean block, byte[] b, int off, int len)
throws IOException {
channel.getBufHandler().getWriteBuffer().clear();
channel.getBufHandler().getWriteBuffer().put(b, off, len);
channel.getBufHandler().getWriteBuffer().flip();
int written = 0;
NioEndpoint.KeyAttachment att =
(NioEndpoint.KeyAttachment) channel.getAttachment(false);
if (att == null) {
throw new IOException("Key must be cancelled");
}
long writeTimeout = att.getTimeout();
Selector selector = null;
try {
selector = pool.get();
} catch ( IOException x ) {
//ignore
}
try {
written = pool.write(channel.getBufHandler().getWriteBuffer(),
channel, selector, writeTimeout, block);
} finally {
if (selector != null) {
pool.put(selector);
}
}
if (written < len) {
channel.getPoller().add(channel, SelectionKey.OP_WRITE);
}
return written;
}
@Override
protected void doFlush() throws IOException {
NioEndpoint.KeyAttachment att =
(NioEndpoint.KeyAttachment) channel.getAttachment(false);
if (att == null) {
throw new IOException("Key must be cancelled");
}
long writeTimeout = att.getTimeout();
Selector selector = null;
try {
selector = pool.get();
} catch ( IOException x ) {
//ignore
}
try {
do {
if (channel.flush(true, selector, writeTimeout)) {
break;
}
} while (true);
} finally {
if (selector != null) {
pool.put(selector);
}
}
}
@Override
protected void doClose() throws IOException {
channel.close();
}
}
|
55,267
|
Bug 55267 NIO thread locked
|
Did some load test and thread got stuck, see dump. Basically I just simulate 100 users that connect and disconnect.
|
resolved fixed
|
11bf498
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-23T14:21:38Z
| 2013-07-15T14:53:20Z
|
java/org/apache/tomcat/util/net/NioEndpoint.java
|
/*
* 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.net;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.X509KeyManager;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.collections.SynchronizedQueue;
import org.apache.tomcat.util.collections.SynchronizedStack;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.SecureNioChannel.ApplicationBufferHandler;
import org.apache.tomcat.util.net.jsse.NioX509KeyManager;
/**
* NIO tailored thread pool, providing the following services:
* <ul>
* <li>Socket acceptor thread</li>
* <li>Socket poller thread</li>
* <li>Worker threads pool</li>
* </ul>
*
* When switching to Java 5, there's an opportunity to use the virtual
* machine's thread pool.
*
* @author Mladen Turk
* @author Remy Maucherat
* @author Filip Hanik
*/
public class NioEndpoint extends AbstractEndpoint {
// -------------------------------------------------------------- Constants
private static final Log log = LogFactory.getLog(NioEndpoint.class);
public static final int OP_REGISTER = 0x100; //register interest op
public static final int OP_CALLBACK = 0x200; //callback interest op
// ----------------------------------------------------------------- Fields
private NioSelectorPool selectorPool = new NioSelectorPool();
/**
* Server socket "pointer".
*/
private ServerSocketChannel serverSock = null;
/**
* use send file
*/
private boolean useSendfile = true;
/**
* The size of the OOM parachute.
*/
private int oomParachute = 1024*1024;
/**
* The oom parachute, when an OOM error happens,
* will release the data, giving the JVM instantly
* a chunk of data to be able to recover with.
*/
private byte[] oomParachuteData = null;
/**
* Make sure this string has already been allocated
*/
private static final String oomParachuteMsg =
"SEVERE:Memory usage is low, parachute is non existent, your system may start failing.";
/**
* Keep track of OOM warning messages.
*/
private long lastParachuteCheck = System.currentTimeMillis();
/**
*
*/
private volatile CountDownLatch stopLatch = null;
/**
* Cache for SocketProcessor objects
*/
private final SynchronizedStack<SocketProcessor> processorCache =
new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getProcessorCache());
/**
* Cache for key attachment objects
*/
private final SynchronizedStack<KeyAttachment> keyCache =
new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getKeyCache());
/**
* Cache for poller events
*/
private final SynchronizedStack<PollerEvent> eventCache =
new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getEventCache());
/**
* Bytebuffer cache, each channel holds a set of buffers (two, except for SSL holds four)
*/
private final SynchronizedStack<NioChannel> nioChannels =
new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getBufferPoolSize());
// ------------------------------------------------------------- Properties
/**
* Generic properties, introspected
*/
@Override
public boolean setProperty(String name, String value) {
final String selectorPoolName = "selectorPool.";
try {
if (name.startsWith(selectorPoolName)) {
return IntrospectionUtils.setProperty(selectorPool, name.substring(selectorPoolName.length()), value);
} else {
return super.setProperty(name, value);
}
}catch ( Exception x ) {
log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x);
return false;
}
}
/**
* Priority of the poller threads.
*/
private int pollerThreadPriority = Thread.NORM_PRIORITY;
public void setPollerThreadPriority(int pollerThreadPriority) { this.pollerThreadPriority = pollerThreadPriority; }
public int getPollerThreadPriority() { return pollerThreadPriority; }
/**
* Handling of accepted sockets.
*/
private Handler handler = null;
public void setHandler(Handler handler ) { this.handler = handler; }
public Handler getHandler() { return handler; }
/**
* Allow comet request handling.
*/
private boolean useComet = true;
public void setUseComet(boolean useComet) { this.useComet = useComet; }
@Override
public boolean getUseComet() { return useComet; }
@Override
public boolean getUseCometTimeout() { return getUseComet(); }
@Override
public boolean getUsePolling() { return true; } // Always supported
/**
* Poller thread count.
*/
private int pollerThreadCount = Math.min(2,Runtime.getRuntime().availableProcessors());
public void setPollerThreadCount(int pollerThreadCount) { this.pollerThreadCount = pollerThreadCount; }
public int getPollerThreadCount() { return pollerThreadCount; }
private long selectorTimeout = 1000;
public void setSelectorTimeout(long timeout){ this.selectorTimeout = timeout;}
public long getSelectorTimeout(){ return this.selectorTimeout; }
/**
* The socket poller.
*/
private Poller[] pollers = null;
private AtomicInteger pollerRotater = new AtomicInteger(0);
/**
* Return an available poller in true round robin fashion
*/
public Poller getPoller0() {
int idx = Math.abs(pollerRotater.incrementAndGet()) % pollers.length;
return pollers[idx];
}
public void setSelectorPool(NioSelectorPool selectorPool) {
this.selectorPool = selectorPool;
}
public void setSocketProperties(SocketProperties socketProperties) {
this.socketProperties = socketProperties;
}
public void setUseSendfile(boolean useSendfile) {
this.useSendfile = useSendfile;
}
/**
* Is deferAccept supported?
*/
@Override
public boolean getDeferAccept() {
// Not supported
return false;
}
public void setOomParachute(int oomParachute) {
this.oomParachute = oomParachute;
}
public void setOomParachuteData(byte[] oomParachuteData) {
this.oomParachuteData = oomParachuteData;
}
private SSLContext sslContext = null;
public SSLContext getSSLContext() { return sslContext;}
public void setSSLContext(SSLContext c) { sslContext = c;}
private String[] enabledCiphers;
private String[] enabledProtocols;
/**
* Port in use.
*/
@Override
public int getLocalPort() {
ServerSocketChannel ssc = serverSock;
if (ssc == null) {
return -1;
} else {
ServerSocket s = ssc.socket();
if (s == null) {
return -1;
} else {
return s.getLocalPort();
}
}
}
@Override
public String[] getCiphersUsed() {
return enabledCiphers;
}
// --------------------------------------------------------- OOM Parachute Methods
protected void checkParachute() {
boolean para = reclaimParachute(false);
if (!para && (System.currentTimeMillis()-lastParachuteCheck)>10000) {
try {
log.fatal(oomParachuteMsg);
}catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
System.err.println(oomParachuteMsg);
}
lastParachuteCheck = System.currentTimeMillis();
}
}
protected boolean reclaimParachute(boolean force) {
if ( oomParachuteData != null ) return true;
if ( oomParachute > 0 && ( force || (Runtime.getRuntime().freeMemory() > (oomParachute*2))) )
oomParachuteData = new byte[oomParachute];
return oomParachuteData != null;
}
protected void releaseCaches() {
this.keyCache.clear();
this.nioChannels.clear();
this.processorCache.clear();
if ( handler != null ) handler.recycle();
}
// --------------------------------------------------------- Public Methods
/**
* Number of keepalive sockets.
*/
public int getKeepAliveCount() {
if (pollers == null) {
return 0;
} else {
int sum = 0;
for (int i=0; i<pollers.length; i++) {
sum += pollers[i].getKeyCount();
}
return sum;
}
}
// ----------------------------------------------- Public Lifecycle Methods
/**
* Initialize the endpoint.
*/
@Override
public void bind() throws Exception {
serverSock = ServerSocketChannel.open();
socketProperties.setProperties(serverSock.socket());
InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
serverSock.socket().bind(addr,getBacklog());
serverSock.configureBlocking(true); //mimic APR behavior
serverSock.socket().setSoTimeout(getSocketProperties().getSoTimeout());
// Initialize thread count defaults for acceptor, poller
if (acceptorThreadCount == 0) {
// FIXME: Doesn't seem to work that well with multiple accept threads
acceptorThreadCount = 1;
}
if (pollerThreadCount <= 0) {
//minimum one poller thread
pollerThreadCount = 1;
}
stopLatch = new CountDownLatch(pollerThreadCount);
// Initialize SSL if needed
if (isSSLEnabled()) {
SSLUtil sslUtil = handler.getSslImplementation().getSSLUtil(this);
sslContext = sslUtil.createSSLContext();
sslContext.init(wrap(sslUtil.getKeyManagers()),
sslUtil.getTrustManagers(), null);
SSLSessionContext sessionContext =
sslContext.getServerSessionContext();
if (sessionContext != null) {
sslUtil.configureSessionContext(sessionContext);
}
// Determine which cipher suites and protocols to enable
enabledCiphers = sslUtil.getEnableableCiphers(sslContext);
enabledProtocols = sslUtil.getEnableableProtocols(sslContext);
}
if (oomParachute>0) reclaimParachute(true);
selectorPool.open();
}
public KeyManager[] wrap(KeyManager[] managers) {
if (managers==null) return null;
KeyManager[] result = new KeyManager[managers.length];
for (int i=0; i<result.length; i++) {
if (managers[i] instanceof X509KeyManager && getKeyAlias()!=null) {
result[i] = new NioX509KeyManager((X509KeyManager)managers[i],getKeyAlias());
} else {
result[i] = managers[i];
}
}
return result;
}
/**
* Start the NIO endpoint, creating acceptor, poller threads.
*/
@Override
public void startInternal() throws Exception {
if (!running) {
running = true;
paused = false;
// Create worker collection
if ( getExecutor() == null ) {
createExecutor();
}
initializeConnectionLatch();
// Start poller threads
pollers = new Poller[getPollerThreadCount()];
for (int i=0; i<pollers.length; i++) {
pollers[i] = new Poller();
Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i);
pollerThread.setPriority(threadPriority);
pollerThread.setDaemon(true);
pollerThread.start();
}
startAcceptorThreads();
}
}
/**
* Stop the endpoint. This will cause all processing threads to stop.
*/
@Override
public void stopInternal() {
releaseConnectionLatch();
if (!paused) {
pause();
}
if (running) {
running = false;
unlockAccept();
for (int i=0; pollers!=null && i<pollers.length; i++) {
if (pollers[i]==null) continue;
pollers[i].destroy();
pollers[i] = null;
}
try {
stopLatch.await(selectorTimeout + 100, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
}
}
eventCache.clear();
keyCache.clear();
nioChannels.clear();
processorCache.clear();
shutdownExecutor();
}
/**
* Deallocate NIO memory pools, and close server socket.
*/
@Override
public void unbind() throws Exception {
if (log.isDebugEnabled()) {
log.debug("Destroy initiated for "+new InetSocketAddress(getAddress(),getPort()));
}
if (running) {
stop();
}
// Close server socket
serverSock.socket().close();
serverSock.close();
serverSock = null;
sslContext = null;
releaseCaches();
selectorPool.close();
if (log.isDebugEnabled()) {
log.debug("Destroy completed for "+new InetSocketAddress(getAddress(),getPort()));
}
}
// ------------------------------------------------------ Protected Methods
public int getWriteBufSize() {
return socketProperties.getTxBufSize();
}
public int getReadBufSize() {
return socketProperties.getRxBufSize();
}
public NioSelectorPool getSelectorPool() {
return selectorPool;
}
@Override
public boolean getUseSendfile() {
return useSendfile;
}
public int getOomParachute() {
return oomParachute;
}
public byte[] getOomParachuteData() {
return oomParachuteData;
}
@Override
protected AbstractEndpoint.Acceptor createAcceptor() {
return new Acceptor();
}
/**
* Process the specified connection.
*/
protected boolean setSocketOptions(SocketChannel socket) {
// Process the connection
try {
//disable blocking, APR style, we are gonna be polling it
socket.configureBlocking(false);
Socket sock = socket.socket();
socketProperties.setProperties(sock);
NioChannel channel = nioChannels.pop();
if ( channel == null ) {
// SSL setup
if (sslContext != null) {
SSLEngine engine = createSSLEngine();
int appbufsize = engine.getSession().getApplicationBufferSize();
NioBufferHandler bufhandler = new NioBufferHandler(Math.max(appbufsize,socketProperties.getAppReadBufSize()),
Math.max(appbufsize,socketProperties.getAppWriteBufSize()),
socketProperties.getDirectBuffer());
channel = new SecureNioChannel(socket, engine, bufhandler, selectorPool);
} else {
// normal tcp setup
NioBufferHandler bufhandler = new NioBufferHandler(socketProperties.getAppReadBufSize(),
socketProperties.getAppWriteBufSize(),
socketProperties.getDirectBuffer());
channel = new NioChannel(socket, bufhandler);
}
} else {
channel.setIOChannel(socket);
if ( channel instanceof SecureNioChannel ) {
SSLEngine engine = createSSLEngine();
((SecureNioChannel)channel).reset(engine);
} else {
channel.reset();
}
}
getPoller0().register(channel);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
log.error("",t);
} catch (Throwable tt) {
ExceptionUtils.handleThrowable(t);
}
// Tell to close the socket
return false;
}
return true;
}
protected SSLEngine createSSLEngine() {
SSLEngine engine = sslContext.createSSLEngine();
if ("false".equals(getClientAuth())) {
engine.setNeedClientAuth(false);
engine.setWantClientAuth(false);
} else if ("true".equals(getClientAuth()) || "yes".equals(getClientAuth())){
engine.setNeedClientAuth(true);
} else if ("want".equals(getClientAuth())) {
engine.setWantClientAuth(true);
}
engine.setUseClientMode(false);
engine.setEnabledCipherSuites(enabledCiphers);
engine.setEnabledProtocols(enabledProtocols);
handler.onCreateSSLEngine(engine);
return engine;
}
/**
* Returns true if a worker thread is available for processing.
* @return boolean
*/
protected boolean isWorkerAvailable() {
return true;
}
public boolean dispatchForEvent(NioChannel socket, SocketStatus status, boolean dispatch) {
if (!dispatch) {
processSocket(socket,status,dispatch);
} else {
socket.getPoller().add(socket, OP_CALLBACK);
}
return true;
}
protected boolean processSocket(NioChannel socket, SocketStatus status, boolean dispatch) {
try {
KeyAttachment attachment = (KeyAttachment)socket.getAttachment(false);
if (attachment == null) {
return false;
}
attachment.setCometNotify(false); //will get reset upon next reg
SocketProcessor sc = processorCache.pop();
if ( sc == null ) sc = new SocketProcessor(socket,status);
else sc.reset(socket,status);
if ( dispatch && getExecutor()!=null ) getExecutor().execute(sc);
else sc.run();
} catch (RejectedExecutionException rx) {
log.warn("Socket processing request was rejected for:"+socket,rx);
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
@Override
protected Log getLog() {
return log;
}
// --------------------------------------------------- Acceptor Inner Class
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/
protected class Acceptor extends AbstractEndpoint.Acceptor {
@Override
public void run() {
int errorDelay = 0;
// Loop until we receive a shutdown command
while (running) {
// Loop if endpoint is paused
while (paused && running) {
state = AcceptorState.PAUSED;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore
}
}
if (!running) {
break;
}
state = AcceptorState.RUNNING;
try {
//if we have reached max connections, wait
countUpOrAwaitConnection();
SocketChannel socket = null;
try {
// Accept the next incoming connection from the server
// socket
socket = serverSock.accept();
} catch (IOException ioe) {
//we didn't get a socket
countDownConnection();
// Introduce delay if necessary
errorDelay = handleExceptionWithDelay(errorDelay);
// re-throw
throw ioe;
}
// Successful accept, reset the error delay
errorDelay = 0;
// setSocketOptions() will add channel to the poller
// if successful
if (running && !paused) {
if (!setSocketOptions(socket)) {
countDownConnection();
closeSocket(socket);
}
} else {
countDownConnection();
closeSocket(socket);
}
} catch (SocketTimeoutException sx) {
// Ignore: Normal condition
} catch (IOException x) {
if (running) {
log.error(sm.getString("endpoint.accept.fail"), x);
}
} catch (OutOfMemoryError oom) {
try {
oomParachuteData = null;
releaseCaches();
log.error("", oom);
}catch ( Throwable oomt ) {
try {
try {
System.err.println(oomParachuteMsg);
oomt.printStackTrace();
}catch (Throwable letsHopeWeDontGetHere){
ExceptionUtils.handleThrowable(letsHopeWeDontGetHere);
}
}catch (Throwable letsHopeWeDontGetHere){
ExceptionUtils.handleThrowable(letsHopeWeDontGetHere);
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("endpoint.accept.fail"), t);
}
}
state = AcceptorState.ENDED;
}
}
private void closeSocket(SocketChannel socket) {
try {
socket.socket().close();
} catch (IOException ioe) {
if (log.isDebugEnabled()) {
log.debug("", ioe);
}
}
try {
socket.close();
} catch (IOException ioe) {
if (log.isDebugEnabled()) {
log.debug("", ioe);
}
}
}
// ----------------------------------------------------- Poller Inner Classes
/**
*
* PollerEvent, cacheable object for poller events to avoid GC
*/
public static class PollerEvent implements Runnable {
private NioChannel socket;
private int interestOps;
private KeyAttachment key;
public PollerEvent(NioChannel ch, KeyAttachment k, int intOps) {
reset(ch, k, intOps);
}
public void reset(NioChannel ch, KeyAttachment k, int intOps) {
socket = ch;
interestOps = intOps;
key = k;
}
public void reset() {
reset(null, null, 0);
}
@Override
public void run() {
if ( interestOps == OP_REGISTER ) {
try {
socket.getIOChannel().register(socket.getPoller().getSelector(), SelectionKey.OP_READ, key);
} catch (Exception x) {
log.error("", x);
}
} else {
final SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
try {
boolean cancel = false;
if (key != null) {
final KeyAttachment att = (KeyAttachment) key.attachment();
if ( att!=null ) {
//handle callback flag
if ((interestOps & OP_CALLBACK) == OP_CALLBACK ) {
att.setCometNotify(true);
} else {
att.setCometNotify(false);
}
interestOps = (interestOps & (~OP_CALLBACK));//remove the callback flag
att.access();//to prevent timeout
//we are registering the key to start with, reset the fairness counter.
int ops = key.interestOps() | interestOps;
att.interestOps(ops);
if (att.getCometNotify()) key.interestOps(0);
else key.interestOps(ops);
} else {
cancel = true;
}
} else {
cancel = true;
}
if ( cancel ) socket.getPoller().cancelledKey(key,SocketStatus.ERROR);
}catch (CancelledKeyException ckx) {
try {
socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT);
}catch (Exception ignore) {}
}
}//end if
}//run
@Override
public String toString() {
return super.toString()+"[intOps="+this.interestOps+"]";
}
}
/**
* Poller class.
*/
public class Poller implements Runnable {
private Selector selector;
private final SynchronizedQueue<PollerEvent> events =
new SynchronizedQueue<>();
private volatile boolean close = false;
private long nextExpiration = 0;//optimize expiration handling
private AtomicLong wakeupCounter = new AtomicLong(0l);
private volatile int keyCount = 0;
public Poller() throws IOException {
synchronized (Selector.class) {
// Selector.open() isn't thread safe
// http://bugs.sun.com/view_bug.do?bug_id=6427854
// Affects 1.6.0_29, fixed in 1.7.0_01
this.selector = Selector.open();
}
}
public int getKeyCount() { return keyCount; }
public Selector getSelector() { return selector;}
/**
* Destroy the poller.
*/
protected void destroy() {
// Wait for polltime before doing anything, so that the poller threads
// exit, otherwise parallel closure of sockets which are still
// in the poller can cause problems
close = true;
selector.wakeup();
}
private void addEvent(PollerEvent event) {
events.offer(event);
if ( wakeupCounter.incrementAndGet() == 0 ) selector.wakeup();
}
/**
* Add specified socket and associated pool to the poller. The socket will
* be added to a temporary array, and polled first after a maximum amount
* of time equal to pollTime (in most cases, latency will be much lower,
* however).
*
* @param socket to add to the poller
*/
public void add(final NioChannel socket) {
add(socket,SelectionKey.OP_READ);
}
public void add(final NioChannel socket, final int interestOps) {
PollerEvent r = eventCache.pop();
if ( r==null) r = new PollerEvent(socket,null,interestOps);
else r.reset(socket,null,interestOps);
if ( (interestOps&OP_CALLBACK) == OP_CALLBACK ) {
nextExpiration = 0; //force the check for faster callback
}
addEvent(r);
if (close) {
processSocket(socket, SocketStatus.STOP, false);
}
}
/**
* Processes events in the event queue of the Poller.
*
* @return <code>true</code> if some events were processed,
* <code>false</code> if queue was empty
*/
public boolean events() {
boolean result = false;
PollerEvent pe = null;
while ( (pe = events.poll()) != null ) {
result = true;
try {
pe.run();
pe.reset();
if (running && !paused) {
eventCache.push(pe);
}
} catch ( Throwable x ) {
log.error("",x);
}
}
return result;
}
/**
* Registers a newly created socket with the poller.
*
* @param socket The newly created socket
*/
public void register(final NioChannel socket) {
socket.setPoller(this);
KeyAttachment key = keyCache.pop();
final KeyAttachment ka = key!=null?key:new KeyAttachment(socket);
ka.reset(this,socket,getSocketProperties().getSoTimeout());
ka.setKeepAliveLeft(NioEndpoint.this.getMaxKeepAliveRequests());
PollerEvent r = eventCache.pop();
ka.interestOps(SelectionKey.OP_READ);//this is what OP_REGISTER turns into.
if ( r==null) r = new PollerEvent(socket,ka,OP_REGISTER);
else r.reset(socket,ka,OP_REGISTER);
addEvent(r);
}
public void cancelledKey(SelectionKey key, SocketStatus status) {
try {
if ( key == null ) return;//nothing to do
KeyAttachment ka = (KeyAttachment) key.attachment();
if (ka != null && ka.isComet() && status != null) {
ka.setComet(false);//to avoid a loop
if (status == SocketStatus.TIMEOUT ) {
if (processSocket(ka.getChannel(), status, true)) {
return; // don't close on comet timeout
}
} else {
// Don't dispatch if the lines below are canceling the key
processSocket(ka.getChannel(), status, false);
}
}
key.attach(null);
if (ka!=null) handler.release(ka);
else handler.release((SocketChannel)key.channel());
if (key.isValid()) key.cancel();
if (key.channel().isOpen()) {
try {
key.channel().close();
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"endpoint.debug.channelCloseFail"), e);
}
}
}
try {
if (ka!=null) {
ka.getSocket().close(true);
}
} catch (Exception e){
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"endpoint.debug.socketCloseFail"), e);
}
}
try {
if (ka != null && ka.getSendfileData() != null
&& ka.getSendfileData().fchannel != null
&& ka.getSendfileData().fchannel.isOpen()) {
ka.getSendfileData().fchannel.close();
}
} catch (Exception ignore) {
}
if (ka!=null) {
ka.reset();
countDownConnection();
}
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
if (log.isDebugEnabled()) log.error("",e);
}
}
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/
@Override
public void run() {
// Loop until destroy() is called
while (true) {
try {
// Loop if endpoint is paused
while (paused && (!close) ) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
}
boolean hasEvents = false;
// Time to terminate?
if (close) {
events();
timeout(0, false);
try {
selector.close();
} catch (IOException ioe) {
log.error(sm.getString(
"endpoint.nio.selectorCloseFail"), ioe);
}
break;
} else {
hasEvents = events();
}
try {
if ( !close ) {
if (wakeupCounter.getAndSet(-1) > 0) {
//if we are here, means we have other stuff to do
//do a non blocking select
keyCount = selector.selectNow();
} else {
keyCount = selector.select(selectorTimeout);
}
wakeupCounter.set(0);
}
if (close) {
events();
timeout(0, false);
try {
selector.close();
} catch (IOException ioe) {
log.error(sm.getString(
"endpoint.nio.selectorCloseFail"), ioe);
}
break;
}
} catch ( NullPointerException x ) {
//sun bug 5076772 on windows JDK 1.5
if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x);
if ( wakeupCounter == null || selector == null ) throw x;
continue;
} catch ( CancelledKeyException x ) {
//sun bug 5076772 on windows JDK 1.5
if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x);
if ( wakeupCounter == null || selector == null ) throw x;
continue;
} catch (Throwable x) {
ExceptionUtils.handleThrowable(x);
log.error("",x);
continue;
}
//either we timed out or we woke up, process events first
if ( keyCount == 0 ) hasEvents = (hasEvents | events());
Iterator<SelectionKey> iterator =
keyCount > 0 ? selector.selectedKeys().iterator() : null;
// Walk through the collection of ready keys and dispatch
// any active event.
while (iterator != null && iterator.hasNext()) {
SelectionKey sk = iterator.next();
KeyAttachment attachment = (KeyAttachment)sk.attachment();
// Attachment may be null if another thread has called
// cancelledKey()
if (attachment == null) {
iterator.remove();
} else {
attachment.access();
iterator.remove();
processKey(sk, attachment);
}
}//while
//process timeouts
timeout(keyCount,hasEvents);
if ( oomParachute > 0 && oomParachuteData == null ) checkParachute();
} catch (OutOfMemoryError oom) {
try {
oomParachuteData = null;
releaseCaches();
log.error("", oom);
}catch ( Throwable oomt ) {
try {
System.err.println(oomParachuteMsg);
oomt.printStackTrace();
}catch (Throwable letsHopeWeDontGetHere){
ExceptionUtils.handleThrowable(letsHopeWeDontGetHere);
}
}
}
}//while
stopLatch.countDown();
}
protected boolean processKey(SelectionKey sk, KeyAttachment attachment) {
boolean result = true;
try {
if ( close ) {
cancelledKey(sk, SocketStatus.STOP);
} else if ( sk.isValid() && attachment != null ) {
attachment.access();//make sure we don't time out valid sockets
NioChannel channel = attachment.getChannel();
if (sk.isReadable() || sk.isWritable() ) {
if ( attachment.getSendfileData() != null ) {
processSendfile(sk,attachment, false);
} else if ( attachment.isComet() ) {
//check if thread is available
if ( isWorkerAvailable() ) {
//set interest ops to 0 so we don't get multiple
//Invocations for both read and write on separate threads
reg(sk, attachment, 0);
//read goes before write
if (sk.isReadable()) {
//read notification
if (!processSocket(channel, SocketStatus.OPEN_READ, true))
processSocket(channel, SocketStatus.DISCONNECT, true);
} else {
//future placement of a WRITE notif
if (!processSocket(channel, SocketStatus.OPEN_WRITE, true))
processSocket(channel, SocketStatus.DISCONNECT, true);
}
} else {
result = false;
}
} else {
//later on, improve latch behavior
if ( isWorkerAvailable() ) {
boolean readAndWrite = sk.isReadable() && sk.isWritable();
reg(sk, attachment, 0);
if (attachment.isAsync() && readAndWrite) {
//remember the that we want to know about write too
attachment.interestOps(SelectionKey.OP_WRITE);
}
//read goes before write
if (sk.isReadable()) {
//read notification
if (!processSocket(channel, SocketStatus.OPEN_READ, true))
close = true;
} else {
//future placement of a WRITE notif
if (!processSocket(channel, SocketStatus.OPEN_WRITE, true))
close = true;
}
if (close) {
cancelledKey(sk,SocketStatus.DISCONNECT);
}
} else {
result = false;
}
}
}
} else {
//invalid key
cancelledKey(sk, SocketStatus.ERROR);
}
} catch ( CancelledKeyException ckx ) {
cancelledKey(sk, SocketStatus.ERROR);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error("",t);
}
return result;
}
public boolean processSendfile(SelectionKey sk, KeyAttachment attachment, boolean event) {
NioChannel sc = null;
try {
unreg(sk, attachment, sk.readyOps());
SendfileData sd = attachment.getSendfileData();
if (log.isTraceEnabled()) {
log.trace("Processing send file for: " + sd.fileName);
}
//setup the file channel
if ( sd.fchannel == null ) {
File f = new File(sd.fileName);
if ( !f.exists() ) {
cancelledKey(sk,SocketStatus.ERROR);
return false;
}
@SuppressWarnings("resource") // Closed when channel is closed
FileInputStream fis = new FileInputStream(f);
sd.fchannel = fis.getChannel();
}
//configure output channel
sc = attachment.getChannel();
sc.setSendFile(true);
//ssl channel is slightly different
WritableByteChannel wc = ((sc instanceof SecureNioChannel)?sc:sc.getIOChannel());
//we still have data in the buffer
if (sc.getOutboundRemaining()>0) {
if (sc.flushOutbound()) {
attachment.access();
}
} else {
long written = sd.fchannel.transferTo(sd.pos,sd.length,wc);
if ( written > 0 ) {
sd.pos += written;
sd.length -= written;
attachment.access();
} else {
// Unusual not to be able to transfer any bytes
// Check the length was set correctly
if (sd.fchannel.size() <= sd.pos) {
throw new IOException("Sendfile configured to " +
"send more data than was available");
}
}
}
if ( sd.length <= 0 && sc.getOutboundRemaining()<=0) {
if (log.isDebugEnabled()) {
log.debug("Send file complete for: "+sd.fileName);
}
attachment.setSendfileData(null);
try {
sd.fchannel.close();
} catch (Exception ignore) {
}
if ( sd.keepAlive ) {
if (log.isDebugEnabled()) {
log.debug("Connection is keep alive, registering back for OP_READ");
}
if (event) {
this.add(attachment.getChannel(),SelectionKey.OP_READ);
} else {
reg(sk,attachment,SelectionKey.OP_READ);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Send file connection is being closed");
}
cancelledKey(sk,SocketStatus.STOP);
return false;
}
} else {
if (log.isDebugEnabled()) {
log.debug("OP_WRITE for sendfile: " + sd.fileName);
}
if (event) {
add(attachment.getChannel(),SelectionKey.OP_WRITE);
} else {
reg(sk,attachment,SelectionKey.OP_WRITE);
}
}
}catch ( IOException x ) {
if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x);
cancelledKey(sk,SocketStatus.ERROR);
return false;
}catch ( Throwable t ) {
log.error("",t);
cancelledKey(sk, SocketStatus.ERROR);
return false;
}finally {
if (sc!=null) sc.setSendFile(false);
}
return true;
}
protected void unreg(SelectionKey sk, KeyAttachment attachment, int readyOps) {
//this is a must, so that we don't have multiple threads messing with the socket
reg(sk,attachment,sk.interestOps()& (~readyOps));
}
protected void reg(SelectionKey sk, KeyAttachment attachment, int intops) {
sk.interestOps(intops);
attachment.interestOps(intops);
}
protected void timeout(int keyCount, boolean hasEvents) {
long now = System.currentTimeMillis();
// This method is called on every loop of the Poller. Don't process
// timeouts on every loop of the Poller since that would create too
// much load and timeouts can afford to wait a few seconds.
// However, do process timeouts if any of the following are true:
// - the selector simply timed out (suggests there isn't much load)
// - the nextExpiration time has passed
// - the server socket is being closed
if (nextExpiration > 0 && (keyCount > 0 || hasEvents) && (now < nextExpiration) && !close) {
return;
}
//timeout
Set<SelectionKey> keys = selector.keys();
int keycount = 0;
for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
SelectionKey key = iter.next();
keycount++;
try {
KeyAttachment ka = (KeyAttachment) key.attachment();
if ( ka == null ) {
cancelledKey(key, SocketStatus.ERROR); //we don't support any keys without attachments
} else if ( ka.getError() ) {
cancelledKey(key, SocketStatus.ERROR);//TODO this is not yet being used
} else if (ka.getCometNotify() ) {
ka.setCometNotify(false);
int ops = ka.interestOps() & ~OP_CALLBACK;
reg(key,ka,0);//avoid multiple calls, this gets re-registered after invocation
ka.interestOps(ops);
if (!processSocket(ka.getChannel(), SocketStatus.OPEN_READ, true)) processSocket(ka.getChannel(), SocketStatus.DISCONNECT, true);
} else if ((ka.interestOps()&SelectionKey.OP_READ) == SelectionKey.OP_READ ||
(ka.interestOps()&SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
//only timeout sockets that we are waiting for a read from
long delta = now - ka.getLastAccess();
long timeout = ka.getTimeout();
boolean isTimedout = timeout > 0 && delta > timeout;
if ( close ) {
key.interestOps(0);
ka.interestOps(0); //avoid duplicate stop calls
processKey(key,ka);
} else if (isTimedout) {
key.interestOps(0);
ka.interestOps(0); //avoid duplicate timeout calls
cancelledKey(key, SocketStatus.TIMEOUT);
}
} else if (ka.isAsync() || ka.isComet()) {
if (close) {
key.interestOps(0);
ka.interestOps(0); //avoid duplicate stop calls
processKey(key,ka);
} else if (!ka.isAsync() || ka.getTimeout() > 0) {
// Async requests with a timeout of 0 or less never timeout
long delta = now - ka.getLastAccess();
long timeout = (ka.getTimeout()==-1)?((long) socketProperties.getSoTimeout()):(ka.getTimeout());
boolean isTimedout = delta > timeout;
if (isTimedout) {
// Prevent subsequent timeouts if the timeout event takes a while to process
ka.access(Long.MAX_VALUE);
processSocket(ka.getChannel(), SocketStatus.TIMEOUT, true);
}
}
}//end if
}catch ( CancelledKeyException ckx ) {
cancelledKey(key, SocketStatus.ERROR);
}
}//for
long prevExp = nextExpiration; //for logging purposes only
nextExpiration = System.currentTimeMillis() +
socketProperties.getTimeoutInterval();
if (log.isTraceEnabled()) {
log.trace("timeout completed: keys processed=" + keycount +
"; now=" + now + "; nextExpiration=" + prevExp +
"; keyCount=" + keyCount + "; hasEvents=" + hasEvents +
"; eval=" + ((now < prevExp) && (keyCount>0 || hasEvents) && (!close) ));
}
}
}
// ----------------------------------------------------- Key Attachment Class
public static class KeyAttachment extends SocketWrapper<NioChannel> {
public KeyAttachment(NioChannel channel) {
super(channel);
}
public void reset(Poller poller, NioChannel channel, long soTimeout) {
this.socket = channel;
this.poller = poller;
lastAccess = System.currentTimeMillis();
setComet(false);
setTimeout(soTimeout);
error = false;
sendfileData = null;
if (readLatch != null) {
try {
for (int i = 0; i < (int) readLatch.getCount(); i++) {
readLatch.countDown();
}
} catch (Exception ignore) {
}
}
readLatch = null;
if (writeLatch != null) {
try {
for (int i = 0; i < (int) writeLatch.getCount(); i++) {
writeLatch.countDown();
}
} catch (Exception ignore) {
}
}
writeLatch = null;
cometNotify = false;
sendfileData = null;
keepAliveLeft = 100;
async = false;
}
public void reset() {
reset(null,null,-1);
}
public Poller getPoller() { return poller;}
public void setPoller(Poller poller){this.poller = poller;}
public void setCometNotify(boolean notify) { this.cometNotify = notify; }
public boolean getCometNotify() { return cometNotify; }
public NioChannel getChannel() { return getSocket();}
public void setChannel(NioChannel channel) { this.socket = channel;}
public int interestOps() { return interestOps;}
public int interestOps(int ops) { this.interestOps = ops; return ops; }
public CountDownLatch getReadLatch() { return readLatch; }
public CountDownLatch getWriteLatch() { return writeLatch; }
protected CountDownLatch resetLatch(CountDownLatch latch) {
if ( latch==null || latch.getCount() == 0 ) return null;
else throw new IllegalStateException("Latch must be at count 0");
}
public void resetReadLatch() { readLatch = resetLatch(readLatch); }
public void resetWriteLatch() { writeLatch = resetLatch(writeLatch); }
protected CountDownLatch startLatch(CountDownLatch latch, int cnt) {
if ( latch == null || latch.getCount() == 0 ) {
return new CountDownLatch(cnt);
}
else throw new IllegalStateException("Latch must be at count 0 or null.");
}
public void startReadLatch(int cnt) { readLatch = startLatch(readLatch,cnt);}
public void startWriteLatch(int cnt) { writeLatch = startLatch(writeLatch,cnt);}
protected void awaitLatch(CountDownLatch latch, long timeout, TimeUnit unit) throws InterruptedException {
if ( latch == null ) throw new IllegalStateException("Latch cannot be null");
// Note: While the return value is ignored if the latch does time
// out, logic further up the call stack will trigger a
// SocketTimeoutException
latch.await(timeout,unit);
}
public void awaitReadLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(readLatch,timeout,unit);}
public void awaitWriteLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(writeLatch,timeout,unit);}
public void setSendfileData(SendfileData sf) { this.sendfileData = sf;}
public SendfileData getSendfileData() { return this.sendfileData;}
private Poller poller = null;
private int interestOps = 0;
private boolean cometNotify = false;
private CountDownLatch readLatch = null;
private CountDownLatch writeLatch = null;
private SendfileData sendfileData = null;
}
// ------------------------------------------------ Application Buffer Handler
public static class NioBufferHandler implements ApplicationBufferHandler {
private ByteBuffer readbuf = null;
private ByteBuffer writebuf = null;
public NioBufferHandler(int readsize, int writesize, boolean direct) {
if ( direct ) {
readbuf = ByteBuffer.allocateDirect(readsize);
writebuf = ByteBuffer.allocateDirect(writesize);
}else {
readbuf = ByteBuffer.allocate(readsize);
writebuf = ByteBuffer.allocate(writesize);
}
}
@Override
public ByteBuffer expand(ByteBuffer buffer, int remaining) {return buffer;}
@Override
public ByteBuffer getReadBuffer() {return readbuf;}
@Override
public ByteBuffer getWriteBuffer() {return writebuf;}
}
// ------------------------------------------------ Handler Inner Interface
/**
* Bare bones interface used for socket processing. Per thread data is to be
* stored in the ThreadWithAttributes extra folders, or alternately in
* thread local fields.
*/
public interface Handler extends AbstractEndpoint.Handler {
public SocketState process(SocketWrapper<NioChannel> socket,
SocketStatus status);
public void release(SocketWrapper<NioChannel> socket);
public void release(SocketChannel socket);
public SSLImplementation getSslImplementation();
public void onCreateSSLEngine(SSLEngine engine);
}
// ---------------------------------------------- SocketProcessor Inner Class
/**
* This class is the equivalent of the Worker, but will simply use in an
* external Executor thread pool.
*/
protected class SocketProcessor implements Runnable {
private NioChannel socket = null;
private SocketStatus status = null;
public SocketProcessor(NioChannel socket, SocketStatus status) {
reset(socket,status);
}
public void reset(NioChannel socket, SocketStatus status) {
this.socket = socket;
this.status = status;
}
@Override
public void run() {
SelectionKey key = socket.getIOChannel().keyFor(
socket.getPoller().getSelector());
KeyAttachment ka = null;
if (key != null) {
ka = (KeyAttachment)key.attachment();
}
// Upgraded connections need to allow multiple threads to access the
// connection at the same time to enable blocking IO to be used when
// NIO has been configured
if (ka != null && ka.isUpgraded() &&
SocketStatus.OPEN_WRITE == status) {
synchronized (ka.getWriteThreadLock()) {
doRun(key, ka);
}
} else {
synchronized (socket) {
doRun(key, ka);
}
}
}
private void doRun(SelectionKey key, KeyAttachment ka) {
boolean launch = false;
try {
int handshake = -1;
try {
if (key != null) {
// For STOP there is no point trying to handshake as the
// Poller has been stopped.
if (socket.isHandshakeComplete() ||
status == SocketStatus.STOP) {
handshake = 0;
} else {
handshake = socket.handshake(
key.isReadable(), key.isWritable());
// The handshake process reads/writes from/to the
// socket. status may therefore be OPEN_WRITE once
// the handshake completes. However, the handshake
// happens when the socket is opened so the status
// must always be OPEN_READ after it completes. It
// is OK to always set this as it is only used if
// the handshake completes.
status = SocketStatus.OPEN_READ;
}
}
}catch ( IOException x ) {
handshake = -1;
if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
}catch ( CancelledKeyException ckx ) {
handshake = -1;
}
if ( handshake == 0 ) {
SocketState state = SocketState.OPEN;
// Process the request from this socket
if (status == null) {
state = handler.process(ka, SocketStatus.OPEN_READ);
} else {
state = handler.process(ka, status);
}
if (state == SocketState.CLOSED) {
// Close socket and pool
try {
if (ka!=null) ka.setComet(false);
socket.getPoller().cancelledKey(key, SocketStatus.ERROR);
if (running && !paused) {
nioChannels.push(socket);
}
socket = null;
if (running && !paused && ka != null) {
keyCache.push(ka);
}
ka = null;
}catch ( Exception x ) {
log.error("",x);
}
} else if (state == SocketState.LONG && ka != null && ka.isAsync() && ka.interestOps() > 0) {
//we are async, and we are interested in operations
ka.getPoller().add(socket, ka.interestOps());
}
} else if (handshake == -1 ) {
if (key != null) {
socket.getPoller().cancelledKey(key, SocketStatus.DISCONNECT);
}
if (running && !paused) {
nioChannels.push(socket);
}
socket = null;
if (running && !paused && ka != null) {
keyCache.push(ka);
}
ka = null;
} else {
ka.getPoller().add(socket,handshake);
}
}catch(CancelledKeyException cx) {
socket.getPoller().cancelledKey(key,null);
} catch (OutOfMemoryError oom) {
try {
oomParachuteData = null;
log.error("", oom);
if (socket != null) {
socket.getPoller().cancelledKey(key,SocketStatus.ERROR);
}
releaseCaches();
}catch ( Throwable oomt ) {
try {
System.err.println(oomParachuteMsg);
oomt.printStackTrace();
}catch (Throwable letsHopeWeDontGetHere){
ExceptionUtils.handleThrowable(letsHopeWeDontGetHere);
}
}
}catch ( Throwable t ) {
log.error("",t);
if (socket != null) {
socket.getPoller().cancelledKey(key,SocketStatus.ERROR);
}
} finally {
if (launch) {
try {
getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN_READ));
} catch (NullPointerException npe) {
if (running) {
log.error(sm.getString("endpoint.launch.fail"),
npe);
}
}
}
socket = null;
status = null;
//return to cache
if (running && !paused) {
processorCache.push(this);
}
}
}
}
// ----------------------------------------------- SendfileData Inner Class
/**
* SendfileData class.
*/
public static class SendfileData {
// File
public String fileName;
public FileChannel fchannel;
public long pos;
public long length;
// KeepAlive flag
public boolean keepAlive;
}
}
|
55,287
|
Bug 55287 ServletContainerInitializer in parent classloader may not be found
|
To include the JasperInitializer in the test environment I added an entry in testclasses/META-INF/services. This is not picked up when the parent classloader is searched because this path is a directory not a JAR file. It would be picked up if the "scanAllDirectories" extension was enabled but that should not be necessary if the search is to be semantically equivalent to j.u.ServiceLoader (which does locate it).
|
resolved fixed
|
6e514c0
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-28T23:01:23Z
| 2013-07-21T23:40:00Z
|
java/org/apache/catalina/startup/ContextConfig.java
|
/*
* 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.startup;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.SessionCookieConfig;
import javax.servlet.annotation.HandlesTypes;
import org.apache.catalina.Authenticator;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Pipeline;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.Valve;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.util.ContextName;
import org.apache.catalina.util.Introspection;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.JarScanType;
import org.apache.tomcat.JarScanner;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.bcel.classfile.AnnotationElementValue;
import org.apache.tomcat.util.bcel.classfile.AnnotationEntry;
import org.apache.tomcat.util.bcel.classfile.ArrayElementValue;
import org.apache.tomcat.util.bcel.classfile.ClassFormatException;
import org.apache.tomcat.util.bcel.classfile.ClassParser;
import org.apache.tomcat.util.bcel.classfile.ElementValue;
import org.apache.tomcat.util.bcel.classfile.ElementValuePair;
import org.apache.tomcat.util.bcel.classfile.JavaClass;
import org.apache.tomcat.util.descriptor.XmlErrorHandler;
import org.apache.tomcat.util.descriptor.web.ApplicationListener;
import org.apache.tomcat.util.descriptor.web.ContextEjb;
import org.apache.tomcat.util.descriptor.web.ContextEnvironment;
import org.apache.tomcat.util.descriptor.web.ContextLocalEjb;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef;
import org.apache.tomcat.util.descriptor.web.ContextService;
import org.apache.tomcat.util.descriptor.web.ErrorPage;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.apache.tomcat.util.descriptor.web.FragmentJarScannerCallback;
import org.apache.tomcat.util.descriptor.web.JspPropertyGroup;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
import org.apache.tomcat.util.descriptor.web.MessageDestinationRef;
import org.apache.tomcat.util.descriptor.web.MultipartDef;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.util.descriptor.web.SecurityRoleRef;
import org.apache.tomcat.util.descriptor.web.ServletDef;
import org.apache.tomcat.util.descriptor.web.SessionConfig;
import org.apache.tomcat.util.descriptor.web.WebXml;
import org.apache.tomcat.util.descriptor.web.WebXmlParser;
import org.apache.tomcat.util.digester.Digester;
import org.apache.tomcat.util.digester.RuleSet;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.scan.Jar;
import org.apache.tomcat.util.scan.JarFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
/**
* Startup event listener for a <b>Context</b> that configures the properties
* of that Context, and the associated defined servlets.
*
* @author Craig R. McClanahan
* @author Jean-Francois Arcand
* @version $Id$
*/
public class ContextConfig implements LifecycleListener {
private static final Log log = LogFactory.getLog( ContextConfig.class );
private static final String SCI_LOCATION =
"META-INF/services/javax.servlet.ServletContainerInitializer";
/**
* The string resources for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
protected static final LoginConfig DUMMY_LOGIN_CONFIG =
new LoginConfig("NONE", null, null, null);
/**
* The set of Authenticators that we know how to configure. The key is
* the name of the implemented authentication method, and the value is
* the fully qualified Java class name of the corresponding Valve.
*/
protected static final Properties authenticators;
static {
// Load our mapping properties for the standard authenticators
InputStream is =
ContextConfig.class.getClassLoader().getResourceAsStream(
"org/apache/catalina/startup/Authenticators.properties");
Properties props = null;
props = new Properties();
if (is != null) {
try {
props.load(is);
} catch (IOException e) {
props = null;
}
}
authenticators = props;
}
/**
* Deployment count.
*/
protected static long deploymentCount = 0L;
/**
* Cache of default web.xml fragments per Host
*/
protected static final Map<Host,DefaultWebXmlCacheEntry> hostWebXmlCache =
new ConcurrentHashMap<>();
// ----------------------------------------------------- Instance Variables
/**
* Custom mappings of login methods to authenticators
*/
protected Map<String,Authenticator> customAuthenticators;
/**
* The Context we are associated with.
*/
protected Context context = null;
/**
* The default web application's deployment descriptor location.
*/
protected String defaultWebXml = null;
/**
* Track any fatal errors during startup configuration processing.
*/
protected boolean ok = false;
/**
* Original docBase.
*/
protected String originalDocBase = null;
/**
* Anti-locking docBase. It is a path to a copy of the web application
* in the java.io.tmpdir directory. This path is always an absolute one.
*/
private File antiLockingDocBase = null;
/**
* Map of ServletContainerInitializer to classes they expressed interest in.
*/
protected final Map<ServletContainerInitializer, Set<Class<?>>> initializerClassMap =
new LinkedHashMap<>();
/**
* Map of Types to ServletContainerInitializer that are interested in those
* types.
*/
protected final Map<Class<?>, Set<ServletContainerInitializer>> typeInitializerMap =
new HashMap<>();
/**
* Cache of JavaClass objects (byte code) by fully qualified class name.
* Only populated if it is necessary to scan the super types and interfaces
* as part of the processing for {@link HandlesTypes}.
*/
protected final Map<String,JavaClassCacheEntry> javaClassCache =
new HashMap<>();
/**
* Flag that indicates if at least one {@link HandlesTypes} entry is present
* that represents an annotation.
*/
protected boolean handlesTypesAnnotations = false;
/**
* Flag that indicates if at least one {@link HandlesTypes} entry is present
* that represents a non-annotation.
*/
protected boolean handlesTypesNonAnnotations = false;
private WebXmlParser webXmlParser;
// ------------------------------------------------------------- Properties
/**
* Return the location of the default deployment descriptor
*/
public String getDefaultWebXml() {
if( defaultWebXml == null ) {
defaultWebXml=Constants.DefaultWebXml;
}
return (this.defaultWebXml);
}
/**
* Set the location of the default deployment descriptor
*
* @param path Absolute/relative path to the default web.xml
*/
public void setDefaultWebXml(String path) {
this.defaultWebXml = path;
}
/**
* Sets custom mappings of login methods to authenticators.
*
* @param customAuthenticators Custom mappings of login methods to
* authenticators
*/
public void setCustomAuthenticators(
Map<String,Authenticator> customAuthenticators) {
this.customAuthenticators = customAuthenticators;
}
// --------------------------------------------------------- Public Methods
/**
* Process events for an associated Context.
*
* @param event The lifecycle event that has occurred
*/
@Override
public void lifecycleEvent(LifecycleEvent event) {
// Identify the context we are associated with
try {
context = (Context) event.getLifecycle();
} catch (ClassCastException e) {
log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e);
return;
}
// Process the event that has occurred
if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
configureStart();
} else if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) {
beforeStart();
} else if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) {
// Restore docBase for management tools
if (originalDocBase != null) {
context.setDocBase(originalDocBase);
}
} else if (event.getType().equals(Lifecycle.CONFIGURE_STOP_EVENT)) {
configureStop();
} else if (event.getType().equals(Lifecycle.AFTER_INIT_EVENT)) {
init();
} else if (event.getType().equals(Lifecycle.AFTER_DESTROY_EVENT)) {
destroy();
}
}
// -------------------------------------------------------- protected Methods
/**
* Process the application classes annotations, if it exists.
*/
protected void applicationAnnotationsConfig() {
long t1=System.currentTimeMillis();
WebAnnotationSet.loadApplicationAnnotations(context);
long t2=System.currentTimeMillis();
if (context instanceof StandardContext) {
((StandardContext) context).setStartupTime(t2-t1+
((StandardContext) context).getStartupTime());
}
}
/**
* Set up an Authenticator automatically if required, and one has not
* already been configured.
*/
protected void authenticatorConfig() {
LoginConfig loginConfig = context.getLoginConfig();
SecurityConstraint constraints[] = context.findConstraints();
if (context.getIgnoreAnnotations() &&
(constraints == null || constraints.length ==0) &&
!context.getPreemptiveAuthentication()) {
return;
} else {
if (loginConfig == null) {
// Not metadata-complete or security constraints present, need
// an authenticator to support @ServletSecurity annotations
// and/or constraints
loginConfig = DUMMY_LOGIN_CONFIG;
context.setLoginConfig(loginConfig);
}
}
// Has an authenticator been configured already?
if (context.getAuthenticator() != null) {
return;
}
// Has a Realm been configured for us to authenticate against?
if (context.getRealm() == null) {
log.error(sm.getString("contextConfig.missingRealm"));
ok = false;
return;
}
/*
* First check to see if there is a custom mapping for the login
* method. If so, use it. Otherwise, check if there is a mapping in
* org/apache/catalina/startup/Authenticators.properties.
*/
Valve authenticator = null;
if (customAuthenticators != null) {
authenticator = (Valve)
customAuthenticators.get(loginConfig.getAuthMethod());
}
if (authenticator == null) {
if (authenticators == null) {
log.error(sm.getString("contextConfig.authenticatorResources"));
ok = false;
return;
}
// Identify the class name of the Valve we should configure
String authenticatorName = null;
authenticatorName =
authenticators.getProperty(loginConfig.getAuthMethod());
if (authenticatorName == null) {
log.error(sm.getString("contextConfig.authenticatorMissing",
loginConfig.getAuthMethod()));
ok = false;
return;
}
// Instantiate and install an Authenticator of the requested class
try {
Class<?> authenticatorClass = Class.forName(authenticatorName);
authenticator = (Valve) authenticatorClass.newInstance();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString(
"contextConfig.authenticatorInstantiate",
authenticatorName),
t);
ok = false;
}
}
if (authenticator != null) {
Pipeline pipeline = context.getPipeline();
if (pipeline != null) {
pipeline.addValve(authenticator);
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"contextConfig.authenticatorConfigured",
loginConfig.getAuthMethod()));
}
}
}
}
/**
* Create (if necessary) and return a Digester configured to process the
* context configuration descriptor for an application.
*/
protected Digester createContextDigester() {
Digester digester = new Digester();
digester.setValidating(false);
digester.setRulesValidation(true);
HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>();
ArrayList<String> attrs = new ArrayList<>();
attrs.add("className");
fakeAttributes.put(Object.class, attrs);
digester.setFakeAttributes(fakeAttributes);
RuleSet contextRuleSet = new ContextRuleSet("", false);
digester.addRuleSet(contextRuleSet);
RuleSet namingRuleSet = new NamingRuleSet("Context/");
digester.addRuleSet(namingRuleSet);
return digester;
}
/**
* Process the default configuration file, if it exists.
*/
protected void contextConfig(Digester digester) {
String defaultContextXml = null;
// Open the default context.xml file, if it exists
if (context instanceof StandardContext) {
defaultContextXml = ((StandardContext)context).getDefaultContextXml();
}
// set the default if we don't have any overrides
if (defaultContextXml == null) {
defaultContextXml = Constants.DefaultContextXml;
}
if (!context.getOverride()) {
File defaultContextFile = new File(defaultContextXml);
if (!defaultContextFile.isAbsolute()) {
defaultContextFile =
new File(context.getCatalinaBase(), defaultContextXml);
}
if (defaultContextFile.exists()) {
try {
URL defaultContextUrl = defaultContextFile.toURI().toURL();
processContextConfig(digester, defaultContextUrl);
} catch (MalformedURLException e) {
log.error(sm.getString(
"contextConfig.badUrl", defaultContextFile), e);
}
}
File hostContextFile = new File(getHostConfigBase(), Constants.HostContextXml);
if (hostContextFile.exists()) {
try {
URL hostContextUrl = hostContextFile.toURI().toURL();
processContextConfig(digester, hostContextUrl);
} catch (MalformedURLException e) {
log.error(sm.getString(
"contextConfig.badUrl", hostContextFile), e);
}
}
}
if (context.getConfigFile() != null) {
processContextConfig(digester, context.getConfigFile());
}
}
/**
* Process a context.xml.
*/
protected void processContextConfig(Digester digester, URL contextXml) {
if (log.isDebugEnabled()) {
log.debug("Processing context [" + context.getName()
+ "] configuration file [" + contextXml + "]");
}
InputSource source = null;
InputStream stream = null;
try {
source = new InputSource(contextXml.toString());
URLConnection xmlConn = contextXml.openConnection();
xmlConn.setUseCaches(false);
stream = xmlConn.getInputStream();
} catch (Exception e) {
log.error(sm.getString("contextConfig.contextMissing",
contextXml) , e);
}
if (source == null) {
return;
}
try {
source.setByteStream(stream);
digester.setClassLoader(this.getClass().getClassLoader());
digester.setUseContextClassLoader(false);
digester.push(context.getParent());
digester.push(context);
XmlErrorHandler errorHandler = new XmlErrorHandler();
digester.setErrorHandler(errorHandler);
digester.parse(source);
if (errorHandler.getWarnings().size() > 0 ||
errorHandler.getErrors().size() > 0) {
errorHandler.logFindings(log, contextXml.toString());
ok = false;
}
if (log.isDebugEnabled()) {
log.debug("Successfully processed context [" + context.getName()
+ "] configuration file [" + contextXml + "]");
}
} catch (SAXParseException e) {
log.error(sm.getString("contextConfig.contextParse",
context.getName()), e);
log.error(sm.getString("contextConfig.defaultPosition",
"" + e.getLineNumber(),
"" + e.getColumnNumber()));
ok = false;
} catch (Exception e) {
log.error(sm.getString("contextConfig.contextParse",
context.getName()), e);
ok = false;
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
log.error(sm.getString("contextConfig.contextClose"), e);
}
}
}
/**
* Adjust docBase.
*/
protected void fixDocBase()
throws IOException {
Host host = (Host) context.getParent();
File appBase = host.getAppBaseFile();
String docBase = context.getDocBase();
if (docBase == null) {
// Trying to guess the docBase according to the path
String path = context.getPath();
if (path == null) {
return;
}
ContextName cn = new ContextName(path, context.getWebappVersion());
docBase = cn.getBaseName();
}
File file = new File(docBase);
if (!file.isAbsolute()) {
docBase = (new File(appBase, docBase)).getPath();
} else {
docBase = file.getCanonicalPath();
}
file = new File(docBase);
String origDocBase = docBase;
ContextName cn = new ContextName(context.getPath(),
context.getWebappVersion());
String pathName = cn.getBaseName();
boolean unpackWARs = true;
if (host instanceof StandardHost &&
context instanceof StandardContext) {
unpackWARs = ((StandardHost) host).isUnpackWARs() &&
((StandardContext) context).getUnpackWAR();
}
if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && unpackWARs) {
URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/");
docBase = ExpandWar.expand(host, war, pathName);
file = new File(docBase);
docBase = file.getCanonicalPath();
if (context instanceof StandardContext) {
((StandardContext) context).setOriginalDocBase(origDocBase);
}
} else if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") &&
!file.isDirectory() && !unpackWARs) {
URL war =
new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/");
ExpandWar.validate(host, war, pathName);
} else {
File docDir = new File(docBase);
if (!docDir.exists()) {
File warFile = new File(docBase + ".war");
if (warFile.exists()) {
URL war =
new URL("jar:" + warFile.toURI().toURL() + "!/");
if (unpackWARs) {
docBase = ExpandWar.expand(host, war, pathName);
file = new File(docBase);
docBase = file.getCanonicalPath();
} else {
docBase = warFile.getCanonicalPath();
ExpandWar.validate(host, war, pathName);
}
}
if (context instanceof StandardContext) {
((StandardContext) context).setOriginalDocBase(origDocBase);
}
}
}
if (docBase.startsWith(appBase.getPath() + File.separatorChar)) {
docBase = docBase.substring(appBase.getPath().length());
docBase = docBase.replace(File.separatorChar, '/');
if (docBase.startsWith("/")) {
docBase = docBase.substring(1);
}
} else {
docBase = docBase.replace(File.separatorChar, '/');
}
context.setDocBase(docBase);
}
protected void antiLocking() {
if ((context instanceof StandardContext)
&& ((StandardContext) context).getAntiResourceLocking()) {
Host host = (Host) context.getParent();
String docBase = context.getDocBase();
if (docBase == null) {
return;
}
originalDocBase = docBase;
File docBaseFile = new File(docBase);
if (!docBaseFile.isAbsolute()) {
docBaseFile = new File(host.getAppBaseFile(), docBase);
}
String path = context.getPath();
if (path == null) {
return;
}
ContextName cn = new ContextName(path, context.getWebappVersion());
docBase = cn.getBaseName();
if (originalDocBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
antiLockingDocBase = new File(
System.getProperty("java.io.tmpdir"),
deploymentCount++ + "-" + docBase + ".war");
} else {
antiLockingDocBase = new File(
System.getProperty("java.io.tmpdir"),
deploymentCount++ + "-" + docBase);
}
antiLockingDocBase = antiLockingDocBase.getAbsoluteFile();
if (log.isDebugEnabled()) {
log.debug("Anti locking context[" + context.getName()
+ "] setting docBase to " +
antiLockingDocBase.getPath());
}
// Cleanup just in case an old deployment is lying around
ExpandWar.delete(antiLockingDocBase);
if (ExpandWar.copy(docBaseFile, antiLockingDocBase)) {
context.setDocBase(antiLockingDocBase.getPath());
}
}
}
/**
* Process a "init" event for this Context.
*/
protected void init() {
// Called from StandardContext.init()
Digester contextDigester = createContextDigester();
contextDigester.getParser();
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.init"));
}
context.setConfigured(false);
ok = true;
contextConfig(contextDigester);
webXmlParser = new WebXmlParser(context.getXmlNamespaceAware(),
context.getXmlValidation());
}
/**
* Process a "before start" event for this Context.
*/
protected synchronized void beforeStart() {
try {
fixDocBase();
} catch (IOException e) {
log.error(sm.getString(
"contextConfig.fixDocBase", context.getName()), e);
}
antiLocking();
}
/**
* Process a "contextConfig" event for this Context.
*/
protected synchronized void configureStart() {
// Called from StandardContext.start()
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.start"));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.xmlSettings",
context.getName(),
Boolean.valueOf(context.getXmlValidation()),
Boolean.valueOf(context.getXmlNamespaceAware())));
}
webConfig();
if (!context.getIgnoreAnnotations()) {
applicationAnnotationsConfig();
}
if (ok) {
validateSecurityRoles();
}
// Configure an authenticator if we need one
if (ok) {
authenticatorConfig();
}
// Dump the contents of this pipeline if requested
if (log.isDebugEnabled()) {
log.debug("Pipeline Configuration:");
Pipeline pipeline = context.getPipeline();
Valve valves[] = null;
if (pipeline != null) {
valves = pipeline.getValves();
}
if (valves != null) {
for (int i = 0; i < valves.length; i++) {
log.debug(" " + valves[i].getClass().getName());
}
}
log.debug("======================");
}
// Make our application available if no problems were encountered
if (ok) {
context.setConfigured(true);
} else {
log.error(sm.getString("contextConfig.unavailable"));
context.setConfigured(false);
}
}
/**
* Process a "stop" event for this Context.
*/
protected synchronized void configureStop() {
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.stop"));
}
int i;
// Removing children
Container[] children = context.findChildren();
for (i = 0; i < children.length; i++) {
context.removeChild(children[i]);
}
// Removing application parameters
/*
ApplicationParameter[] applicationParameters =
context.findApplicationParameters();
for (i = 0; i < applicationParameters.length; i++) {
context.removeApplicationParameter
(applicationParameters[i].getName());
}
*/
// Removing security constraints
SecurityConstraint[] securityConstraints = context.findConstraints();
for (i = 0; i < securityConstraints.length; i++) {
context.removeConstraint(securityConstraints[i]);
}
// Removing Ejbs
/*
ContextEjb[] contextEjbs = context.findEjbs();
for (i = 0; i < contextEjbs.length; i++) {
context.removeEjb(contextEjbs[i].getName());
}
*/
// Removing environments
/*
ContextEnvironment[] contextEnvironments = context.findEnvironments();
for (i = 0; i < contextEnvironments.length; i++) {
context.removeEnvironment(contextEnvironments[i].getName());
}
*/
// Removing errors pages
ErrorPage[] errorPages = context.findErrorPages();
for (i = 0; i < errorPages.length; i++) {
context.removeErrorPage(errorPages[i]);
}
// Removing filter defs
FilterDef[] filterDefs = context.findFilterDefs();
for (i = 0; i < filterDefs.length; i++) {
context.removeFilterDef(filterDefs[i]);
}
// Removing filter maps
FilterMap[] filterMaps = context.findFilterMaps();
for (i = 0; i < filterMaps.length; i++) {
context.removeFilterMap(filterMaps[i]);
}
// Removing local ejbs
/*
ContextLocalEjb[] contextLocalEjbs = context.findLocalEjbs();
for (i = 0; i < contextLocalEjbs.length; i++) {
context.removeLocalEjb(contextLocalEjbs[i].getName());
}
*/
// Removing Mime mappings
String[] mimeMappings = context.findMimeMappings();
for (i = 0; i < mimeMappings.length; i++) {
context.removeMimeMapping(mimeMappings[i]);
}
// Removing parameters
String[] parameters = context.findParameters();
for (i = 0; i < parameters.length; i++) {
context.removeParameter(parameters[i]);
}
// Removing resource env refs
/*
String[] resourceEnvRefs = context.findResourceEnvRefs();
for (i = 0; i < resourceEnvRefs.length; i++) {
context.removeResourceEnvRef(resourceEnvRefs[i]);
}
*/
// Removing resource links
/*
ContextResourceLink[] contextResourceLinks =
context.findResourceLinks();
for (i = 0; i < contextResourceLinks.length; i++) {
context.removeResourceLink(contextResourceLinks[i].getName());
}
*/
// Removing resources
/*
ContextResource[] contextResources = context.findResources();
for (i = 0; i < contextResources.length; i++) {
context.removeResource(contextResources[i].getName());
}
*/
// Removing security role
String[] securityRoles = context.findSecurityRoles();
for (i = 0; i < securityRoles.length; i++) {
context.removeSecurityRole(securityRoles[i]);
}
// Removing servlet mappings
String[] servletMappings = context.findServletMappings();
for (i = 0; i < servletMappings.length; i++) {
context.removeServletMapping(servletMappings[i]);
}
// FIXME : Removing status pages
// Removing welcome files
String[] welcomeFiles = context.findWelcomeFiles();
for (i = 0; i < welcomeFiles.length; i++) {
context.removeWelcomeFile(welcomeFiles[i]);
}
// Removing wrapper lifecycles
String[] wrapperLifecycles = context.findWrapperLifecycles();
for (i = 0; i < wrapperLifecycles.length; i++) {
context.removeWrapperLifecycle(wrapperLifecycles[i]);
}
// Removing wrapper listeners
String[] wrapperListeners = context.findWrapperListeners();
for (i = 0; i < wrapperListeners.length; i++) {
context.removeWrapperListener(wrapperListeners[i]);
}
// Remove (partially) folders and files created by antiLocking
if (antiLockingDocBase != null) {
// No need to log failure - it is expected in this case
ExpandWar.delete(antiLockingDocBase, false);
}
// Reset ServletContextInitializer scanning
initializerClassMap.clear();
typeInitializerMap.clear();
ok = true;
}
/**
* Process a "destroy" event for this Context.
*/
protected synchronized void destroy() {
// Called from StandardContext.destroy()
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.destroy"));
}
// Skip clearing the work directory if Tomcat is being shutdown
Server s = getServer();
if (s != null && !s.getState().isAvailable()) {
return;
}
// Changed to getWorkPath per Bugzilla 35819.
if (context instanceof StandardContext) {
String workDir = ((StandardContext) context).getWorkPath();
if (workDir != null) {
ExpandWar.delete(new File(workDir));
}
}
}
private Server getServer() {
Container c = context;
while (c != null && !(c instanceof Engine)) {
c = c.getParent();
}
if (c == null) {
return null;
}
Service s = ((Engine)c).getService();
if (s == null) {
return null;
}
return s.getServer();
}
/**
* Validate the usage of security role names in the web application
* deployment descriptor. If any problems are found, issue warning
* messages (for backwards compatibility) and add the missing roles.
* (To make these problems fatal instead, simply set the <code>ok</code>
* instance variable to <code>false</code> as well).
*/
protected void validateSecurityRoles() {
// Check role names used in <security-constraint> elements
SecurityConstraint constraints[] = context.findConstraints();
for (int i = 0; i < constraints.length; i++) {
String roles[] = constraints[i].findAuthRoles();
for (int j = 0; j < roles.length; j++) {
if (!"*".equals(roles[j]) &&
!context.findSecurityRole(roles[j])) {
log.info(sm.getString("contextConfig.role.auth", roles[j]));
context.addSecurityRole(roles[j]);
}
}
}
// Check role names used in <servlet> elements
Container wrappers[] = context.findChildren();
for (int i = 0; i < wrappers.length; i++) {
Wrapper wrapper = (Wrapper) wrappers[i];
String runAs = wrapper.getRunAs();
if ((runAs != null) && !context.findSecurityRole(runAs)) {
log.info(sm.getString("contextConfig.role.runas", runAs));
context.addSecurityRole(runAs);
}
String names[] = wrapper.findSecurityReferences();
for (int j = 0; j < names.length; j++) {
String link = wrapper.findSecurityReference(names[j]);
if ((link != null) && !context.findSecurityRole(link)) {
log.info(sm.getString("contextConfig.role.link", link));
context.addSecurityRole(link);
}
}
}
}
protected File getHostConfigBase() {
File file = null;
if (context.getParent() instanceof Host) {
file = ((Host)context.getParent()).getConfigBaseFile();
}
return file;
}
/**
* Scan the web.xml files that apply to the web application and merge them
* using the rules defined in the spec. For the global web.xml files,
* where there is duplicate configuration, the most specific level wins. ie
* an application's web.xml takes precedence over the host level or global
* web.xml file.
*/
protected void webConfig() {
/*
* Anything and everything can override the global and host defaults.
* This is implemented in two parts
* - Handle as a web fragment that gets added after everything else so
* everything else takes priority
* - Mark Servlets as overridable so SCI configuration can replace
* configuration from the defaults
*/
/*
* The rules for annotation scanning are not as clear-cut as one might
* think. Tomcat implements the following process:
* - As per SRV.1.6.2, Tomcat will scan for annotations regardless of
* which Servlet spec version is declared in web.xml. The EG has
* confirmed this is the expected behaviour.
* - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main
* web.xml is marked as metadata-complete, JARs are still processed
* for SCIs.
* - If metadata-complete=true and an absolute ordering is specified,
* JARs excluded from the ordering are also excluded from the SCI
* processing.
* - If an SCI has a @HandlesType annotation then all classes (except
* those in JARs excluded from an absolute ordering) need to be
* scanned to check if they match.
*/
Set<WebXml> defaults = new HashSet<>();
defaults.add(getDefaultWebXmlFragment());
WebXml webXml = createWebXml();
// Parse context level web.xml
InputSource contextWebXml = getContextWebXmlSource();
if (!webXmlParser.parseWebXml(contextWebXml, webXml, false)) {
ok = false;
}
ServletContext sContext = context.getServletContext();
// Ordering is important here
// Step 1. Identify all the JARs packaged with the application and those
// provided by the container. If any of the application JARs have a
// web-fragment.xml it will be parsed at this point. web-fragment.xml
// files are ignored for container provided JARs.
Map<String,WebXml> fragments = processJarsForWebFragments();
// Step 2. Order the fragments.
Set<WebXml> orderedFragments = null;
orderedFragments =
WebXml.orderWebFragments(webXml, fragments, sContext);
// Step 3. Look for ServletContainerInitializer implementations
if (ok) {
processServletContainerInitializers(orderedFragments);
}
if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) {
// Step 4. Process /WEB-INF/classes for annotations
if (ok) {
WebResource[] webResources =
context.getResources().listResources("/WEB-INF/classes");
for (WebResource webResource : webResources) {
processAnnotationsWebResource(webResource, webXml,
webXml.isMetadataComplete());
}
}
// Step 5. Process JARs for annotations - only need to process
// those fragments we are going to use
if (ok) {
processAnnotations(
orderedFragments, webXml.isMetadataComplete());
}
// Cache, if used, is no longer required so clear it
javaClassCache.clear();
}
if (!webXml.isMetadataComplete()) {
// Step 6. Merge web-fragment.xml files into the main web.xml
// file.
if (ok) {
ok = webXml.merge(orderedFragments);
}
// Step 7. Apply global defaults
// Have to merge defaults before JSP conversion since defaults
// provide JSP servlet definition.
webXml.merge(defaults);
// Step 8. Convert explicitly mentioned jsps to servlets
if (ok) {
convertJsps(webXml);
}
// Step 9. Apply merged web.xml to Context
if (ok) {
configureContext(webXml);
}
} else {
webXml.merge(defaults);
convertJsps(webXml);
configureContext(webXml);
}
// Step 9a. Make the merged web.xml available to other
// components, specifically Jasper, to save those components
// from having to re-generate it.
// TODO Use a ServletContainerInitializer for Jasper
String mergedWebXml = webXml.toXml();
sContext.setAttribute(
org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML,
mergedWebXml);
if (context.getLogEffectiveWebXml()) {
log.info("web.xml:\n" + mergedWebXml);
}
// Always need to look for static resources
// Step 10. Look for static resources packaged in JARs
if (ok) {
// Spec does not define an order.
// Use ordered JARs followed by remaining JARs
Set<WebXml> resourceJars = new LinkedHashSet<>();
if (orderedFragments != null) {
for (WebXml fragment : orderedFragments) {
resourceJars.add(fragment);
}
}
for (WebXml fragment : fragments.values()) {
if (!resourceJars.contains(fragment)) {
resourceJars.add(fragment);
}
}
processResourceJARs(resourceJars);
// See also StandardContext.resourcesStart() for
// WEB-INF/classes/META-INF/resources configuration
}
// Step 11. Apply the ServletContainerInitializer config to the
// context
if (ok) {
for (Map.Entry<ServletContainerInitializer,
Set<Class<?>>> entry :
initializerClassMap.entrySet()) {
if (entry.getValue().isEmpty()) {
context.addServletContainerInitializer(
entry.getKey(), null);
} else {
context.addServletContainerInitializer(
entry.getKey(), entry.getValue());
}
}
}
}
private void configureContext(WebXml webxml) {
// As far as possible, process in alphabetical order so it is easy to
// check everything is present
// Some validation depends on correct public ID
context.setPublicId(webxml.getPublicId());
// Everything else in order
context.setEffectiveMajorVersion(webxml.getMajorVersion());
context.setEffectiveMinorVersion(webxml.getMinorVersion());
for (Entry<String, String> entry : webxml.getContextParams().entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
context.setDenyUncoveredHttpMethods(
webxml.getDenyUncoveredHttpMethods());
context.setDisplayName(webxml.getDisplayName());
context.setDistributable(webxml.isDistributable());
for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) {
context.getNamingResources().addLocalEjb(ejbLocalRef);
}
for (ContextEjb ejbRef : webxml.getEjbRefs().values()) {
context.getNamingResources().addEjb(ejbRef);
}
for (ContextEnvironment environment : webxml.getEnvEntries().values()) {
context.getNamingResources().addEnvironment(environment);
}
for (ErrorPage errorPage : webxml.getErrorPages().values()) {
context.addErrorPage(errorPage);
}
for (FilterDef filter : webxml.getFilters().values()) {
if (filter.getAsyncSupported() == null) {
filter.setAsyncSupported("false");
}
context.addFilterDef(filter);
}
for (FilterMap filterMap : webxml.getFilterMappings()) {
context.addFilterMap(filterMap);
}
context.setJspConfigDescriptor(webxml.getJspConfigDescriptor());
for (String listener : webxml.getListeners()) {
context.addApplicationListener(
new ApplicationListener(listener, false));
}
for (Entry<String, String> entry :
webxml.getLocaleEncodingMappings().entrySet()) {
context.addLocaleEncodingMappingParameter(entry.getKey(),
entry.getValue());
}
// Prevents IAE
if (webxml.getLoginConfig() != null) {
context.setLoginConfig(webxml.getLoginConfig());
}
for (MessageDestinationRef mdr :
webxml.getMessageDestinationRefs().values()) {
context.getNamingResources().addMessageDestinationRef(mdr);
}
// messageDestinations were ignored in Tomcat 6, so ignore here
context.setIgnoreAnnotations(webxml.isMetadataComplete());
for (Entry<String, String> entry :
webxml.getMimeMappings().entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
// Name is just used for ordering
for (ContextResourceEnvRef resource :
webxml.getResourceEnvRefs().values()) {
context.getNamingResources().addResourceEnvRef(resource);
}
for (ContextResource resource : webxml.getResourceRefs().values()) {
context.getNamingResources().addResource(resource);
}
boolean allAuthenticatedUsersIsAppRole =
webxml.getSecurityRoles().contains(
SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS);
for (SecurityConstraint constraint : webxml.getSecurityConstraints()) {
if (allAuthenticatedUsersIsAppRole) {
constraint.treatAllAuthenticatedUsersAsApplicationRole();
}
context.addConstraint(constraint);
}
for (String role : webxml.getSecurityRoles()) {
context.addSecurityRole(role);
}
for (ContextService service : webxml.getServiceRefs().values()) {
context.getNamingResources().addService(service);
}
for (ServletDef servlet : webxml.getServlets().values()) {
Wrapper wrapper = context.createWrapper();
// Description is ignored
// Display name is ignored
// Icons are ignored
// jsp-file gets passed to the JSP Servlet as an init-param
if (servlet.getLoadOnStartup() != null) {
wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue());
}
if (servlet.getEnabled() != null) {
wrapper.setEnabled(servlet.getEnabled().booleanValue());
}
wrapper.setName(servlet.getServletName());
Map<String,String> params = servlet.getParameterMap();
for (Entry<String, String> entry : params.entrySet()) {
wrapper.addInitParameter(entry.getKey(), entry.getValue());
}
wrapper.setRunAs(servlet.getRunAs());
Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs();
for (SecurityRoleRef roleRef : roleRefs) {
wrapper.addSecurityReference(
roleRef.getName(), roleRef.getLink());
}
wrapper.setServletClass(servlet.getServletClass());
MultipartDef multipartdef = servlet.getMultipartDef();
if (multipartdef != null) {
if (multipartdef.getMaxFileSize() != null &&
multipartdef.getMaxRequestSize()!= null &&
multipartdef.getFileSizeThreshold() != null) {
wrapper.setMultipartConfigElement(new MultipartConfigElement(
multipartdef.getLocation(),
Long.parseLong(multipartdef.getMaxFileSize()),
Long.parseLong(multipartdef.getMaxRequestSize()),
Integer.parseInt(
multipartdef.getFileSizeThreshold())));
} else {
wrapper.setMultipartConfigElement(new MultipartConfigElement(
multipartdef.getLocation()));
}
}
if (servlet.getAsyncSupported() != null) {
wrapper.setAsyncSupported(
servlet.getAsyncSupported().booleanValue());
}
wrapper.setOverridable(servlet.isOverridable());
context.addChild(wrapper);
}
for (Entry<String, String> entry :
webxml.getServletMappings().entrySet()) {
context.addServletMapping(entry.getKey(), entry.getValue());
}
SessionConfig sessionConfig = webxml.getSessionConfig();
if (sessionConfig != null) {
if (sessionConfig.getSessionTimeout() != null) {
context.setSessionTimeout(
sessionConfig.getSessionTimeout().intValue());
}
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
scc.setName(sessionConfig.getCookieName());
scc.setDomain(sessionConfig.getCookieDomain());
scc.setPath(sessionConfig.getCookiePath());
scc.setComment(sessionConfig.getCookieComment());
if (sessionConfig.getCookieHttpOnly() != null) {
scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue());
}
if (sessionConfig.getCookieSecure() != null) {
scc.setSecure(sessionConfig.getCookieSecure().booleanValue());
}
if (sessionConfig.getCookieMaxAge() != null) {
scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue());
}
if (sessionConfig.getSessionTrackingModes().size() > 0) {
context.getServletContext().setSessionTrackingModes(
sessionConfig.getSessionTrackingModes());
}
}
// Context doesn't use version directly
for (String welcomeFile : webxml.getWelcomeFiles()) {
/*
* The following will result in a welcome file of "" so don't add
* that to the context
* <welcome-file-list>
* <welcome-file/>
* </welcome-file-list>
*/
if (welcomeFile != null && welcomeFile.length() > 0) {
context.addWelcomeFile(welcomeFile);
}
}
// Do this last as it depends on servlets
for (JspPropertyGroup jspPropertyGroup :
webxml.getJspPropertyGroups()) {
String jspServletName = context.findServletMapping("*.jsp");
if (jspServletName == null) {
jspServletName = "jsp";
}
if (context.findChild(jspServletName) != null) {
for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
context.addServletMapping(urlPattern, jspServletName, true);
}
} else {
if(log.isDebugEnabled()) {
for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
log.debug("Skiping " + urlPattern + " , no servlet " +
jspServletName);
}
}
}
}
for (Entry<String, String> entry :
webxml.getPostConstructMethods().entrySet()) {
context.addPostConstructMethod(entry.getKey(), entry.getValue());
}
for (Entry<String, String> entry :
webxml.getPreDestroyMethods().entrySet()) {
context.addPreDestroyMethod(entry.getKey(), entry.getValue());
}
}
private WebXml getDefaultWebXmlFragment() {
// Host should never be null
Host host = (Host) context.getParent();
DefaultWebXmlCacheEntry entry = hostWebXmlCache.get(host);
InputSource globalWebXml = getGlobalWebXmlSource();
InputSource hostWebXml = getHostWebXmlSource();
long globalTimeStamp = 0;
long hostTimeStamp = 0;
if (globalWebXml != null) {
try {
URL url = new URL(globalWebXml.getSystemId());
globalTimeStamp = url.openConnection().getLastModified();
} catch (MalformedURLException e) {
globalTimeStamp = -1;
} catch (IOException e) {
globalTimeStamp = -1;
}
}
if (hostWebXml != null) {
try {
URL url = new URL(hostWebXml.getSystemId());
hostTimeStamp = url.openConnection().getLastModified();
} catch (MalformedURLException e) {
hostTimeStamp = -1;
} catch (IOException e) {
hostTimeStamp = -1;
}
}
if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp &&
entry.getHostTimeStamp() == hostTimeStamp) {
return entry.getWebXml();
}
// Parsing global web.xml is relatively expensive. Use a sync block to
// make sure it only happens once. Use the pipeline since a lock will
// already be held on the host by another thread
synchronized (host.getPipeline()) {
entry = hostWebXmlCache.get(host);
if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp &&
entry.getHostTimeStamp() == hostTimeStamp) {
return entry.getWebXml();
}
WebXml webXmlDefaultFragment = createWebXml();
webXmlDefaultFragment.setOverridable(true);
// Set to distributable else every app will be prevented from being
// distributable when the default fragment is merged with the main
// web.xml
webXmlDefaultFragment.setDistributable(true);
// When merging, the default welcome files are only used if the app has
// not defined any welcomes files.
webXmlDefaultFragment.setAlwaysAddWelcomeFiles(false);
// Parse global web.xml if present
if (globalWebXml == null) {
// This is unusual enough to log
log.info(sm.getString("contextConfig.defaultMissing"));
} else {
if (!webXmlParser.parseWebXml(
globalWebXml, webXmlDefaultFragment, false)) {
ok = false;
}
}
// Parse host level web.xml if present
// Additive apart from welcome pages
webXmlDefaultFragment.setReplaceWelcomeFiles(true);
if (!webXmlParser.parseWebXml(
hostWebXml, webXmlDefaultFragment, false)) {
ok = false;
}
// Don't update the cache if an error occurs
if (globalTimeStamp != -1 && hostTimeStamp != -1) {
entry = new DefaultWebXmlCacheEntry(webXmlDefaultFragment,
globalTimeStamp, hostTimeStamp);
hostWebXmlCache.put(host, entry);
}
return webXmlDefaultFragment;
}
}
private void convertJsps(WebXml webXml) {
Map<String,String> jspInitParams;
ServletDef jspServlet = webXml.getServlets().get("jsp");
if (jspServlet == null) {
jspInitParams = new HashMap<>();
Wrapper w = (Wrapper) context.findChild("jsp");
if (w != null) {
String[] params = w.findInitParameters();
for (String param : params) {
jspInitParams.put(param, w.findInitParameter(param));
}
}
} else {
jspInitParams = jspServlet.getParameterMap();
}
for (ServletDef servletDef: webXml.getServlets().values()) {
if (servletDef.getJspFile() != null) {
convertJsp(servletDef, jspInitParams);
}
}
}
private void convertJsp(ServletDef servletDef,
Map<String,String> jspInitParams) {
servletDef.setServletClass(org.apache.catalina.core.Constants.JSP_SERVLET_CLASS);
String jspFile = servletDef.getJspFile();
if ((jspFile != null) && !jspFile.startsWith("/")) {
if (context.isServlet22()) {
if(log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.jspFile.warning",
jspFile));
}
jspFile = "/" + jspFile;
} else {
throw new IllegalArgumentException
(sm.getString("contextConfig.jspFile.error", jspFile));
}
}
servletDef.getParameterMap().put("jspFile", jspFile);
servletDef.setJspFile(null);
for (Map.Entry<String, String> initParam: jspInitParams.entrySet()) {
servletDef.addInitParameter(initParam.getKey(), initParam.getValue());
}
}
protected WebXml createWebXml() {
return new WebXml();
}
/**
* Scan JARs for ServletContainerInitializer implementations.
* Implementations will be added in web-fragment.xml priority order.
*/
protected void processServletContainerInitializers(
Set<WebXml> fragments) {
for (WebXml fragment : fragments) {
URL url = fragment.getURL();
Jar jar = null;
InputStream is = null;
List<ServletContainerInitializer> detectedScis = null;
try {
if ("jar".equals(url.getProtocol())) {
jar = JarFactory.newInstance(url);
is = jar.getInputStream(SCI_LOCATION);
} else if ("file".equals(url.getProtocol())) {
String path = url.getPath();
File file = new File(path, SCI_LOCATION);
if (file.exists()) {
is = new FileInputStream(file);
}
}
if (is != null) {
detectedScis = getServletContainerInitializers(is);
}
} catch (IOException ioe) {
log.error(sm.getString(
"contextConfig.servletContainerInitializerFail", url,
context.getName()));
ok = false;
return;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// Ignore
}
}
if (jar != null) {
jar.close();
}
}
if (detectedScis == null) {
continue;
}
for (ServletContainerInitializer sci : detectedScis) {
initializerClassMap.put(sci, new HashSet<Class<?>>());
HandlesTypes ht = null;
try {
ht = sci.getClass().getAnnotation(HandlesTypes.class);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.info(sm.getString("contextConfig.sci.debug", url),
e);
} else {
log.info(sm.getString("contextConfig.sci.info", url));
}
}
if (ht != null) {
Class<?>[] types = ht.value();
if (types != null) {
for (Class<?> type : types) {
if (type.isAnnotation()) {
handlesTypesAnnotations = true;
} else {
handlesTypesNonAnnotations = true;
}
Set<ServletContainerInitializer> scis = typeInitializerMap
.get(type);
if (scis == null) {
scis = new HashSet<>();
typeInitializerMap.put(type, scis);
}
scis.add(sci);
}
}
}
}
}
}
/**
* Extract the name of the ServletContainerInitializer.
*
* @param is The resource where the name is defined
* @return The class name
* @throws IOException
*/
protected List<ServletContainerInitializer> getServletContainerInitializers(
InputStream is) throws IOException {
List<ServletContainerInitializer> initializers = new ArrayList<>();
if (is != null) {
String line = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() > 0) {
int i = line.indexOf('#');
if (i > -1) {
if (i == 0) {
continue;
}
line = line.substring(0, i).trim();
}
initializers.add(getServletContainerInitializer(line));
}
}
} catch (UnsupportedEncodingException e) {
// Should never happen with UTF-8
// If it does - ignore & return null
}
}
return initializers;
}
protected ServletContainerInitializer getServletContainerInitializer(
String className) throws IOException {
ServletContainerInitializer sci = null;
try {
Class<?> clazz = Class.forName(className, true, context.getLoader()
.getClassLoader());
sci = (ServletContainerInitializer) clazz.newInstance();
} catch (ClassNotFoundException e) {
log.error(sm.getString("contextConfig.invalidSci", className), e);
throw new IOException(e);
} catch (InstantiationException e) {
log.error(sm.getString("contextConfig.invalidSci", className), e);
throw new IOException(e);
} catch (IllegalAccessException e) {
log.error(sm.getString("contextConfig.invalidSci", className), e);
throw new IOException(e);
}
return sci;
}
/**
* Scan JARs that contain web-fragment.xml files that will be used to
* configure this application to see if they also contain static resources.
* If static resources are found, add them to the context. Resources are
* added in web-fragment.xml priority order.
*/
protected void processResourceJARs(Set<WebXml> fragments) {
for (WebXml fragment : fragments) {
URL url = fragment.getURL();
Jar jar = null;
try {
// Note: Ignore file URLs for now since only jar URLs will be accepted
if ("jar".equals(url.getProtocol())) {
jar = JarFactory.newInstance(url);
jar.nextEntry();
String entryName = jar.getEntryName();
while (entryName != null) {
if (entryName.startsWith("META-INF/resources/")) {
context.getResources().createWebResourceSet(
WebResourceRoot.ResourceSetType.RESOURCE_JAR,
url, "/", "/META-INF/resources");
break;
}
jar.nextEntry();
entryName = jar.getEntryName();
}
} else if ("file".equals(url.getProtocol())) {
File file = new File(url.toURI());
File resources = new File(file, "META-INF/resources/");
if (resources.isDirectory()) {
context.getResources().createWebResourceSet(
WebResourceRoot.ResourceSetType.RESOURCE_JAR,
file.getAbsolutePath(), "/", "/");
}
}
} catch (IOException ioe) {
log.error(sm.getString("contextConfig.resourceJarFail", url,
context.getName()));
} catch (URISyntaxException e) {
log.error(sm.getString("contextConfig.resourceJarFail", url,
context.getName()));
} finally {
if (jar != null) {
jar.close();
}
}
}
}
/**
* Identify the default web.xml to be used and obtain an input source for
* it.
*/
protected InputSource getGlobalWebXmlSource() {
// Is a default web.xml specified for the Context?
if (defaultWebXml == null && context instanceof StandardContext) {
defaultWebXml = ((StandardContext) context).getDefaultWebXml();
}
// Set the default if we don't have any overrides
if (defaultWebXml == null) {
getDefaultWebXml();
}
// Is it explicitly suppressed, e.g. in embedded environment?
if (Constants.NoDefaultWebXml.equals(defaultWebXml)) {
return null;
}
return getWebXmlSource(defaultWebXml,
context.getCatalinaBase().getPath());
}
/**
* Identify the host web.xml to be used and obtain an input source for
* it.
*/
protected InputSource getHostWebXmlSource() {
File hostConfigBase = getHostConfigBase();
if (hostConfigBase == null)
return null;
return getWebXmlSource(Constants.HostWebXml, hostConfigBase.getPath());
}
/**
* Identify the application web.xml to be used and obtain an input source
* for it.
*/
@SuppressWarnings("resource") // stream is meant to be left open here
protected InputSource getContextWebXmlSource() {
InputStream stream = null;
InputSource source = null;
URL url = null;
String altDDName = null;
// Open the application web.xml file, if it exists
ServletContext servletContext = context.getServletContext();
if (servletContext != null) {
altDDName = (String)servletContext.getAttribute(
Globals.ALT_DD_ATTR);
if (altDDName != null) {
try {
stream = new FileInputStream(altDDName);
url = new File(altDDName).toURI().toURL();
} catch (FileNotFoundException e) {
log.error(sm.getString("contextConfig.altDDNotFound",
altDDName));
} catch (MalformedURLException e) {
log.error(sm.getString("contextConfig.applicationUrl"));
}
}
else {
stream = servletContext.getResourceAsStream
(Constants.ApplicationWebXml);
try {
url = servletContext.getResource(
Constants.ApplicationWebXml);
} catch (MalformedURLException e) {
log.error(sm.getString("contextConfig.applicationUrl"));
}
}
}
if (stream == null || url == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.applicationMissing") + " " + context);
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
} else {
source = new InputSource(url.toExternalForm());
source.setByteStream(stream);
}
return source;
}
/**
*
* @param filename Name of the file (possibly with one or more leading path
* segments) to read
* @param path Location that filename is relative to
*/
protected InputSource getWebXmlSource(String filename, String path) {
File file = new File(filename);
if (!file.isAbsolute()) {
file = new File(path, filename);
}
InputStream stream = null;
InputSource source = null;
try {
if (!file.exists()) {
// Use getResource and getResourceAsStream
stream =
getClass().getClassLoader().getResourceAsStream(filename);
if(stream != null) {
source =
new InputSource(getClass().getClassLoader().getResource(
filename).toURI().toString());
}
} else {
source = new InputSource(file.getAbsoluteFile().toURI().toString());
stream = new FileInputStream(file);
}
if (stream != null && source != null) {
source.setByteStream(stream);
}
} catch (Exception e) {
log.error(sm.getString(
"contextConfig.defaultError", filename, file), e);
}
return source;
}
/**
* Scan /WEB-INF/lib for JARs and for each one found add it and any
* /META-INF/web-fragment.xml to the resulting Map. web-fragment.xml files
* will be parsed before being added to the map. Every JAR will be added and
* <code>null</code> will be used if no web-fragment.xml was found. Any JARs
* known not contain fragments will be skipped.
*
* @return A map of JAR name to processed web fragment (if any)
*/
protected Map<String,WebXml> processJarsForWebFragments() {
JarScanner jarScanner = context.getJarScanner();
boolean delegate = false;
if (context instanceof StandardContext) {
delegate = ((StandardContext) context).getDelegate();
}
FragmentJarScannerCallback callback =
new FragmentJarScannerCallback(webXmlParser, delegate);
jarScanner.scan(JarScanType.PLUGGABILITY,
context.getServletContext(), callback);
if (!callback.isOk()) {
ok = false;
}
return callback.getFragments();
}
protected void processAnnotations(Set<WebXml> fragments,
boolean handlesTypesOnly) {
for(WebXml fragment : fragments) {
if (fragment.getWebappJar()) {
// Only web application JARs should be scanned for deployment
// annotations
WebXml annotations = new WebXml();
// no impact on distributable
annotations.setDistributable(true);
URL url = fragment.getURL();
processAnnotationsUrl(url, annotations,
(handlesTypesOnly || fragment.isMetadataComplete()));
Set<WebXml> set = new HashSet<>();
set.add(annotations);
// Merge annotations into fragment - fragment takes priority
fragment.merge(set);
}
}
}
protected void processAnnotationsWebResource(WebResource webResource,
WebXml fragment, boolean handlesTypesOnly) {
if (webResource.isDirectory()) {
WebResource[] webResources =
webResource.getWebResourceRoot().listResources(
webResource.getWebappPath());
for (WebResource r : webResources) {
processAnnotationsWebResource(r, fragment, handlesTypesOnly);
}
} else if (webResource.isFile() &&
webResource.getName().endsWith(".class")) {
InputStream is = null;
try {
is = webResource.getInputStream();
processAnnotationsStream(is, fragment, handlesTypesOnly);
} catch (IOException e) {
log.error(sm.getString("contextConfig.inputStreamWebResource",
webResource.getWebappPath()),e);
} catch (ClassFormatException e) {
log.error(sm.getString("contextConfig.inputStreamWebResource",
webResource.getWebappPath()),e);
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
}
}
}
protected void processAnnotationsUrl(URL url, WebXml fragment,
boolean handlesTypesOnly) {
if (url == null) {
// Nothing to do.
return;
} else if ("jar".equals(url.getProtocol())) {
processAnnotationsJar(url, fragment, handlesTypesOnly);
} else if ("file".equals(url.getProtocol())) {
try {
processAnnotationsFile(
new File(url.toURI()), fragment, handlesTypesOnly);
} catch (URISyntaxException e) {
log.error(sm.getString("contextConfig.fileUrl", url), e);
}
} else {
log.error(sm.getString("contextConfig.unknownUrlProtocol",
url.getProtocol(), url));
}
}
protected void processAnnotationsJar(URL url, WebXml fragment,
boolean handlesTypesOnly) {
Jar jar = null;
InputStream is;
try {
jar = JarFactory.newInstance(url);
jar.nextEntry();
String entryName = jar.getEntryName();
while (entryName != null) {
if (entryName.endsWith(".class")) {
is = null;
try {
is = jar.getEntryInputStream();
processAnnotationsStream(
is, fragment, handlesTypesOnly);
} catch (IOException e) {
log.error(sm.getString("contextConfig.inputStreamJar",
entryName, url),e);
} catch (ClassFormatException e) {
log.error(sm.getString("contextConfig.inputStreamJar",
entryName, url),e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
jar.nextEntry();
entryName = jar.getEntryName();
}
} catch (IOException e) {
log.error(sm.getString("contextConfig.jarFile", url), e);
} finally {
if (jar != null) {
jar.close();
}
}
}
protected void processAnnotationsFile(File file, WebXml fragment,
boolean handlesTypesOnly) {
if (file.isDirectory()) {
String[] dirs = file.list();
for (String dir : dirs) {
processAnnotationsFile(
new File(file,dir), fragment, handlesTypesOnly);
}
} else if (file.canRead() && file.getName().endsWith(".class")) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
processAnnotationsStream(fis, fragment, handlesTypesOnly);
} catch (IOException e) {
log.error(sm.getString("contextConfig.inputStreamFile",
file.getAbsolutePath()),e);
} catch (ClassFormatException e) {
log.error(sm.getString("contextConfig.inputStreamFile",
file.getAbsolutePath()),e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
}
}
}
protected void processAnnotationsStream(InputStream is, WebXml fragment,
boolean handlesTypesOnly)
throws ClassFormatException, IOException {
ClassParser parser = new ClassParser(is, null);
JavaClass clazz = parser.parse();
checkHandlesTypes(clazz);
if (handlesTypesOnly) {
return;
}
String className = clazz.getClassName();
AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries();
for (AnnotationEntry ae : annotationsEntries) {
String type = ae.getAnnotationType();
if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) {
processAnnotationWebServlet(className, ae, fragment);
}else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) {
processAnnotationWebFilter(className, ae, fragment);
}else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) {
fragment.addListener(className);
} else {
// Unknown annotation - ignore
}
}
}
/**
* For classes packaged with the web application, the class and each
* super class needs to be checked for a match with {@link HandlesTypes} or
* for an annotation that matches {@link HandlesTypes}.
* @param javaClass
*/
protected void checkHandlesTypes(JavaClass javaClass) {
// Skip this if we can
if (typeInitializerMap.size() == 0) {
return;
}
if ((javaClass.getAccessFlags() &
org.apache.tomcat.util.bcel.Constants.ACC_ANNOTATION) > 0) {
// Skip annotations.
return;
}
String className = javaClass.getClassName();
Class<?> clazz = null;
if (handlesTypesNonAnnotations) {
// This *might* be match for a HandlesType.
populateJavaClassCache(className, javaClass);
JavaClassCacheEntry entry = javaClassCache.get(className);
if (entry.getSciSet() == null) {
try {
populateSCIsForCacheEntry(entry);
} catch (StackOverflowError soe) {
throw new IllegalStateException(sm.getString(
"contextConfig.annotationsStackOverflow",
context.getName(),
classHierarchyToString(className, entry)));
}
}
if (entry.getSciSet().size() > 0) {
// Need to try and load the class
clazz = Introspection.loadClass(context, className);
if (clazz == null) {
// Can't load the class so no point continuing
return;
}
for (ServletContainerInitializer sci :
entry.getSciSet()) {
Set<Class<?>> classes = initializerClassMap.get(sci);
if (classes == null) {
classes = new HashSet<>();
initializerClassMap.put(sci, classes);
}
classes.add(clazz);
}
}
}
if (handlesTypesAnnotations) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
if (entry.getKey().isAnnotation()) {
AnnotationEntry[] annotationEntries =
javaClass.getAnnotationEntries();
for (AnnotationEntry annotationEntry : annotationEntries) {
if (entry.getKey().getName().equals(
getClassName(annotationEntry.getAnnotationType()))) {
if (clazz == null) {
clazz = Introspection.loadClass(
context, className);
if (clazz == null) {
// Can't load the class so no point
// continuing
return;
}
}
for (ServletContainerInitializer sci : entry.getValue()) {
initializerClassMap.get(sci).add(clazz);
}
break;
}
}
}
}
}
}
private String classHierarchyToString(String className,
JavaClassCacheEntry entry) {
JavaClassCacheEntry start = entry;
StringBuilder msg = new StringBuilder(className);
msg.append("->");
String parentName = entry.getSuperclassName();
JavaClassCacheEntry parent = javaClassCache.get(parentName);
int count = 0;
while (count < 100 && parent != null && parent != start) {
msg.append(parentName);
msg.append("->");
count ++;
parentName = parent.getSuperclassName();
parent = javaClassCache.get(parentName);
}
msg.append(parentName);
return msg.toString();
}
private void populateJavaClassCache(String className, JavaClass javaClass) {
if (javaClassCache.containsKey(className)) {
return;
}
// Add this class to the cache
javaClassCache.put(className, new JavaClassCacheEntry(javaClass));
populateJavaClassCache(javaClass.getSuperclassName());
for (String iterface : javaClass.getInterfaceNames()) {
populateJavaClassCache(iterface);
}
}
private void populateJavaClassCache(String className) {
if (!javaClassCache.containsKey(className)) {
String name = className.replace('.', '/') + ".class";
InputStream is =
context.getLoader().getClassLoader().getResourceAsStream(name);
if (is == null) {
return;
}
ClassParser parser = new ClassParser(is, null);
try {
JavaClass clazz = parser.parse();
populateJavaClassCache(clazz.getClassName(), clazz);
} catch (ClassFormatException e) {
log.debug(sm.getString("contextConfig.invalidSciHandlesTypes",
className), e);
} catch (IOException e) {
log.debug(sm.getString("contextConfig.invalidSciHandlesTypes",
className), e);
}
}
}
private void populateSCIsForCacheEntry(JavaClassCacheEntry cacheEntry) {
Set<ServletContainerInitializer> result = new HashSet<>();
// Super class
String superClassName = cacheEntry.getSuperclassName();
JavaClassCacheEntry superClassCacheEntry =
javaClassCache.get(superClassName);
// Avoid an infinite loop with java.lang.Object
if (cacheEntry.equals(superClassCacheEntry)) {
cacheEntry.setSciSet(new HashSet<ServletContainerInitializer>());
return;
}
// May be null of the class is not present or could not be loaded.
if (superClassCacheEntry != null) {
if (superClassCacheEntry.getSciSet() == null) {
populateSCIsForCacheEntry(superClassCacheEntry);
}
result.addAll(superClassCacheEntry.getSciSet());
}
result.addAll(getSCIsForClass(superClassName));
// Interfaces
for (String interfaceName : cacheEntry.getInterfaceNames()) {
JavaClassCacheEntry interfaceEntry =
javaClassCache.get(interfaceName);
// A null could mean that the class not present in application or
// that there is nothing of interest. Either way, nothing to do here
// so move along
if (interfaceEntry != null) {
if (interfaceEntry.getSciSet() == null) {
populateSCIsForCacheEntry(interfaceEntry);
}
result.addAll(interfaceEntry.getSciSet());
}
result.addAll(getSCIsForClass(interfaceName));
}
cacheEntry.setSciSet(result);
}
private Set<ServletContainerInitializer> getSCIsForClass(String className) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
Class<?> clazz = entry.getKey();
if (!clazz.isAnnotation()) {
if (clazz.getName().equals(className)) {
return entry.getValue();
}
}
}
return Collections.emptySet();
}
private static final String getClassName(String internalForm) {
if (!internalForm.startsWith("L")) {
return internalForm;
}
// Assume starts with L, ends with ; and uses / rather than .
return internalForm.substring(1,
internalForm.length() - 1).replace('/', '.');
}
protected void processAnnotationWebServlet(String className,
AnnotationEntry ae, WebXml fragment) {
String servletName = null;
// must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81
ElementValuePair[] evps = ae.getElementValuePairs();
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("name".equals(name)) {
servletName = evp.getValue().stringifyValue();
break;
}
}
if (servletName == null) {
// classname is default servletName as annotation has no name!
servletName = className;
}
ServletDef servletDef = fragment.getServlets().get(servletName);
boolean isWebXMLservletDef;
if (servletDef == null) {
servletDef = new ServletDef();
servletDef.setServletName(servletName);
servletDef.setServletClass(className);
isWebXMLservletDef = false;
} else {
isWebXMLservletDef = true;
}
boolean urlPatternsSet = false;
String[] urlPatterns = null;
// ElementValuePair[] evps = ae.getElementValuePairs();
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("value".equals(name) || "urlPatterns".equals(name)) {
if (urlPatternsSet) {
throw new IllegalArgumentException(sm.getString(
"contextConfig.urlPatternValue", className));
}
urlPatternsSet = true;
urlPatterns = processAnnotationsStringArray(evp.getValue());
} else if ("description".equals(name)) {
if (servletDef.getDescription() == null) {
servletDef.setDescription(evp.getValue().stringifyValue());
}
} else if ("displayName".equals(name)) {
if (servletDef.getDisplayName() == null) {
servletDef.setDisplayName(evp.getValue().stringifyValue());
}
} else if ("largeIcon".equals(name)) {
if (servletDef.getLargeIcon() == null) {
servletDef.setLargeIcon(evp.getValue().stringifyValue());
}
} else if ("smallIcon".equals(name)) {
if (servletDef.getSmallIcon() == null) {
servletDef.setSmallIcon(evp.getValue().stringifyValue());
}
} else if ("asyncSupported".equals(name)) {
if (servletDef.getAsyncSupported() == null) {
servletDef.setAsyncSupported(evp.getValue()
.stringifyValue());
}
} else if ("loadOnStartup".equals(name)) {
if (servletDef.getLoadOnStartup() == null) {
servletDef
.setLoadOnStartup(evp.getValue().stringifyValue());
}
} else if ("initParams".equals(name)) {
Map<String, String> initParams = processAnnotationWebInitParams(evp
.getValue());
if (isWebXMLservletDef) {
Map<String, String> webXMLInitParams = servletDef
.getParameterMap();
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
if (webXMLInitParams.get(entry.getKey()) == null) {
servletDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
} else {
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
servletDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
}
}
if (!isWebXMLservletDef && urlPatterns != null) {
fragment.addServlet(servletDef);
}
if (urlPatterns != null) {
if (!fragment.getServletMappings().containsValue(servletName)) {
for (String urlPattern : urlPatterns) {
fragment.addServletMapping(urlPattern, servletName);
}
}
}
}
/**
* process filter annotation and merge with existing one!
* FIXME: refactoring method too long and has redundant subroutines with
* processAnnotationWebServlet!
* @param className
* @param ae
* @param fragment
*/
protected void processAnnotationWebFilter(String className,
AnnotationEntry ae, WebXml fragment) {
String filterName = null;
// must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81
ElementValuePair[] evps = ae.getElementValuePairs();
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("filterName".equals(name)) {
filterName = evp.getValue().stringifyValue();
break;
}
}
if (filterName == null) {
// classname is default filterName as annotation has no name!
filterName = className;
}
FilterDef filterDef = fragment.getFilters().get(filterName);
FilterMap filterMap = new FilterMap();
boolean isWebXMLfilterDef;
if (filterDef == null) {
filterDef = new FilterDef();
filterDef.setFilterName(filterName);
filterDef.setFilterClass(className);
isWebXMLfilterDef = false;
} else {
isWebXMLfilterDef = true;
}
boolean urlPatternsSet = false;
boolean servletNamesSet = false;
boolean dispatchTypesSet = false;
String[] urlPatterns = null;
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("value".equals(name) || "urlPatterns".equals(name)) {
if (urlPatternsSet) {
throw new IllegalArgumentException(sm.getString(
"contextConfig.urlPatternValue", className));
}
urlPatterns = processAnnotationsStringArray(evp.getValue());
urlPatternsSet = urlPatterns.length > 0;
for (String urlPattern : urlPatterns) {
filterMap.addURLPattern(urlPattern);
}
} else if ("servletNames".equals(name)) {
String[] servletNames = processAnnotationsStringArray(evp
.getValue());
servletNamesSet = servletNames.length > 0;
for (String servletName : servletNames) {
filterMap.addServletName(servletName);
}
} else if ("dispatcherTypes".equals(name)) {
String[] dispatcherTypes = processAnnotationsStringArray(evp
.getValue());
dispatchTypesSet = dispatcherTypes.length > 0;
for (String dispatcherType : dispatcherTypes) {
filterMap.setDispatcher(dispatcherType);
}
} else if ("description".equals(name)) {
if (filterDef.getDescription() == null) {
filterDef.setDescription(evp.getValue().stringifyValue());
}
} else if ("displayName".equals(name)) {
if (filterDef.getDisplayName() == null) {
filterDef.setDisplayName(evp.getValue().stringifyValue());
}
} else if ("largeIcon".equals(name)) {
if (filterDef.getLargeIcon() == null) {
filterDef.setLargeIcon(evp.getValue().stringifyValue());
}
} else if ("smallIcon".equals(name)) {
if (filterDef.getSmallIcon() == null) {
filterDef.setSmallIcon(evp.getValue().stringifyValue());
}
} else if ("asyncSupported".equals(name)) {
if (filterDef.getAsyncSupported() == null) {
filterDef
.setAsyncSupported(evp.getValue().stringifyValue());
}
} else if ("initParams".equals(name)) {
Map<String, String> initParams = processAnnotationWebInitParams(evp
.getValue());
if (isWebXMLfilterDef) {
Map<String, String> webXMLInitParams = filterDef
.getParameterMap();
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
if (webXMLInitParams.get(entry.getKey()) == null) {
filterDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
} else {
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
filterDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
}
}
if (!isWebXMLfilterDef) {
fragment.addFilter(filterDef);
if (urlPatternsSet || servletNamesSet) {
filterMap.setFilterName(filterName);
fragment.addFilterMapping(filterMap);
}
}
if (urlPatternsSet || dispatchTypesSet) {
Set<FilterMap> fmap = fragment.getFilterMappings();
FilterMap descMap = null;
for (FilterMap map : fmap) {
if (filterName.equals(map.getFilterName())) {
descMap = map;
break;
}
}
if (descMap != null) {
String[] urlsPatterns = descMap.getURLPatterns();
if (urlPatternsSet
&& (urlsPatterns == null || urlsPatterns.length == 0)) {
for (String urlPattern : filterMap.getURLPatterns()) {
descMap.addURLPattern(urlPattern);
}
}
String[] dispatcherNames = descMap.getDispatcherNames();
if (dispatchTypesSet
&& (dispatcherNames == null || dispatcherNames.length == 0)) {
for (String dis : filterMap.getDispatcherNames()) {
descMap.setDispatcher(dis);
}
}
}
}
}
protected String[] processAnnotationsStringArray(ElementValue ev) {
ArrayList<String> values = new ArrayList<>();
if (ev instanceof ArrayElementValue) {
ElementValue[] arrayValues =
((ArrayElementValue) ev).getElementValuesArray();
for (ElementValue value : arrayValues) {
values.add(value.stringifyValue());
}
} else {
values.add(ev.stringifyValue());
}
String[] result = new String[values.size()];
return values.toArray(result);
}
protected Map<String,String> processAnnotationWebInitParams(
ElementValue ev) {
Map<String, String> result = new HashMap<>();
if (ev instanceof ArrayElementValue) {
ElementValue[] arrayValues =
((ArrayElementValue) ev).getElementValuesArray();
for (ElementValue value : arrayValues) {
if (value instanceof AnnotationElementValue) {
ElementValuePair[] evps = ((AnnotationElementValue)
value).getAnnotationEntry().getElementValuePairs();
String initParamName = null;
String initParamValue = null;
for (ElementValuePair evp : evps) {
if ("name".equals(evp.getNameString())) {
initParamName = evp.getValue().stringifyValue();
} else if ("value".equals(evp.getNameString())) {
initParamValue = evp.getValue().stringifyValue();
} else {
// Ignore
}
}
result.put(initParamName, initParamValue);
}
}
}
return result;
}
private static class DefaultWebXmlCacheEntry {
private final WebXml webXml;
private final long globalTimeStamp;
private final long hostTimeStamp;
public DefaultWebXmlCacheEntry(WebXml webXml, long globalTimeStamp,
long hostTimeStamp) {
this.webXml = webXml;
this.globalTimeStamp = globalTimeStamp;
this.hostTimeStamp = hostTimeStamp;
}
public WebXml getWebXml() {
return webXml;
}
public long getGlobalTimeStamp() {
return globalTimeStamp;
}
public long getHostTimeStamp() {
return hostTimeStamp;
}
}
private static class JavaClassCacheEntry {
public final String superclassName;
public final String[] interfaceNames;
private Set<ServletContainerInitializer> sciSet = null;
public JavaClassCacheEntry(JavaClass javaClass) {
superclassName = javaClass.getSuperclassName();
interfaceNames = javaClass.getInterfaceNames();
}
public String getSuperclassName() {
return superclassName;
}
public String[] getInterfaceNames() {
return interfaceNames;
}
public Set<ServletContainerInitializer> getSciSet() {
return sciSet;
}
public void setSciSet(Set<ServletContainerInitializer> sciSet) {
this.sciSet = sciSet;
}
}
}
|
55,287
|
Bug 55287 ServletContainerInitializer in parent classloader may not be found
|
To include the JasperInitializer in the test environment I added an entry in testclasses/META-INF/services. This is not picked up when the parent classloader is searched because this path is a directory not a JAR file. It would be picked up if the "scanAllDirectories" extension was enabled but that should not be necessary if the search is to be semantically equivalent to j.u.ServiceLoader (which does locate it).
|
resolved fixed
|
6e514c0
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-28T23:01:23Z
| 2013-07-21T23:40:00Z
|
java/org/apache/catalina/startup/WebappServiceLoader.java
| |
55,287
|
Bug 55287 ServletContainerInitializer in parent classloader may not be found
|
To include the JasperInitializer in the test environment I added an entry in testclasses/META-INF/services. This is not picked up when the parent classloader is searched because this path is a directory not a JAR file. It would be picked up if the "scanAllDirectories" extension was enabled but that should not be necessary if the search is to be semantically equivalent to j.u.ServiceLoader (which does locate it).
|
resolved fixed
|
6e514c0
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-28T23:01:23Z
| 2013-07-21T23:40:00Z
|
test/org/apache/catalina/startup/TestWebappServiceLoader.java
| |
55,309
|
Bug 55309 Concurrent issue of TagPluginManager
| null |
resolved fixed
|
11c05b7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-29T20:55:45Z
| 2013-07-26T09:13:20Z
|
java/org/apache/jasper/compiler/TagPluginManager.java
|
/*
* 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.jasper.compiler;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.ServletContext;
import org.apache.jasper.JasperException;
import org.apache.jasper.compiler.tagplugin.TagPlugin;
import org.apache.jasper.compiler.tagplugin.TagPluginContext;
import org.apache.jasper.xmlparser.ParserUtils;
import org.apache.jasper.xmlparser.TreeNode;
/**
* Manages tag plugin optimizations.
* @author Kin-man Chung
*/
public class TagPluginManager {
private static final String META_INF_JASPER_TAG_PLUGINS_XML =
"META-INF/org.apache.jasper/tagPlugins.xml";
private static final String TAG_PLUGINS_XML = "/WEB-INF/tagPlugins.xml";
private static final String TAG_PLUGINS_ROOT_ELEM = "tag-plugins";
private boolean initialized = false;
private HashMap<String, TagPlugin> tagPlugins = null;
private final ServletContext ctxt;
private PageInfo pageInfo;
public TagPluginManager(ServletContext ctxt) {
this.ctxt = ctxt;
}
public void apply(Node.Nodes page, ErrorDispatcher err, PageInfo pageInfo)
throws JasperException {
init(err);
if (tagPlugins == null || tagPlugins.size() == 0) {
return;
}
this.pageInfo = pageInfo;
page.visit(new Node.Visitor() {
@Override
public void visit(Node.CustomTag n)
throws JasperException {
invokePlugin(n);
visitBody(n);
}
});
}
private void init(ErrorDispatcher err) throws JasperException {
if (initialized)
return;
tagPlugins = new HashMap<>();
Enumeration<URL> urls = null;
try {
urls = ctxt.getClassLoader().getResources(
META_INF_JASPER_TAG_PLUGINS_XML);
} catch (IOException ioe) {
throw new JasperException(ioe);
}
if (urls != null) {
while(urls.hasMoreElements()) {
URL url = urls.nextElement();
try (InputStream is = url.openStream()){
loadTagPlugins(err, is);
} catch(IOException ioe) {
throw new JasperException(ioe);
}
}
}
try (InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML)) {
if (is != null) {
loadTagPlugins(err, is);
}
} catch (IOException ioe) {
throw new JasperException(ioe);
}
initialized = true;
}
private void loadTagPlugins(ErrorDispatcher err, InputStream is)
throws JasperException {
TreeNode root =
(new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is);
if (root == null) {
return;
}
if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) {
err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML,
TAG_PLUGINS_ROOT_ELEM);
}
tagPlugins = new HashMap<>();
Iterator<TreeNode> pluginList = root.findChildren("tag-plugin");
while (pluginList.hasNext()) {
TreeNode pluginNode = pluginList.next();
TreeNode tagClassNode = pluginNode.findChild("tag-class");
if (tagClassNode == null) {
// Error
return;
}
String tagClass = tagClassNode.getBody().trim();
TreeNode pluginClassNode = pluginNode.findChild("plugin-class");
if (pluginClassNode == null) {
// Error
return;
}
String pluginClassStr = pluginClassNode.getBody();
TagPlugin tagPlugin = null;
try {
Class<?> pluginClass =
ctxt.getClassLoader().loadClass(pluginClassStr);
tagPlugin = (TagPlugin) pluginClass.newInstance();
} catch (Exception e) {
throw new JasperException(e);
}
if (tagPlugin == null) {
return;
}
tagPlugins.put(tagClass, tagPlugin);
}
initialized = true;
}
/**
* Invoke tag plugin for the given custom tag, if a plugin exists for
* the custom tag's tag handler.
*
* The given custom tag node will be manipulated by the plugin.
*/
private void invokePlugin(Node.CustomTag n) {
TagPlugin tagPlugin = tagPlugins.get(n.getTagHandlerClass().getName());
if (tagPlugin == null) {
return;
}
TagPluginContext tagPluginContext = new TagPluginContextImpl(n, pageInfo);
n.setTagPluginContext(tagPluginContext);
tagPlugin.doTag(tagPluginContext);
}
private static class TagPluginContextImpl implements TagPluginContext {
private final Node.CustomTag node;
private Node.Nodes curNodes;
private final PageInfo pageInfo;
private final HashMap<String, Object> pluginAttributes;
TagPluginContextImpl(Node.CustomTag n, PageInfo pageInfo) {
this.node = n;
this.pageInfo = pageInfo;
curNodes = new Node.Nodes();
n.setAtETag(curNodes);
curNodes = new Node.Nodes();
n.setAtSTag(curNodes);
n.setUseTagPlugin(true);
pluginAttributes = new HashMap<>();
}
@Override
public TagPluginContext getParentContext() {
Node parent = node.getParent();
if (! (parent instanceof Node.CustomTag)) {
return null;
}
return ((Node.CustomTag) parent).getTagPluginContext();
}
@Override
public void setPluginAttribute(String key, Object value) {
pluginAttributes.put(key, value);
}
@Override
public Object getPluginAttribute(String key) {
return pluginAttributes.get(key);
}
@Override
public boolean isScriptless() {
return node.getChildInfo().isScriptless();
}
@Override
public boolean isConstantAttribute(String attribute) {
Node.JspAttribute attr = getNodeAttribute(attribute);
if (attr == null)
return false;
return attr.isLiteral();
}
@Override
public String getConstantAttribute(String attribute) {
Node.JspAttribute attr = getNodeAttribute(attribute);
if (attr == null)
return null;
return attr.getValue();
}
@Override
public boolean isAttributeSpecified(String attribute) {
return getNodeAttribute(attribute) != null;
}
@Override
public String getTemporaryVariableName() {
return node.getRoot().nextTemporaryVariableName();
}
@Override
public void generateImport(String imp) {
pageInfo.addImport(imp);
}
@Override
public void generateDeclaration(String id, String text) {
if (pageInfo.isPluginDeclared(id)) {
return;
}
curNodes.add(new Node.Declaration(text, node.getStart(), null));
}
@Override
public void generateJavaSource(String sourceCode) {
curNodes.add(new Node.Scriptlet(sourceCode, node.getStart(),
null));
}
@Override
public void generateAttribute(String attributeName) {
curNodes.add(new Node.AttributeGenerator(node.getStart(),
attributeName,
node));
}
@Override
public void dontUseTagPlugin() {
node.setUseTagPlugin(false);
}
@Override
public void generateBody() {
// Since we'll generate the body anyway, this is really a nop,
// except for the fact that it lets us put the Java sources the
// plugins produce in the correct order (w.r.t the body).
curNodes = node.getAtETag();
}
@Override
public boolean isTagFile() {
return pageInfo.isTagFile();
}
private Node.JspAttribute getNodeAttribute(String attribute) {
Node.JspAttribute[] attrs = node.getJspAttributes();
for (int i=0; attrs != null && i < attrs.length; i++) {
if (attrs[i].getName().equals(attribute)) {
return attrs[i];
}
}
return null;
}
}
}
|
55,312
|
Bug 55312 No SCI scan in embedded Tomcat
|
I like the fact that SCI scanning is off by default in a Tomcat embedded instance, but I'd lik eto be able to switch it on. It might even be possible already, but the API is non-obvious. Maybe a method in Tomcat or associated friendly helper? Would also be nice in Tomcat 7.
|
resolved fixed
|
7540e90
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-31T13:13:10Z
| 2013-07-26T20:20:00Z
|
java/org/apache/tomcat/util/scan/StandardJarScanner.java
|
/*
* 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.scan;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.ServletContext;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.JarScanFilter;
import org.apache.tomcat.JarScanType;
import org.apache.tomcat.JarScanner;
import org.apache.tomcat.JarScannerCallback;
import org.apache.tomcat.util.res.StringManager;
/**
* The default {@link JarScanner} implementation scans the WEB-INF/lib directory
* followed by the provided classloader and then works up the classloader
* hierarchy. This implementation is sufficient to meet the requirements of the
* Servlet 3.0 specification as well as to provide a number of Tomcat specific
* extensions. The extensions are:
* <ul>
* <li>Scanning the classloader hierarchy (enabled by default)</li>
* <li>Testing all files to see if they are JARs (disabled by default)</li>
* <li>Testing all directories to see if they are exploded JARs
* (disabled by default)</li>
* </ul>
* All of the extensions may be controlled via configuration.
*/
public class StandardJarScanner implements JarScanner {
private static final Log log = LogFactory.getLog(StandardJarScanner.class);
/**
* The string resources for this package.
*/
private static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Controls the classpath scanning extension.
*/
private boolean scanClassPath = true;
public boolean isScanClassPath() {
return scanClassPath;
}
public void setScanClassPath(boolean scanClassPath) {
this.scanClassPath = scanClassPath;
}
/**
* Controls the testing all files to see of they are JAR files extension.
*/
private boolean scanAllFiles = false;
public boolean isScanAllFiles() {
return scanAllFiles;
}
public void setScanAllFiles(boolean scanAllFiles) {
this.scanAllFiles = scanAllFiles;
}
/**
* Controls the testing all directories to see of they are exploded JAR
* files extension.
*/
private boolean scanAllDirectories = false;
public boolean isScanAllDirectories() {
return scanAllDirectories;
}
public void setScanAllDirectories(boolean scanAllDirectories) {
this.scanAllDirectories = scanAllDirectories;
}
/**
* Controls the testing of the bootstrap classpath which consists of the
* runtime classes provided by the JVM and any installed system extensions.
*/
private boolean scanBootstrapClassPath = false;
public boolean isScanBootstrapClassPath() {
return scanBootstrapClassPath;
}
public void setScanBootstrapClassPath(boolean scanBootstrapClassPath) {
this.scanBootstrapClassPath = scanBootstrapClassPath;
}
/**
* Controls the filtering of the results from the scan for JARs
*/
private JarScanFilter jarScanFilter = new StandardJarScanFilter();
@Override
public JarScanFilter getJarScanFilter() {
return jarScanFilter;
}
@Override
public void setJarScanFilter(JarScanFilter jarScanFilter) {
this.jarScanFilter = jarScanFilter;
}
/**
* Scan the provided ServletContext and class loader for JAR files. Each JAR
* file found will be passed to the callback handler to be processed.
*
* @param scanType The type of JAR scan to perform. This is passed to
* the filter which uses it to determine how to
* filter the results
* @param context The ServletContext - used to locate and access
* WEB-INF/lib
* @param callback The handler to process any JARs found
*/
@Override
public void scan(JarScanType scanType, ServletContext context,
JarScannerCallback callback) {
if (log.isTraceEnabled()) {
log.trace(sm.getString("jarScan.webinflibStart"));
}
// Scan WEB-INF/lib
Set<String> dirList = context.getResourcePaths(Constants.WEB_INF_LIB);
if (dirList != null) {
Iterator<String> it = dirList.iterator();
while (it.hasNext()) {
String path = it.next();
if (path.endsWith(Constants.JAR_EXT) &&
jarScanFilter.check(scanType,
path.substring(path.lastIndexOf('/')+1))) {
// Need to scan this JAR
if (log.isDebugEnabled()) {
log.debug(sm.getString("jarScan.webinflibJarScan", path));
}
URL url = null;
try {
// File URLs are always faster to work with so use them
// if available.
String realPath = context.getRealPath(path);
if (realPath == null) {
url = context.getResource(path);
} else {
url = (new File(realPath)).toURI().toURL();
}
process(callback, url, true);
} catch (IOException e) {
log.warn(sm.getString("jarScan.webinflibFail", url), e);
}
} else {
if (log.isTraceEnabled()) {
log.trace(sm.getString("jarScan.webinflibJarNoScan", path));
}
}
}
}
// Scan WEB-INF/classes
if (scanAllDirectories) {
try {
URL url = context.getResource("/WEB-INF/classes/META-INF");
if (url != null) {
try {
callback.scanWebInfClasses();
} catch (IOException e) {
log.warn(sm.getString("jarScan.webinfclassesFail"), e);
}
}
} catch (MalformedURLException e) {
// Ignore
}
}
// Scan the classpath
if (scanClassPath) {
if (log.isTraceEnabled()) {
log.trace(sm.getString("jarScan.classloaderStart"));
}
ClassLoader stopLoader = null;
if (!scanBootstrapClassPath) {
// Stop when we reach the bootstrap class loader
stopLoader = ClassLoader.getSystemClassLoader().getParent();
}
ClassLoader classLoader = context.getClassLoader();
// No need to scan the web application class loader - we have
// already scanned WEB-INF/lib and WEB-INF/classes
classLoader = classLoader.getParent();
// JARs are treated as application provided until the common class
// loader is reached.
boolean isWebapp = true;
while (classLoader != null && classLoader != stopLoader) {
if (classLoader instanceof URLClassLoader) {
if (isWebapp) {
isWebapp = isWebappClassLoader(classLoader);
}
URL[] urls = ((URLClassLoader) classLoader).getURLs();
for (int i=0; i<urls.length; i++) {
// Extract the jarName if there is one to be found
String jarName = getJarName(urls[i]);
// Skip JARs known not to be interesting
if (jarName != null &&
jarScanFilter.check(scanType, jarName)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("jarScan.classloaderJarScan", urls[i]));
}
try {
process(callback, urls[i], isWebapp);
} catch (IOException ioe) {
log.warn(sm.getString(
"jarScan.classloaderFail",urls[i]), ioe);
}
} else {
if (log.isTraceEnabled()) {
log.trace(sm.getString("jarScan.classloaderJarNoScan", urls[i]));
}
}
}
}
classLoader = classLoader.getParent();
}
}
}
/*
* Since class loader hierarchies can get complicated, this method attempts
* to apply the following rule: A class loader is a web application class
* loader unless it loaded this class (StandardJarScanner) or is a parent
* of the class loader that loaded this class.
*
* This should mean:
* the webapp class loader is an application class loader
* the shared class loader is an application class loader
* the server class loader is not an application class loader
* the common class loader is not an application class loader
* the system class loader is not an application class loader
* the bootstrap class loader is not an application class loader
*/
private boolean isWebappClassLoader(ClassLoader classLoader) {
ClassLoader nonWebappLoader = StandardJarScanner.class.getClassLoader();
while (nonWebappLoader != null) {
if (nonWebappLoader == classLoader) {
return false;
}
nonWebappLoader = nonWebappLoader.getParent();
}
return true;
}
/*
* Scan a URL for JARs with the optional extensions to look at all files
* and all directories.
*/
private void process(JarScannerCallback callback, URL url, boolean isWebapp)
throws IOException {
if (log.isTraceEnabled()) {
log.trace(sm.getString("jarScan.jarUrlStart", url));
}
URLConnection conn = url.openConnection();
if (conn instanceof JarURLConnection) {
callback.scan((JarURLConnection) conn, isWebapp);
} else {
String urlStr = url.toString();
if (urlStr.startsWith("file:") || urlStr.startsWith("jndi:") ||
urlStr.startsWith("http:") || urlStr.startsWith("https:")) {
if (urlStr.endsWith(Constants.JAR_EXT)) {
URL jarURL = new URL("jar:" + urlStr + "!/");
callback.scan((JarURLConnection) jarURL.openConnection(),
isWebapp);
} else {
File f;
try {
f = new File(url.toURI());
if (f.isFile() && scanAllFiles) {
// Treat this file as a JAR
URL jarURL = new URL("jar:" + urlStr + "!/");
callback.scan(
(JarURLConnection) jarURL.openConnection(),
isWebapp);
} else if (f.isDirectory() && scanAllDirectories) {
File metainf = new File(f.getAbsoluteFile() +
File.separator + "META-INF");
if (metainf.isDirectory()) {
callback.scan(f, isWebapp);
}
}
} catch (URISyntaxException e) {
// Wrap the exception and re-throw
IOException ioe = new IOException();
ioe.initCause(e);
throw ioe;
}
}
}
}
}
/*
* Extract the JAR name, if present, from a URL
*/
private String getJarName(URL url) {
String name = null;
String path = url.getPath();
int end = path.indexOf(Constants.JAR_EXT);
if (end != -1) {
int start = path.lastIndexOf('/', end);
name = path.substring(start + 1, end + 4);
} else if (isScanAllDirectories()){
int start = path.lastIndexOf('/');
name = path.substring(start + 1);
}
return name;
}
}
|
55,316
|
Bug 55316 Ugly error log when WS client disconnects unexpectedly
|
When a WS browser client disconnects unexpectedly (e.g. in the SNake sample if the user just closes the browser or loads another page) you get ugle ERROR logs in the Tomcat server. E.g. 2013-07-27 12:04:34.424 ERROR 31847 --- [nio-8080-exec-7] org.apache.tomcat.websocket.WsSession : Failed to send close message to remote endpoint java.io.IOException: java.util.concurrent.ExecutionException: java.io.EOFException at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.startMessageBlock(WsRemoteEndpointImplBase.java:221) at org.apache.tomcat.websocket.WsSession.sendCloseMessage(WsSession.java:466) at org.apache.tomcat.websocket.WsSession.onClose(WsSession.java:430) at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.close(WsHttpUpgradeHandler.java:172) at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.access$200(WsHttpUpgradeHandler.java:45) at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:198) at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:169) at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:95) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:630) at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1585) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1543) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:724) Caused by: java.util.concurrent.ExecutionException: java.io.EOFException at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$FutureToSendHandler.get(WsRemoteEndpointImplBase.java:779) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.startMessageBlock(WsRemoteEndpointImplBase.java:217) ... 14 common frames omitted Caused by: java.io.EOFException: null at org.apache.tomcat.websocket.server.WsRemoteEndpointImplServer.doClose(WsRemoteEndpointImplServer.java:126) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.close(WsRemoteEndpointImplBase.java:531) at org.apache.tomcat.websocket.server.WsRemoteEndpointImplServer.onWritePossible(WsRemoteEndpointImplServer.java:107) at org.apache.tomcat.websocket.server.WsRemoteEndpointImplServer.doWrite(WsRemoteEndpointImplServer.java:71) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.writeMessagePart(WsRemoteEndpointImplBase.java:353) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.startMessage(WsRemoteEndpointImplBase.java:254) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.startMessageBlock(WsRemoteEndpointImplBase.java:211) ... 14 common frames omitted Presumably this is expected to be relatively normal, so I'd expect a lot less noise (and no ERROR) in the log?
|
resolved fixed
|
d370084
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-07-31T14:41:55Z
| 2013-07-27T15:46:40Z
|
java/org/apache/tomcat/websocket/WsSession.java
|
/*
* 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.websocket;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Extension;
import javax.websocket.MessageHandler;
import javax.websocket.PongMessage;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
public class WsSession implements Session {
// An ellipsis is a single character that looks like three periods in a row
// and is used to indicate a continuation.
private static final byte[] ELLIPSIS_BYTES =
"\u2026".getBytes(StandardCharsets.UTF_8);
// An ellipsis is three bytes in UTF-8
private static final int ELLIPSIS_BYTES_LEN = ELLIPSIS_BYTES.length;
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static AtomicLong ids = new AtomicLong(0);
private final Log log = LogFactory.getLog(WsSession.class);
private final Endpoint localEndpoint;
private final WsRemoteEndpointImplBase wsRemoteEndpoint;
private final RemoteEndpoint.Async remoteEndpointAsync;
private final RemoteEndpoint.Basic remoteEndpointBasic;
private final ClassLoader applicationClassLoader;
private final WsWebSocketContainer webSocketContainer;
private final URI requestUri;
private final Map<String,List<String>> requestParameterMap;
private final String queryString;
private final Principal userPrincipal;
private final EndpointConfig endpointConfig;
private final String subProtocol;
private final Map<String,String> pathParameters;
private final boolean secure;
private final String httpSessionId;
private final String id;
// Expected to handle message types of <String> only
private MessageHandler textMessageHandler = null;
// Expected to handle message types of <ByteBuffer> only
private MessageHandler binaryMessageHandler = null;
private MessageHandler.Whole<PongMessage> pongMessageHandler = null;
private volatile State state = State.OPEN;
private final Object stateLock = new Object();
private final Map<String,Object> userProperties = new ConcurrentHashMap<>();
private volatile int maxBinaryMessageBufferSize =
Constants.DEFAULT_BUFFER_SIZE;
private volatile int maxTextMessageBufferSize =
Constants.DEFAULT_BUFFER_SIZE;
private volatile long maxIdleTimeout = 0;
private volatile long lastActive = System.currentTimeMillis();
/**
* Creates a new WebSocket session for communication between the two
* provided end points. The result of {@link Thread#getContextClassLoader()}
* at the time this constructor is called will be used when calling
* {@link Endpoint#onClose(Session, CloseReason)}.
*
* @param localEndpoint
* @param wsRemoteEndpoint
* @throws DeploymentException
*/
public WsSession(Endpoint localEndpoint,
WsRemoteEndpointImplBase wsRemoteEndpoint,
WsWebSocketContainer wsWebSocketContainer,
URI requestUri, Map<String,List<String>> requestParameterMap,
String queryString, Principal userPrincipal, String httpSessionId,
String subProtocol, Map<String,String> pathParameters,
boolean secure, EndpointConfig endpointConfig)
throws DeploymentException {
this.localEndpoint = localEndpoint;
this.wsRemoteEndpoint = wsRemoteEndpoint;
this.wsRemoteEndpoint.setSession(this);
this.remoteEndpointAsync = new WsRemoteEndpointAsync(wsRemoteEndpoint);
this.remoteEndpointBasic = new WsRemoteEndpointBasic(wsRemoteEndpoint);
this.webSocketContainer = wsWebSocketContainer;
applicationClassLoader = Thread.currentThread().getContextClassLoader();
wsRemoteEndpoint.setSendTimeout(
wsWebSocketContainer.getDefaultAsyncSendTimeout());
this.maxBinaryMessageBufferSize =
webSocketContainer.getDefaultMaxBinaryMessageBufferSize();
this.maxTextMessageBufferSize =
webSocketContainer.getDefaultMaxTextMessageBufferSize();
this.maxIdleTimeout =
webSocketContainer.getDefaultMaxSessionIdleTimeout();
this.requestUri = requestUri;
if (requestParameterMap == null) {
this.requestParameterMap = Collections.EMPTY_MAP;
} else {
this.requestParameterMap = requestParameterMap;
}
this.queryString = queryString;
this.userPrincipal = userPrincipal;
this.httpSessionId = httpSessionId;
if (subProtocol == null) {
this.subProtocol = "";
} else {
this.subProtocol = subProtocol;
}
this.pathParameters = pathParameters;
this.secure = secure;
this.wsRemoteEndpoint.setEncoders(endpointConfig);
this.endpointConfig = endpointConfig;
this.userProperties.putAll(endpointConfig.getUserProperties());
this.id = Long.toHexString(ids.getAndIncrement());
}
@Override
public WebSocketContainer getContainer() {
checkState();
return webSocketContainer;
}
@SuppressWarnings("unchecked")
@Override
public void addMessageHandler(MessageHandler listener) {
checkState();
// Message handlers that require decoders may map to text messages,
// binary messages, both or neither.
// The frame processing code expects binary message handlers to
// accept ByteBuffer
// Use the POJO message handler wrappers as they are designed to wrap
// arbitrary objects with MessageHandlers and can wrap MessageHandlers
// just as easily.
Set<MessageHandlerResult> mhResults =
Util.getMessageHandlers(listener, endpointConfig);
for (MessageHandlerResult mhResult : mhResults) {
switch (mhResult.getType()) {
case TEXT: {
if (textMessageHandler != null) {
throw new IllegalStateException(
sm.getString("wsSession.duplicateHandlerText"));
}
textMessageHandler = mhResult.getHandler();
break;
}
case BINARY: {
if (binaryMessageHandler != null) {
throw new IllegalStateException(
sm.getString("wsSession.duplicateHandlerBinary"));
}
binaryMessageHandler = mhResult.getHandler();
break;
}
case PONG: {
if (pongMessageHandler != null) {
throw new IllegalStateException(
sm.getString("wsSession.duplicateHandlerPong"));
}
MessageHandler handler = mhResult.getHandler();
if (handler instanceof MessageHandler.Whole<?>) {
pongMessageHandler =
(MessageHandler.Whole<PongMessage>) handler;
} else {
throw new IllegalStateException(
sm.getString("wsSession.invalidHandlerTypePong"));
}
break;
}
default: {
throw new IllegalArgumentException(sm.getString(
"wsSession.unknownHandlerType", listener,
mhResult.getType()));
}
}
}
}
@Override
public Set<MessageHandler> getMessageHandlers() {
checkState();
Set<MessageHandler> result = new HashSet<>();
if (binaryMessageHandler != null) {
result.add(binaryMessageHandler);
}
if (textMessageHandler != null) {
result.add(textMessageHandler);
}
if (pongMessageHandler != null) {
result.add(pongMessageHandler);
}
return result;
}
@Override
public void removeMessageHandler(MessageHandler listener) {
checkState();
if (listener == null) {
return;
}
MessageHandler wrapped = null;
if (listener instanceof WrappedMessageHandler) {
wrapped = ((WrappedMessageHandler) listener).getWrappedHandler();
}
if (wrapped == null) {
wrapped = listener;
}
boolean removed = false;
if (wrapped.equals(textMessageHandler) ||
listener.equals(textMessageHandler)) {
textMessageHandler = null;
removed = true;
}
if (listener.equals(binaryMessageHandler) ||
listener.equals(binaryMessageHandler)) {
binaryMessageHandler = null;
removed = true;
}
if (listener.equals(pongMessageHandler) ||
listener.equals(pongMessageHandler)) {
pongMessageHandler = null;
removed = true;
}
if (!removed) {
// ISE for now. Could swallow this silently / log this if the ISE
// becomes a problem
throw new IllegalStateException(
sm.getString("wsSession.removeHandlerFailed", listener));
}
}
@Override
public String getProtocolVersion() {
checkState();
return Constants.WS_VERSION_HEADER_VALUE;
}
@Override
public String getNegotiatedSubprotocol() {
checkState();
return subProtocol;
}
@Override
public List<Extension> getNegotiatedExtensions() {
checkState();
return Collections.EMPTY_LIST;
}
@Override
public boolean isSecure() {
checkState();
return secure;
}
@Override
public boolean isOpen() {
return state == State.OPEN;
}
@Override
public long getMaxIdleTimeout() {
checkState();
return maxIdleTimeout;
}
@Override
public void setMaxIdleTimeout(long timeout) {
checkState();
this.maxIdleTimeout = timeout;
}
@Override
public void setMaxBinaryMessageBufferSize(int max) {
checkState();
this.maxBinaryMessageBufferSize = max;
}
@Override
public int getMaxBinaryMessageBufferSize() {
checkState();
return maxBinaryMessageBufferSize;
}
@Override
public void setMaxTextMessageBufferSize(int max) {
checkState();
this.maxTextMessageBufferSize = max;
}
@Override
public int getMaxTextMessageBufferSize() {
checkState();
return maxTextMessageBufferSize;
}
@Override
public Set<Session> getOpenSessions() {
checkState();
return webSocketContainer.getOpenSessions(localEndpoint.getClass());
}
@Override
public RemoteEndpoint.Async getAsyncRemote() {
checkState();
return remoteEndpointAsync;
}
@Override
public RemoteEndpoint.Basic getBasicRemote() {
checkState();
return remoteEndpointBasic;
}
@Override
public void close() throws IOException {
close(new CloseReason(CloseCodes.NORMAL_CLOSURE, ""));
}
@Override
public void close(CloseReason closeReason) throws IOException {
doClose(closeReason, closeReason);
}
/**
* WebSocket 1.0. Section 2.1.5.
* Need internal close method as spec requires that the local endpoint
* receives a 1006 on timeout.
*/
private void doClose(CloseReason closeReasonMessage,
CloseReason closeReasonLocal) {
// Double-checked locking. OK because state is volatile
if (state != State.OPEN) {
return;
}
synchronized (stateLock) {
if (state != State.OPEN) {
return;
}
state = State.CLOSING;
sendCloseMessage(closeReasonMessage);
fireEndpointOnClose(closeReasonLocal);
state = State.CLOSED;
}
}
/**
* Called when a close message is received. Should only ever happen once.
* Also called after a protocol error when the ProtocolHandler needs to
* force the closing of the connection.
*/
public void onClose(CloseReason closeReason) {
synchronized (stateLock) {
if (state == State.OPEN) {
sendCloseMessage(closeReason);
fireEndpointOnClose(closeReason);
state = State.CLOSED;
}
// Close the socket
wsRemoteEndpoint.close();
}
}
private void fireEndpointOnClose(CloseReason closeReason) {
// Fire the onClose event
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
localEndpoint.onClose(this, closeReason);
} finally {
t.setContextClassLoader(cl);
}
}
private void sendCloseMessage(CloseReason closeReason) {
// 125 is maximum size for the payload of a control message
ByteBuffer msg = ByteBuffer.allocate(125);
msg.putShort((short) closeReason.getCloseCode().getCode());
String reason = closeReason.getReasonPhrase();
if (reason != null && reason.length() > 0) {
appendCloseReasonWithTruncation(msg, reason);
}
msg.flip();
try {
wsRemoteEndpoint.startMessageBlock(
Constants.OPCODE_CLOSE, msg, true);
} catch (IOException ioe) {
// Failed to send close message. Close the socket and let the caller
// deal with the Exception
log.error(sm.getString("wsSession.sendCloseFail"), ioe);
wsRemoteEndpoint.close();
localEndpoint.onError(this, ioe);
} finally {
webSocketContainer.unregisterSession(localEndpoint, this);
}
}
/**
* Use protected so unit tests can access this method directly.
*/
protected static void appendCloseReasonWithTruncation(ByteBuffer msg,
String reason) {
// Once the close code has been added there are a maximum of 123 bytes
// left for the reason phrase. If it is truncated then care needs to be
// taken to ensure the bytes are not truncated in the middle of a
// multi-byte UTF-8 character.
byte[] reasonBytes = reason.getBytes(StandardCharsets.UTF_8);
if (reasonBytes.length <= 123) {
// No need to truncate
msg.put(reasonBytes);
} else {
// Need to truncate
int remaining = 123 - ELLIPSIS_BYTES_LEN;
int pos = 0;
byte[] bytesNext = reason.substring(pos, pos + 1).getBytes(
StandardCharsets.UTF_8);
while (remaining >= bytesNext.length) {
msg.put(bytesNext);
remaining -= bytesNext.length;
pos++;
bytesNext = reason.substring(pos, pos + 1).getBytes(
StandardCharsets.UTF_8);
}
msg.put(ELLIPSIS_BYTES);
}
}
@Override
public URI getRequestURI() {
checkState();
return requestUri;
}
@Override
public Map<String,List<String>> getRequestParameterMap() {
checkState();
return requestParameterMap;
}
@Override
public String getQueryString() {
checkState();
return queryString;
}
@Override
public Principal getUserPrincipal() {
checkState();
return userPrincipal;
}
@Override
public Map<String,String> getPathParameters() {
checkState();
return pathParameters;
}
@Override
public String getId() {
return id;
}
@Override
public Map<String,Object> getUserProperties() {
checkState();
return userProperties;
}
public Endpoint getLocal() {
return localEndpoint;
}
public String getHttpSessionId() {
return httpSessionId;
}
protected MessageHandler getTextMessageHandler() {
return textMessageHandler;
}
protected MessageHandler getBinaryMessageHandler() {
return binaryMessageHandler;
}
protected MessageHandler.Whole<PongMessage> getPongMessageHandler() {
return pongMessageHandler;
}
protected void updateLastActive() {
lastActive = System.currentTimeMillis();
}
protected void expire() {
long timeout = maxIdleTimeout;
if (timeout < 1) {
return;
}
if (System.currentTimeMillis() - lastActive > timeout) {
String msg = sm.getString("wsSession.timeout");
doClose(new CloseReason(CloseCodes.GOING_AWAY, msg),
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
}
}
private void checkState() {
if (state == State.CLOSED) {
throw new IllegalStateException(sm.getString("wsSession.closed"));
}
}
private static enum State {
OPEN,
CLOSING,
CLOSED
}
}
|
55,333
|
Bug 55333 JDBCRealm Digest authentication Flow is not working throws Function sequence error
|
Issue: Digest authentication flow is not working Error Thrown : Function sequence error PackageName: org.apache.catalina.realm ClassName : JDBCRealm MethodName: String getPassword(String username) Snapshot from above mentioned method =================================== stmt = credentials(dbConnection, username); rs = stmt.executeQuery(); // Due to this connection commit, resultset is nullified dbConnection.commit(); // While executing this statement it throws Function sequence error if (rs.next()) { dbCredentials = rs.getString(1); } =================================== Above explanation has been validate by placing 7.0.41 catalina.jar where the above changes are not there due to fix of 55071 bug Below snapshot is the error observed while trying for Digest authentication ========================================================================== Jul 31, 2013 3:43:40 PM org.apache.catalina.realm.JDBCRealm getPassword SEVERE: Exception performing authentication java.sql.SQLException: [TimesTen][TimesTen 11.2.2.5.0 ODBC Driver]Function sequence error at com.timesten.jdbc.JdbcOdbc.createSQLException(JdbcOdbc.java:3238) at com.timesten.jdbc.JdbcOdbc.standardError(JdbcOdbc.java:3387) at com.timesten.jdbc.JdbcOdbc.SQLFetch(JdbcOdbc.java:921) at com.timesten.jdbc.JdbcOdbcResultSet.next(JdbcOdbcResultSet.java:409) at org.apache.catalina.realm.JDBCRealm.getPassword(JDBCRealm.java:558) at org.apache.catalina.realm.RealmBase.getDigest(RealmBase.java:1189) at org.apache.catalina.realm.RealmBase.authenticate(RealmBase.java:409) at com.kodiak.digest.authentication.KnDigestAuthenticator$KnDigestInfo.authenticate(KnDigestAuthenticator.java:733) at com.kodiak.digest.authentication.KnDigestAuthenticator.authenticate(KnDigestAuthenticator.java:275) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:574) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:724) Jul 31, 2013 3:43:40 PM org.apache.catalina.realm.JDBCRealm getPassword SEVERE: Exception performing authentication java.sql.SQLException: [TimesTen][TimesTen 11.2.2.5.0 ODBC Driver]Function sequence error at com.timesten.jdbc.JdbcOdbc.createSQLException(JdbcOdbc.java:3238) at com.timesten.jdbc.JdbcOdbc.standardError(JdbcOdbc.java:3387) at com.timesten.jdbc.JdbcOdbc.SQLFetch(JdbcOdbc.java:921) at com.timesten.jdbc.JdbcOdbcResultSet.next(JdbcOdbcResultSet.java:409) at org.apache.catalina.realm.JDBCRealm.getPassword(JDBCRealm.java:558) at org.apache.catalina.realm.RealmBase.getDigest(RealmBase.java:1189) at org.apache.catalina.realm.RealmBase.authenticate(RealmBase.java:409) "localhost.2013-07-31.log" 50L, 3800C Cheers, Mahaaboob
|
resolved fixed
|
6cd42af
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-01T10:13:31Z
| 2013-07-31T22:33:20Z
|
java/org/apache/catalina/realm/JDBCRealm.java
|
/*
* 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.tomcat.util.ExceptionUtils;
/**
*
* Implementation 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>For a <b>Realm</b> implementation that supports connection pooling and
* doesn't require synchronisation of <code>authenticate()</code>,
* <code>getPassword()</code>, <code>roles()</code> and
* <code>getPrincipal()</code> or the ugly connection logic use the
* <code>DataSourceRealm</code>.</p>
*
* @author Craig R. McClanahan
* @author Carson McDonald
* @author Ignacio Ortega
* @version $Id$
*/
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 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 column in the user table that holds the user's credentials
*/
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
*/
@Override
public synchronized Principal authenticate(String username, String credentials) {
// Number of tries is the number of attempts to connect to the database
// during this login attempt (if we need to open the database)
// This needs rewritten with 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
*/
public synchronized Principal authenticate(Connection dbConnection,
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;
}
// 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<String> roles = getRoles(username);
// Create and return a suitable Principal for this user
return (new GenericPrincipal(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) {
ExceptionUtils.handleThrowable(f);
}
this.preparedCredentials = null;
try {
preparedRoles.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(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.
*/
@Override
protected String getName() {
return (name);
}
/**
* Return the password associated with the given principal's user name.
*/
@Override
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 number of attempts to connect to the database
// during this login attempt (if we need to open the database)
// This needs rewritten with 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();
stmt = credentials(dbConnection, username);
rs = stmt.executeQuery();
dbConnection.commit();
if (rs.next()) {
dbCredentials = rs.getString(1);
}
if (dbCredentials != null) {
dbCredentials = dbCredentials.trim();
}
return dbCredentials;
} catch (SQLException e) {
// Log the problem for posterity
containerLog.error(sm.getString("jdbcRealm.exception"), e);
} finally {
if (rs != null) {
try {
rs.close();
} catch(SQLException e) {
containerLog.warn(sm.getString(
"jdbcRealm.abnormalCloseResultSet"));
}
}
}
// 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.
*/
@Override
protected synchronized Principal getPrincipal(String username) {
return (new GenericPrincipal(username,
getPassword(username),
getRoles(username)));
}
/**
* Return the roles associated with the gven user name.
*/
protected ArrayList<String> getRoles(String username) {
if (allRolesMode != AllRolesMode.STRICT_MODE && !isRoleStoreDefined()) {
// Using an authentication only configuration and no role store has
// been defined so don't spend cycles looking
return null;
}
PreparedStatement stmt = null;
ResultSet rs = null;
// Number of tries is the number 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<String> 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) {
ExceptionUtils.handleThrowable(e);
throw new SQLException(e.getMessage(), e);
}
}
// 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);
}
/**
* 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);
}
private boolean isRoleStoreDefined() {
return userRoleTable != null || roleNameCol != null;
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Prepare for the beginning of active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected void startInternal() throws LifecycleException {
// 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);
}
super.startInternal();
}
/**
* Gracefully terminate the active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
super.stopInternal();
// Close any open DB connection
close(this.dbConnection);
}
}
|
55,345
|
Bug 55345 Webresources class AbstractResourceSet throws exception upon callong ServletContext.getRealPath("")
|
As described on user list: Tomcat 8, unlike Tomcat 7.0.42, throws IllegalArgumentException upon calling ServletContext.getRealPath(""). It seems that TC8 expects that argument provided to getRealPath is non-empty string. I believe that ServletContext.getRealPath should allow empty string as argument. -Ognjen Stack trace: [ERROR] java.lang.IllegalArgumentException java.lang.IllegalArgumentException at org.apache.catalina.webresources.AbstractResourceSet.checkPath(AbstractResourceSet.java:39) at org.apache.catalina.webresources.DirResourceSet.getResource(DirResourceSet.java:91) at org.apache.catalina.webresources.StandardRoot.getResourceInternal(StandardRoot.java:176) at org.apache.catalina.webresources.CachedResource.validate(CachedResource.java:62) at org.apache.catalina.webresources.Cache.getResource(Cache.java:78) at org.apache.catalina.webresources.StandardRoot.getResource(StandardRoot.java:163) at org.apache.catalina.core.StandardContext.getRealPath(StandardContext.java:4528) at org.apache.catalina.core.ApplicationContext.getRealPath(ApplicationContext.java:398) at org.apache.catalina.core.ApplicationContextFacade.getRealPath(ApplicationContextFacade.java:335) at org.apache.axis2.deployment.WarBasedAxisConfigurator.<init>(WarBasedAxisConfigurator.java:103) at org.apache.axis2.transport.http.AxisServlet.initConfigContext(AxisServlet.java:584) at org.apache.axis2.transport.http.AxisServlet.init(AxisServlet.java:454) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1235) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1148) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1044) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5025) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:702) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:698) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:968) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1742) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:724)
|
closed fixed
|
aa15bac
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-02T20:05:43Z
| 2013-08-02T16:13:20Z
|
java/org/apache/catalina/core/StandardContext.java
|
/*
* 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.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.FilterRegistration;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.ServletSecurityElement;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import org.apache.catalina.Authenticator;
import org.apache.catalina.Cluster;
import org.apache.catalina.Container;
import org.apache.catalina.ContainerListener;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.InstanceListener;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Loader;
import org.apache.catalina.Manager;
import org.apache.catalina.Pipeline;
import org.apache.catalina.Realm;
import org.apache.catalina.Valve;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.Wrapper;
import org.apache.catalina.deploy.NamingResourcesImpl;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.session.StandardManager;
import org.apache.catalina.startup.TldConfig;
import org.apache.catalina.util.CharsetMapper;
import org.apache.catalina.util.ContextName;
import org.apache.catalina.util.ExtensionValidator;
import org.apache.catalina.util.URLEncoder;
import org.apache.catalina.webresources.StandardRoot;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.naming.ContextBindings;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.JarScanner;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.buf.UDecoder;
import org.apache.tomcat.util.descriptor.XmlIdentifiers;
import org.apache.tomcat.util.descriptor.web.ApplicationListener;
import org.apache.tomcat.util.descriptor.web.ApplicationParameter;
import org.apache.tomcat.util.descriptor.web.ErrorPage;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.apache.tomcat.util.descriptor.web.Injectable;
import org.apache.tomcat.util.descriptor.web.InjectionTarget;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
import org.apache.tomcat.util.descriptor.web.MessageDestination;
import org.apache.tomcat.util.descriptor.web.MessageDestinationRef;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.util.scan.StandardJarScanner;
/**
* Standard implementation of the <b>Context</b> interface. Each
* child container must be a Wrapper implementation to process the
* requests directed to a particular servlet.
*
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Id$
*/
public class StandardContext extends ContainerBase
implements Context, NotificationEmitter {
private static final Log log = LogFactory.getLog(StandardContext.class);
// ----------------------------------------------------------- Constructors
/**
* Create a new StandardContext component with the default basic Valve.
*/
public StandardContext() {
super();
pipeline.setBasic(new StandardContextValve());
broadcaster = new NotificationBroadcasterSupport();
// Set defaults
if (!Globals.STRICT_SERVLET_COMPLIANCE) {
// Strict servlet compliance requires all extension mapped servlets
// to be checked against welcome files
resourceOnlyServlets.add("jsp");
}
}
// ----------------------------------------------------- Class Variables
/**
* Array containing the safe characters set.
*/
protected static URLEncoder urlEncoder;
/**
* GMT timezone - all HTTP dates are on GMT
*/
static {
urlEncoder = new URLEncoder();
urlEncoder.addSafeCharacter('~');
urlEncoder.addSafeCharacter('-');
urlEncoder.addSafeCharacter('_');
urlEncoder.addSafeCharacter('.');
urlEncoder.addSafeCharacter('*');
urlEncoder.addSafeCharacter('/');
}
// ----------------------------------------------------- Instance Variables
/**
* Allow multipart/form-data requests to be parsed even when the
* target servlet doesn't specify @MultipartConfig or have a
* <multipart-config> element.
*/
protected boolean allowCasualMultipartParsing = false;
/**
* Control whether remaining request data will be read
* (swallowed) even if the request violates a data size constraint.
*/
private boolean swallowAbortedUploads = true;
/**
* The alternate deployment descriptor name.
*/
private String altDDName = null;
/**
* Lifecycle provider.
*/
private InstanceManager instanceManager = null;
/**
* The antiJARLocking flag for this Context.
*/
private boolean antiJARLocking = false;
/**
* The antiResourceLocking flag for this Context.
*/
private boolean antiResourceLocking = false;
/**
* The set of application listener class names configured for this
* application, in the order they were encountered in the resulting merged
* web.xml file.
*/
private ApplicationListener applicationListeners[] =
new ApplicationListener[0];
private final Object applicationListenersLock = new Object();
/**
* The set of instantiated application event listener objects. Note that
* SCIs and other code may use the pluggability APIs to add listener
* instances directly to this list before the application starts.
*/
private Object applicationEventListenersObjects[] =
new Object[0];
/**
* The set of instantiated application lifecycle listener objects. Note that
* SCIs and other code may use the pluggability APIs to add listener
* instances directly to this list before the application starts.
*/
private Object applicationLifecycleListenersObjects[] =
new Object[0];
/**
* The ordered set of ServletContainerInitializers for this web application.
*/
private Map<ServletContainerInitializer,Set<Class<?>>> initializers =
new LinkedHashMap<>();
/**
* The set of application parameters defined for this application.
*/
private ApplicationParameter applicationParameters[] =
new ApplicationParameter[0];
private final Object applicationParametersLock = new Object();
/**
* The broadcaster that sends j2ee notifications.
*/
private NotificationBroadcasterSupport broadcaster = null;
/**
* The Locale to character set mapper for this application.
*/
private CharsetMapper charsetMapper = null;
/**
* The Java class name of the CharsetMapper class to be created.
*/
private String charsetMapperClass =
"org.apache.catalina.util.CharsetMapper";
/**
* The URL of the XML descriptor for this context.
*/
private URL configFile = null;
/**
* The "correctly configured" flag for this Context.
*/
private boolean configured = false;
/**
* The security constraints for this web application.
*/
private volatile SecurityConstraint constraints[] =
new SecurityConstraint[0];
private final Object constraintsLock = new Object();
/**
* The ServletContext implementation associated with this Context.
*/
protected ApplicationContext context = null;
/**
* Should we attempt to use cookies for session id communication?
*/
private boolean cookies = true;
/**
* Should we allow the <code>ServletContext.getContext()</code> method
* to access the context of other web applications in this server?
*/
private boolean crossContext = false;
/**
* Encoded path.
*/
private String encodedPath = null;
/**
* Unencoded path for this web application.
*/
private String path = null;
/**
* The "follow standard delegation model" flag that will be used to
* configure our ClassLoader.
*/
private boolean delegate = false;
private boolean denyUncoveredHttpMethods;
/**
* The display name of this web application.
*/
private String displayName = null;
/**
* Override the default context xml location.
*/
private String defaultContextXml;
/**
* Override the default web xml location.
*/
private String defaultWebXml;
/**
* The distributable flag for this web application.
*/
private boolean distributable = false;
/**
* The document root for this web application.
*/
private String docBase = null;
/**
* The exception pages for this web application, keyed by fully qualified
* class name of the Java exception.
*/
private HashMap<String, ErrorPage> exceptionPages = new HashMap<>();
/**
* The set of filter configurations (and associated filter instances) we
* have initialized, keyed by filter name.
*/
private HashMap<String, ApplicationFilterConfig> filterConfigs =
new HashMap<>();
/**
* The set of filter definitions for this application, keyed by
* filter name.
*/
private HashMap<String, FilterDef> filterDefs = new HashMap<>();
/**
* The set of filter mappings for this application, in the order
* they were defined in the deployment descriptor with additional mappings
* added via the {@link ServletContext} possibly both before and after those
* defined in the deployment descriptor.
*/
private final ContextFilterMaps filterMaps = new ContextFilterMaps();
/**
* Ignore annotations.
*/
private boolean ignoreAnnotations = false;
/**
* The set of classnames of InstanceListeners that will be added
* to each newly created Wrapper by <code>createWrapper()</code>.
*/
private String instanceListeners[] = new String[0];
private final Object instanceListenersLock = new Object();
/**
* The Loader implementation with which this Container is associated.
*/
private Loader loader = null;
private final ReadWriteLock loaderLock = new ReentrantReadWriteLock();
/**
* The login configuration descriptor for this web application.
*/
private LoginConfig loginConfig = null;
/**
* The Manager implementation with which this Container is associated.
*/
protected Manager manager = null;
private final ReadWriteLock managerLock = new ReentrantReadWriteLock();
/**
* The naming context listener for this web application.
*/
private NamingContextListener namingContextListener = null;
/**
* The naming resources for this web application.
*/
private NamingResourcesImpl namingResources = null;
/**
* The message destinations for this web application.
*/
private HashMap<String, MessageDestination> messageDestinations =
new HashMap<>();
/**
* The MIME mappings for this web application, keyed by extension.
*/
private HashMap<String, String> mimeMappings = new HashMap<>();
/**
* The context initialization parameters for this web application,
* keyed by name.
*/
private HashMap<String, String> parameters = new HashMap<>();
/**
* The request processing pause flag (while reloading occurs)
*/
private boolean paused = false;
/**
* The public identifier of the DTD for the web application deployment
* descriptor version we are currently parsing. This is used to support
* relaxed validation rules when processing version 2.2 web.xml files.
*/
private String publicId = null;
/**
* The reloadable flag for this web application.
*/
private boolean reloadable = false;
/**
* Unpack WAR property.
*/
private boolean unpackWAR = true;
/**
* Context level override for default {@link StandardHost#isCopyXML()}.
*/
private boolean copyXML = false;
/**
* The default context override flag for this web application.
*/
private boolean override = false;
/**
* The original document root for this web application.
*/
private String originalDocBase = null;
/**
* The privileged flag for this web application.
*/
private boolean privileged = false;
/**
* Should the next call to <code>addWelcomeFile()</code> cause replacement
* of any existing welcome files? This will be set before processing the
* web application's deployment descriptor, so that application specified
* choices <strong>replace</strong>, rather than append to, those defined
* in the global descriptor.
*/
private boolean replaceWelcomeFiles = false;
/**
* The security role mappings for this application, keyed by role
* name (as used within the application).
*/
private HashMap<String, String> roleMappings = new HashMap<>();
/**
* The security roles for this application, keyed by role name.
*/
private String securityRoles[] = new String[0];
private final Object securityRolesLock = new Object();
/**
* The servlet mappings for this web application, keyed by
* matching pattern.
*/
private HashMap<String, String> servletMappings = new HashMap<>();
private final Object servletMappingsLock = new Object();
/**
* The session timeout (in minutes) for this web application.
*/
private int sessionTimeout = 30;
/**
* The notification sequence number.
*/
private AtomicLong sequenceNumber = new AtomicLong(0);
/**
* The status code error pages for this web application, keyed by
* HTTP status code (as an Integer). Note status code zero is used for the
* default error page.
*/
private HashMap<Integer, ErrorPage> statusPages = new HashMap<>();
/**
* Set flag to true to cause the system.out and system.err to be redirected
* to the logger when executing a servlet.
*/
private boolean swallowOutput = false;
/**
* Amount of ms that the container will wait for servlets to unload.
*/
private long unloadDelay = 2000;
/**
* The watched resources for this application.
*/
private String watchedResources[] = new String[0];
private final Object watchedResourcesLock = new Object();
/**
* The welcome files for this application.
*/
private String welcomeFiles[] = new String[0];
private final Object welcomeFilesLock = new Object();
/**
* The set of classnames of LifecycleListeners that will be added
* to each newly created Wrapper by <code>createWrapper()</code>.
*/
private String wrapperLifecycles[] = new String[0];
private final Object wrapperLifecyclesLock = new Object();
/**
* The set of classnames of ContainerListeners that will be added
* to each newly created Wrapper by <code>createWrapper()</code>.
*/
private String wrapperListeners[] = new String[0];
private final Object wrapperListenersLock = new Object();
/**
* The pathname to the work directory for this context (relative to
* the server's home if not absolute).
*/
private String workDir = null;
/**
* Java class name of the Wrapper class implementation we use.
*/
private String wrapperClassName = StandardWrapper.class.getName();
private Class<?> wrapperClass = null;
/**
* JNDI use flag.
*/
private boolean useNaming = true;
/**
* Name of the associated naming context.
*/
private String namingContextName = null;
/**
* Caching allowed flag.
*/
private boolean cachingAllowed = true;
/**
* Allow linking.
*/
protected boolean allowLinking = false;
/**
* Cache max size in KB.
*/
protected int cacheMaxSize = 10240; // 10 MB
/**
* Cache object max size in KB.
*/
protected int cacheObjectMaxSize = 512; // 512K
/**
* Cache TTL in ms.
*/
protected int cacheTTL = 5000;
private WebResourceRoot resources;
private final ReadWriteLock resourcesLock = new ReentrantReadWriteLock();
private long startupTime;
private long startTime;
private long tldScanTime;
/**
* Name of the engine. If null, the domain is used.
*/
private String j2EEApplication="none";
private String j2EEServer="none";
/**
* Attribute value used to turn on/off XML validation
*/
private boolean webXmlValidation = Globals.STRICT_SERVLET_COMPLIANCE;
/**
* Attribute value used to turn on/off XML namespace validation
*/
private boolean webXmlNamespaceAware = Globals.STRICT_SERVLET_COMPLIANCE;
/**
* Attribute value used to turn on/off TLD processing
*/
private boolean processTlds = true;
/**
* Attribute value used to turn on/off XML validation
*/
private boolean tldValidation = Globals.STRICT_SERVLET_COMPLIANCE;
/**
* Attribute value used to turn on/off TLD XML namespace validation
*/
private boolean tldNamespaceAware = Globals.STRICT_SERVLET_COMPLIANCE;
/**
* The name to use for session cookies. <code>null</code> indicates that
* the name is controlled by the application.
*/
private String sessionCookieName;
/**
* The flag that indicates that session cookies should use HttpOnly
*/
private boolean useHttpOnly = true;
/**
* The domain to use for session cookies. <code>null</code> indicates that
* the domain is controlled by the application.
*/
private String sessionCookieDomain;
/**
* The path to use for session cookies. <code>null</code> indicates that
* the path is controlled by the application.
*/
private String sessionCookiePath;
/**
* Is a / added to the end of the session cookie path to ensure browsers,
* particularly IE, don't send a session cookie for context /foo with
* requests intended for context /foobar.
*/
private boolean sessionCookiePathUsesTrailingSlash = true;
/**
* The Jar scanner to use to search for Jars that might contain
* configuration information such as TLDs or web-fragment.xml files.
*/
private JarScanner jarScanner = null;
/**
* Should Tomcat attempt to null out any static or final fields from loaded
* classes when a web application is stopped as a work around for apparent
* garbage collection bugs and application coding errors? There have been
* some issues reported with log4j when this option is true. Applications
* without memory leaks using recent JVMs should operate correctly with this
* option set to <code>false</code>. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStatic = false;
/**
* Should Tomcat attempt to terminate threads that have been started by the
* web application? Stopping threads is performed via the deprecated (for
* good reason) <code>Thread.stop()</code> method and is likely to result in
* instability. As such, enabling this should be viewed as an option of last
* resort in a development environment and is not recommended in a
* production environment. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStopThreads = false;
/**
* Should Tomcat attempt to terminate any {@link java.util.TimerThread}s
* that have been started by the web application? If not specified, the
* default value of <code>false</code> will be used.
*/
private boolean clearReferencesStopTimerThreads = false;
/**
* If an HttpClient keep-alive timer thread has been started by this web
* application and is still running, should Tomcat change the context class
* loader from the current {@link WebappClassLoader} to
* {@link WebappClassLoader#parent} to prevent a memory leak? Note that the
* keep-alive timer thread will stop on its own once the keep-alives all
* expire however, on a busy system that might not happen for some time.
*/
private boolean clearReferencesHttpClientKeepAliveThread = true;
/**
* Should Tomcat renew the threads of the thread pool when the application
* is stopped to avoid memory leaks because of uncleaned ThreadLocal
* variables. This also requires that the threadRenewalDelay property of the
* StandardThreadExecutor of ThreadPoolExecutor be set to a positive value.
*/
private boolean renewThreadsWhenStoppingContext = true;
/**
* Should the effective web.xml be logged when the context starts?
*/
private boolean logEffectiveWebXml = false;
private int effectiveMajorVersion = 3;
private int effectiveMinorVersion = 0;
private JspConfigDescriptor jspConfigDescriptor = null;
private Set<String> resourceOnlyServlets = new HashSet<>();
private String webappVersion = "";
private boolean addWebinfClassesResources = false;
private boolean fireRequestListenersOnForwards = false;
/**
* Servlets created via {@link ApplicationContext#createServlet(Class)} for
* tracking purposes.
*/
private Set<Servlet> createdServlets = new HashSet<>();
private boolean preemptiveAuthentication = false;
private boolean sendRedirectBody = false;
private boolean jndiExceptionOnFailedWrite = true;
private Map<String, String> postConstructMethods = new HashMap<>();
private Map<String, String> preDestroyMethods = new HashMap<>();
// ----------------------------------------------------- Context Properties
@Override
public boolean getSendRedirectBody() {
return sendRedirectBody;
}
@Override
public void setSendRedirectBody(boolean sendRedirectBody) {
this.sendRedirectBody = sendRedirectBody;
}
@Override
public boolean getPreemptiveAuthentication() {
return preemptiveAuthentication;
}
@Override
public void setPreemptiveAuthentication(boolean preemptiveAuthentication) {
this.preemptiveAuthentication = preemptiveAuthentication;
}
@Override
public void setFireRequestListenersOnForwards(boolean enable) {
fireRequestListenersOnForwards = enable;
}
@Override
public boolean getFireRequestListenersOnForwards() {
return fireRequestListenersOnForwards;
}
@Override
public void setAddWebinfClassesResources(
boolean addWebinfClassesResources) {
this.addWebinfClassesResources = addWebinfClassesResources;
}
@Override
public boolean getAddWebinfClassesResources() {
return addWebinfClassesResources;
}
@Override
public void setWebappVersion(String webappVersion) {
if (null == webappVersion) {
this.webappVersion = "";
} else {
this.webappVersion = webappVersion;
}
}
@Override
public String getWebappVersion() {
return webappVersion;
}
@Override
public String getBaseName() {
return new ContextName(path, webappVersion).getBaseName();
}
@Override
public String getResourceOnlyServlets() {
StringBuilder result = new StringBuilder();
boolean first = true;
for (String servletName : resourceOnlyServlets) {
if (!first) {
result.append(',');
}
result.append(servletName);
}
return result.toString();
}
@Override
public void setResourceOnlyServlets(String resourceOnlyServlets) {
this.resourceOnlyServlets.clear();
if (resourceOnlyServlets == null) {
return;
}
for (String servletName : resourceOnlyServlets.split(",")) {
servletName = servletName.trim();
if (servletName.length()>0) {
this.resourceOnlyServlets.add(servletName);
}
}
}
@Override
public boolean isResourceOnlyServlet(String servletName) {
return resourceOnlyServlets.contains(servletName);
}
@Override
public int getEffectiveMajorVersion() {
return effectiveMajorVersion;
}
@Override
public void setEffectiveMajorVersion(int effectiveMajorVersion) {
this.effectiveMajorVersion = effectiveMajorVersion;
}
@Override
public int getEffectiveMinorVersion() {
return effectiveMinorVersion;
}
@Override
public void setEffectiveMinorVersion(int effectiveMinorVersion) {
this.effectiveMinorVersion = effectiveMinorVersion;
}
@Override
public void setLogEffectiveWebXml(boolean logEffectiveWebXml) {
this.logEffectiveWebXml = logEffectiveWebXml;
}
@Override
public boolean getLogEffectiveWebXml() {
return logEffectiveWebXml;
}
@Override
public Authenticator getAuthenticator() {
if (this instanceof Authenticator)
return (Authenticator) this;
Pipeline pipeline = getPipeline();
if (pipeline != null) {
Valve basic = pipeline.getBasic();
if ((basic != null) && (basic instanceof Authenticator))
return (Authenticator) basic;
Valve valves[] = pipeline.getValves();
for (int i = 0; i < valves.length; i++) {
if (valves[i] instanceof Authenticator)
return (Authenticator) valves[i];
}
}
return null;
}
@Override
public JarScanner getJarScanner() {
if (jarScanner == null) {
jarScanner = new StandardJarScanner();
}
return jarScanner;
}
@Override
public void setJarScanner(JarScanner jarScanner) {
this.jarScanner = jarScanner;
}
@Override
public InstanceManager getInstanceManager() {
return instanceManager;
}
@Override
public void setInstanceManager(InstanceManager instanceManager) {
this.instanceManager = instanceManager;
}
@Override
public String getEncodedPath() {
return encodedPath;
}
/**
* Is caching allowed ?
*/
public boolean isCachingAllowed() {
return cachingAllowed;
}
/**
* Set caching allowed flag.
*/
public void setCachingAllowed(boolean cachingAllowed) {
this.cachingAllowed = cachingAllowed;
}
/**
* Set allow linking.
*/
public void setAllowLinking(boolean allowLinking) {
this.allowLinking = allowLinking;
}
/**
* Is linking allowed.
*/
public boolean isAllowLinking() {
return allowLinking;
}
/**
* Set to <code>true</code> to allow requests mapped to servlets that
* do not explicitly declare @MultipartConfig or have
* <multipart-config> specified in web.xml to parse
* multipart/form-data requests.
*
* @param allowCasualMultipartParsing <code>true</code> to allow such
* casual parsing, <code>false</code> otherwise.
*/
@Override
public void setAllowCasualMultipartParsing(
boolean allowCasualMultipartParsing) {
this.allowCasualMultipartParsing = allowCasualMultipartParsing;
}
/**
* Returns <code>true</code> if requests mapped to servlets without
* "multipart config" to parse multipart/form-data requests anyway.
*
* @return <code>true</code> if requests mapped to servlets without
* "multipart config" to parse multipart/form-data requests,
* <code>false</code> otherwise.
*/
@Override
public boolean getAllowCasualMultipartParsing() {
return this.allowCasualMultipartParsing;
}
/**
* Set to <code>false</code> to disable request data swallowing
* after an upload was aborted due to size constraints.
*
* @param swallowAbortedUploads <code>false</code> to disable
* swallowing, <code>true</code> otherwise (default).
*/
@Override
public void setSwallowAbortedUploads(boolean swallowAbortedUploads) {
this.swallowAbortedUploads = swallowAbortedUploads;
}
/**
* Returns <code>true</code> if remaining request data will be read
* (swallowed) even the request violates a data size constraint.
*
* @return <code>true</code> if data will be swallowed (default),
* <code>false</code> otherwise.
*/
@Override
public boolean getSwallowAbortedUploads() {
return this.swallowAbortedUploads;
}
/**
* Set cache TTL.
*/
public void setCacheTTL(int cacheTTL) {
this.cacheTTL = cacheTTL;
}
/**
* Get cache TTL.
*/
public int getCacheTTL() {
return cacheTTL;
}
/**
* Return the maximum size of the cache in KB.
*/
public int getCacheMaxSize() {
return cacheMaxSize;
}
/**
* Set the maximum size of the cache in KB.
*/
public void setCacheMaxSize(int cacheMaxSize) {
this.cacheMaxSize = cacheMaxSize;
}
/**
* Return the maximum size of objects to be cached in KB.
*/
public int getCacheObjectMaxSize() {
return cacheObjectMaxSize;
}
/**
* Set the maximum size of objects to be placed the cache in KB.
*/
public void setCacheObjectMaxSize(int cacheObjectMaxSize) {
this.cacheObjectMaxSize = cacheObjectMaxSize;
}
/**
* Add a ServletContainerInitializer instance to this web application.
*
* @param sci The instance to add
* @param classes The classes in which the initializer expressed an
* interest
*/
@Override
public void addServletContainerInitializer(
ServletContainerInitializer sci, Set<Class<?>> classes) {
initializers.put(sci, classes);
}
/**
* Return the "follow standard delegation model" flag used to configure
* our ClassLoader.
*/
public boolean getDelegate() {
return (this.delegate);
}
/**
* Set the "follow standard delegation model" flag used to configure
* our ClassLoader.
*
* @param delegate The new flag
*/
public void setDelegate(boolean delegate) {
boolean oldDelegate = this.delegate;
this.delegate = delegate;
support.firePropertyChange("delegate", oldDelegate,
this.delegate);
}
/**
* Returns true if the internal naming support is used.
*/
public boolean isUseNaming() {
return (useNaming);
}
/**
* Enables or disables naming.
*/
public void setUseNaming(boolean useNaming) {
this.useNaming = useNaming;
}
/**
* Return the set of initialized application event listener objects,
* in the order they were specified in the web application deployment
* descriptor, for this application.
*
* @exception IllegalStateException if this method is called before
* this application has started, or after it has been stopped
*/
@Override
public Object[] getApplicationEventListeners() {
return (applicationEventListenersObjects);
}
/**
* Store the set of initialized application event listener objects,
* in the order they were specified in the web application deployment
* descriptor, for this application.
*
* @param listeners The set of instantiated listener objects.
*/
@Override
public void setApplicationEventListeners(Object listeners[]) {
applicationEventListenersObjects = listeners;
}
/**
* Add a listener to the end of the list of initialized application event
* listeners.
*/
public void addApplicationEventListener(Object listener) {
int len = applicationEventListenersObjects.length;
Object[] newListeners = Arrays.copyOf(applicationEventListenersObjects,
len + 1);
newListeners[len] = listener;
applicationEventListenersObjects = newListeners;
}
/**
* Return the set of initialized application lifecycle listener objects,
* in the order they were specified in the web application deployment
* descriptor, for this application.
*
* @exception IllegalStateException if this method is called before
* this application has started, or after it has been stopped
*/
@Override
public Object[] getApplicationLifecycleListeners() {
return (applicationLifecycleListenersObjects);
}
/**
* Store the set of initialized application lifecycle listener objects,
* in the order they were specified in the web application deployment
* descriptor, for this application.
*
* @param listeners The set of instantiated listener objects.
*/
@Override
public void setApplicationLifecycleListeners(Object listeners[]) {
applicationLifecycleListenersObjects = listeners;
}
/**
* Add a listener to the end of the list of initialized application
* lifecycle listeners.
*/
public void addApplicationLifecycleListener(Object listener) {
int len = applicationLifecycleListenersObjects.length;
Object[] newListeners = Arrays.copyOf(
applicationLifecycleListenersObjects, len + 1);
newListeners[len] = listener;
applicationLifecycleListenersObjects = newListeners;
}
/**
* Return the antiJARLocking flag for this Context.
*/
public boolean getAntiJARLocking() {
return (this.antiJARLocking);
}
/**
* Return the antiResourceLocking flag for this Context.
*/
public boolean getAntiResourceLocking() {
return (this.antiResourceLocking);
}
/**
* Set the antiJARLocking feature for this Context.
*
* @param antiJARLocking The new flag value
*/
public void setAntiJARLocking(boolean antiJARLocking) {
boolean oldAntiJARLocking = this.antiJARLocking;
this.antiJARLocking = antiJARLocking;
support.firePropertyChange("antiJARLocking",
oldAntiJARLocking,
this.antiJARLocking);
}
/**
* Set the antiResourceLocking feature for this Context.
*
* @param antiResourceLocking The new flag value
*/
public void setAntiResourceLocking(boolean antiResourceLocking) {
boolean oldAntiResourceLocking = this.antiResourceLocking;
this.antiResourceLocking = antiResourceLocking;
support.firePropertyChange("antiResourceLocking",
oldAntiResourceLocking,
this.antiResourceLocking);
}
/**
* Return the Locale to character set mapper for this Context.
*/
public CharsetMapper getCharsetMapper() {
// Create a mapper the first time it is requested
if (this.charsetMapper == null) {
try {
Class<?> clazz = Class.forName(charsetMapperClass);
this.charsetMapper = (CharsetMapper) clazz.newInstance();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
this.charsetMapper = new CharsetMapper();
}
}
return (this.charsetMapper);
}
/**
* Set the Locale to character set mapper for this Context.
*
* @param mapper The new mapper
*/
public void setCharsetMapper(CharsetMapper mapper) {
CharsetMapper oldCharsetMapper = this.charsetMapper;
this.charsetMapper = mapper;
if( mapper != null )
this.charsetMapperClass= mapper.getClass().getName();
support.firePropertyChange("charsetMapper", oldCharsetMapper,
this.charsetMapper);
}
@Override
public String getCharset(Locale locale) {
return getCharsetMapper().getCharset(locale);
}
/**
* Return the URL of the XML descriptor for this context.
*/
@Override
public URL getConfigFile() {
return (this.configFile);
}
/**
* Set the URL of the XML descriptor for this context.
*
* @param configFile The URL of the XML descriptor for this context.
*/
@Override
public void setConfigFile(URL configFile) {
this.configFile = configFile;
}
/**
* Return the "correctly configured" flag for this Context.
*/
@Override
public boolean getConfigured() {
return (this.configured);
}
/**
* Set the "correctly configured" flag for this Context. This can be
* set to false by startup listeners that detect a fatal configuration
* error to avoid the application from being made available.
*
* @param configured The new correctly configured flag
*/
@Override
public void setConfigured(boolean configured) {
boolean oldConfigured = this.configured;
this.configured = configured;
support.firePropertyChange("configured",
oldConfigured,
this.configured);
}
/**
* Return the "use cookies for session ids" flag.
*/
@Override
public boolean getCookies() {
return (this.cookies);
}
/**
* Set the "use cookies for session ids" flag.
*
* @param cookies The new flag
*/
@Override
public void setCookies(boolean cookies) {
boolean oldCookies = this.cookies;
this.cookies = cookies;
support.firePropertyChange("cookies",
oldCookies,
this.cookies);
}
/**
* Gets the name to use for session cookies. Overrides any setting that
* may be specified by the application.
*
* @return The value of the default session cookie name or null if not
* specified
*/
@Override
public String getSessionCookieName() {
return sessionCookieName;
}
/**
* Sets the name to use for session cookies. Overrides any setting that
* may be specified by the application.
*
* @param sessionCookieName The name to use
*/
@Override
public void setSessionCookieName(String sessionCookieName) {
String oldSessionCookieName = this.sessionCookieName;
this.sessionCookieName = sessionCookieName;
support.firePropertyChange("sessionCookieName",
oldSessionCookieName, sessionCookieName);
}
/**
* Gets the value of the use HttpOnly cookies for session cookies flag.
*
* @return <code>true</code> if the HttpOnly flag should be set on session
* cookies
*/
@Override
public boolean getUseHttpOnly() {
return useHttpOnly;
}
/**
* Sets the use HttpOnly cookies for session cookies flag.
*
* @param useHttpOnly Set to <code>true</code> to use HttpOnly cookies
* for session cookies
*/
@Override
public void setUseHttpOnly(boolean useHttpOnly) {
boolean oldUseHttpOnly = this.useHttpOnly;
this.useHttpOnly = useHttpOnly;
support.firePropertyChange("useHttpOnly",
oldUseHttpOnly,
this.useHttpOnly);
}
/**
* Gets the domain to use for session cookies. Overrides any setting that
* may be specified by the application.
*
* @return The value of the default session cookie domain or null if not
* specified
*/
@Override
public String getSessionCookieDomain() {
return sessionCookieDomain;
}
/**
* Sets the domain to use for session cookies. Overrides any setting that
* may be specified by the application.
*
* @param sessionCookieDomain The domain to use
*/
@Override
public void setSessionCookieDomain(String sessionCookieDomain) {
String oldSessionCookieDomain = this.sessionCookieDomain;
this.sessionCookieDomain = sessionCookieDomain;
support.firePropertyChange("sessionCookieDomain",
oldSessionCookieDomain, sessionCookieDomain);
}
/**
* Gets the path to use for session cookies. Overrides any setting that
* may be specified by the application.
*
* @return The value of the default session cookie path or null if not
* specified
*/
@Override
public String getSessionCookiePath() {
return sessionCookiePath;
}
/**
* Sets the path to use for session cookies. Overrides any setting that
* may be specified by the application.
*
* @param sessionCookiePath The path to use
*/
@Override
public void setSessionCookiePath(String sessionCookiePath) {
String oldSessionCookiePath = this.sessionCookiePath;
this.sessionCookiePath = sessionCookiePath;
support.firePropertyChange("sessionCookiePath",
oldSessionCookiePath, sessionCookiePath);
}
@Override
public boolean getSessionCookiePathUsesTrailingSlash() {
return sessionCookiePathUsesTrailingSlash;
}
@Override
public void setSessionCookiePathUsesTrailingSlash(
boolean sessionCookiePathUsesTrailingSlash) {
this.sessionCookiePathUsesTrailingSlash =
sessionCookiePathUsesTrailingSlash;
}
/**
* Return the "allow crossing servlet contexts" flag.
*/
@Override
public boolean getCrossContext() {
return (this.crossContext);
}
/**
* Set the "allow crossing servlet contexts" flag.
*
* @param crossContext The new cross contexts flag
*/
@Override
public void setCrossContext(boolean crossContext) {
boolean oldCrossContext = this.crossContext;
this.crossContext = crossContext;
support.firePropertyChange("crossContext",
oldCrossContext,
this.crossContext);
}
public String getDefaultContextXml() {
return defaultContextXml;
}
/**
* Set the location of the default context xml that will be used.
* If not absolute, it'll be made relative to the engine's base dir
* ( which defaults to catalina.base system property ).
*
* @param defaultContextXml The default web xml
*/
public void setDefaultContextXml(String defaultContextXml) {
this.defaultContextXml = defaultContextXml;
}
public String getDefaultWebXml() {
return defaultWebXml;
}
/**
* Set the location of the default web xml that will be used.
* If not absolute, it'll be made relative to the engine's base dir
* ( which defaults to catalina.base system property ).
*
* @param defaultWebXml The default web xml
*/
public void setDefaultWebXml(String defaultWebXml) {
this.defaultWebXml = defaultWebXml;
}
/**
* Gets the time (in milliseconds) it took to start this context.
*
* @return Time (in milliseconds) it took to start this context.
*/
public long getStartupTime() {
return startupTime;
}
public void setStartupTime(long startupTime) {
this.startupTime = startupTime;
}
public long getTldScanTime() {
return tldScanTime;
}
public void setTldScanTime(long tldScanTime) {
this.tldScanTime = tldScanTime;
}
@Override
public boolean getDenyUncoveredHttpMethods() {
return denyUncoveredHttpMethods;
}
@Override
public void setDenyUncoveredHttpMethods(boolean denyUncoveredHttpMethods) {
this.denyUncoveredHttpMethods = denyUncoveredHttpMethods;
}
/**
* Return the display name of this web application.
*/
@Override
public String getDisplayName() {
return (this.displayName);
}
/**
* Return the alternate Deployment Descriptor name.
*/
@Override
public String getAltDDName(){
return altDDName;
}
/**
* Set an alternate Deployment Descriptor name.
*/
@Override
public void setAltDDName(String altDDName) {
this.altDDName = altDDName;
if (context != null) {
context.setAttribute(Globals.ALT_DD_ATTR,altDDName);
}
}
/**
* Set the display name of this web application.
*
* @param displayName The new display name
*/
@Override
public void setDisplayName(String displayName) {
String oldDisplayName = this.displayName;
this.displayName = displayName;
support.firePropertyChange("displayName", oldDisplayName,
this.displayName);
}
/**
* Return the distributable flag for this web application.
*/
@Override
public boolean getDistributable() {
return (this.distributable);
}
/**
* Set the distributable flag for this web application.
*
* @param distributable The new distributable flag
*/
@Override
public void setDistributable(boolean distributable) {
boolean oldDistributable = this.distributable;
this.distributable = distributable;
support.firePropertyChange("distributable",
oldDistributable,
this.distributable);
// Bugzilla 32866
if(getManager() != null) {
if(log.isDebugEnabled()) {
log.debug("Propagating distributable=" + distributable
+ " to manager");
}
getManager().setDistributable(distributable);
}
}
/**
* Return the document root for this Context. This can be an absolute
* pathname, a relative pathname, or a URL.
*/
@Override
public String getDocBase() {
return (this.docBase);
}
/**
* Set the document root for this Context. This can be an absolute
* pathname, a relative pathname, or a URL.
*
* @param docBase The new document root
*/
@Override
public void setDocBase(String docBase) {
this.docBase = docBase;
}
public String getJ2EEApplication() {
return j2EEApplication;
}
public void setJ2EEApplication(String j2EEApplication) {
this.j2EEApplication = j2EEApplication;
}
public String getJ2EEServer() {
return j2EEServer;
}
public void setJ2EEServer(String j2EEServer) {
this.j2EEServer = j2EEServer;
}
@Override
public Loader getLoader() {
Lock readLock = loaderLock.readLock();
readLock.lock();
try {
return loader;
} finally {
readLock.unlock();
}
}
@Override
public void setLoader(Loader loader) {
Lock writeLock = loaderLock.writeLock();
writeLock.lock();
Loader oldLoader = null;
try {
// Change components if necessary
oldLoader = this.loader;
if (oldLoader == loader)
return;
this.loader = loader;
// Stop the old component if necessary
if (getState().isAvailable() && (oldLoader != null) &&
(oldLoader instanceof Lifecycle)) {
try {
((Lifecycle) oldLoader).stop();
} catch (LifecycleException e) {
log.error("StandardContext.setLoader: stop: ", e);
}
}
// Start the new component if necessary
if (loader != null)
loader.setContext(this);
if (getState().isAvailable() && (loader != null) &&
(loader instanceof Lifecycle)) {
try {
((Lifecycle) loader).start();
} catch (LifecycleException e) {
log.error("StandardContext.setLoader: start: ", e);
}
}
} finally {
writeLock.unlock();
}
// Report this property change to interested listeners
support.firePropertyChange("loader", oldLoader, loader);
}
@Override
public Manager getManager() {
Lock readLock = managerLock.readLock();
readLock.lock();
try {
return manager;
} finally {
readLock.unlock();
}
}
@Override
public void setManager(Manager manager) {
Lock writeLock = managerLock.writeLock();
writeLock.lock();
Manager oldManager = null;
try {
// Change components if necessary
oldManager = this.manager;
if (oldManager == manager)
return;
this.manager = manager;
// Stop the old component if necessary
if (getState().isAvailable() && (oldManager != null) &&
(oldManager instanceof Lifecycle)) {
try {
((Lifecycle) oldManager).stop();
} catch (LifecycleException e) {
log.error("StandardContext.setManager: stop: ", e);
}
}
// Start the new component if necessary
if (manager != null)
manager.setContext(this);
if (getState().isAvailable() && (manager != null) &&
(manager instanceof Lifecycle)) {
try {
((Lifecycle) manager).start();
} catch (LifecycleException e) {
log.error("StandardContext.setManager: start: ", e);
}
}
} finally {
writeLock.unlock();
}
// Report this property change to interested listeners
support.firePropertyChange("manager", oldManager, manager);
}
/**
* Return the boolean on the annotations parsing.
*/
@Override
public boolean getIgnoreAnnotations() {
return this.ignoreAnnotations;
}
/**
* Set the boolean on the annotations parsing for this web
* application.
*
* @param ignoreAnnotations The boolean on the annotations parsing
*/
@Override
public void setIgnoreAnnotations(boolean ignoreAnnotations) {
boolean oldIgnoreAnnotations = this.ignoreAnnotations;
this.ignoreAnnotations = ignoreAnnotations;
support.firePropertyChange("ignoreAnnotations", oldIgnoreAnnotations,
this.ignoreAnnotations);
}
/**
* Return the login configuration descriptor for this web application.
*/
@Override
public LoginConfig getLoginConfig() {
return (this.loginConfig);
}
/**
* Set the login configuration descriptor for this web application.
*
* @param config The new login configuration
*/
@Override
public void setLoginConfig(LoginConfig config) {
// Validate the incoming property value
if (config == null)
throw new IllegalArgumentException
(sm.getString("standardContext.loginConfig.required"));
String loginPage = config.getLoginPage();
if ((loginPage != null) && !loginPage.startsWith("/")) {
if (isServlet22()) {
if(log.isDebugEnabled())
log.debug(sm.getString("standardContext.loginConfig.loginWarning",
loginPage));
config.setLoginPage("/" + loginPage);
} else {
throw new IllegalArgumentException
(sm.getString("standardContext.loginConfig.loginPage",
loginPage));
}
}
String errorPage = config.getErrorPage();
if ((errorPage != null) && !errorPage.startsWith("/")) {
if (isServlet22()) {
if(log.isDebugEnabled())
log.debug(sm.getString("standardContext.loginConfig.errorWarning",
errorPage));
config.setErrorPage("/" + errorPage);
} else {
throw new IllegalArgumentException
(sm.getString("standardContext.loginConfig.errorPage",
errorPage));
}
}
// Process the property setting change
LoginConfig oldLoginConfig = this.loginConfig;
this.loginConfig = config;
support.firePropertyChange("loginConfig",
oldLoginConfig, this.loginConfig);
}
/**
* Return the naming resources associated with this web application.
*/
@Override
public NamingResourcesImpl getNamingResources() {
if (namingResources == null) {
setNamingResources(new NamingResourcesImpl());
}
return (namingResources);
}
/**
* Set the naming resources for this web application.
*
* @param namingResources The new naming resources
*/
@Override
public void setNamingResources(NamingResourcesImpl namingResources) {
// Process the property setting change
NamingResourcesImpl oldNamingResources = this.namingResources;
this.namingResources = namingResources;
if (namingResources != null) {
namingResources.setContainer(this);
}
support.firePropertyChange("namingResources",
oldNamingResources, this.namingResources);
if (getState() == LifecycleState.NEW ||
getState() == LifecycleState.INITIALIZING ||
getState() == LifecycleState.INITIALIZED) {
// NEW will occur if Context is defined in server.xml
// At this point getObjectKeyPropertiesNameOnly() will trigger an
// NPE.
// INITIALIZED will occur if the Context is defined in a context.xml
// file
// If started now, a second start will be attempted when the context
// starts
// In both cases, return and let context init the namingResources
// when it starts
return;
}
if (oldNamingResources != null) {
try {
oldNamingResources.stop();
oldNamingResources.destroy();
} catch (LifecycleException e) {
log.warn("standardContext.namingResource.destroy.fail", e);
}
}
if (namingResources != null) {
try {
namingResources.init();
namingResources.start();
} catch (LifecycleException e) {
log.warn("standardContext.namingResource.init.fail", e);
}
}
}
/**
* Return the context path for this Context.
*/
@Override
public String getPath() {
return (path);
}
/**
* Set the context path for this Context.
*
* @param path The new context path
*/
@Override
public void setPath(String path) {
if (path == null || (!path.equals("") && !path.startsWith("/"))) {
this.path = "/" + path;
log.warn(sm.getString(
"standardContext.pathInvalid", path, this.path));
} else {
this.path = path;
}
encodedPath = urlEncoder.encode(this.path);
if (getName() == null) {
setName(this.path);
}
}
/**
* Return the public identifier of the deployment descriptor DTD that is
* currently being parsed.
*/
@Override
public String getPublicId() {
return (this.publicId);
}
/**
* Set the public identifier of the deployment descriptor DTD that is
* currently being parsed.
*
* @param publicId The public identifier
*/
@Override
public void setPublicId(String publicId) {
if (log.isDebugEnabled())
log.debug("Setting deployment descriptor public ID to '" +
publicId + "'");
String oldPublicId = this.publicId;
this.publicId = publicId;
support.firePropertyChange("publicId", oldPublicId, publicId);
}
/**
* Return the reloadable flag for this web application.
*/
@Override
public boolean getReloadable() {
return (this.reloadable);
}
/**
* Return the default context override flag for this web application.
*/
@Override
public boolean getOverride() {
return (this.override);
}
/**
* Return the original document root for this Context. This can be an absolute
* pathname, a relative pathname, or a URL.
* Is only set as deployment has change docRoot!
*/
public String getOriginalDocBase() {
return (this.originalDocBase);
}
/**
* Set the original document root for this Context. This can be an absolute
* pathname, a relative pathname, or a URL.
*
* @param docBase The original document root
*/
public void setOriginalDocBase(String docBase) {
this.originalDocBase = docBase;
}
/**
* Return the parent class loader (if any) for this web application.
* This call is meaningful only <strong>after</strong> a Loader has
* been configured.
*/
@Override
public ClassLoader getParentClassLoader() {
if (parentClassLoader != null)
return (parentClassLoader);
if (getPrivileged()) {
return this.getClass().getClassLoader();
} else if (parent != null) {
return (parent.getParentClassLoader());
}
return (ClassLoader.getSystemClassLoader());
}
/**
* Return the privileged flag for this web application.
*/
@Override
public boolean getPrivileged() {
return (this.privileged);
}
/**
* Set the privileged flag for this web application.
*
* @param privileged The new privileged flag
*/
@Override
public void setPrivileged(boolean privileged) {
boolean oldPrivileged = this.privileged;
this.privileged = privileged;
support.firePropertyChange("privileged",
oldPrivileged,
this.privileged);
}
/**
* Set the reloadable flag for this web application.
*
* @param reloadable The new reloadable flag
*/
@Override
public void setReloadable(boolean reloadable) {
boolean oldReloadable = this.reloadable;
this.reloadable = reloadable;
support.firePropertyChange("reloadable",
oldReloadable,
this.reloadable);
}
/**
* Set the default context override flag for this web application.
*
* @param override The new override flag
*/
@Override
public void setOverride(boolean override) {
boolean oldOverride = this.override;
this.override = override;
support.firePropertyChange("override",
oldOverride,
this.override);
}
/**
* Set the "replace welcome files" property.
*
* @param replaceWelcomeFiles The new property value
*/
public void setReplaceWelcomeFiles(boolean replaceWelcomeFiles) {
boolean oldReplaceWelcomeFiles = this.replaceWelcomeFiles;
this.replaceWelcomeFiles = replaceWelcomeFiles;
support.firePropertyChange("replaceWelcomeFiles",
oldReplaceWelcomeFiles,
this.replaceWelcomeFiles);
}
/**
* Return the servlet context for which this Context is a facade.
*/
@Override
public ServletContext getServletContext() {
if (context == null) {
context = new ApplicationContext(this);
if (altDDName != null)
context.setAttribute(Globals.ALT_DD_ATTR,altDDName);
}
return (context.getFacade());
}
/**
* Return the default session timeout (in minutes) for this
* web application.
*/
@Override
public int getSessionTimeout() {
return (this.sessionTimeout);
}
/**
* Set the default session timeout (in minutes) for this
* web application.
*
* @param timeout The new default session timeout
*/
@Override
public void setSessionTimeout(int timeout) {
int oldSessionTimeout = this.sessionTimeout;
/*
* SRV.13.4 ("Deployment Descriptor"):
* If the timeout is 0 or less, the container ensures the default
* behaviour of sessions is never to time out.
*/
this.sessionTimeout = (timeout == 0) ? -1 : timeout;
support.firePropertyChange("sessionTimeout",
oldSessionTimeout,
this.sessionTimeout);
}
/**
* Return the value of the swallowOutput flag.
*/
@Override
public boolean getSwallowOutput() {
return (this.swallowOutput);
}
/**
* Set the value of the swallowOutput flag. If set to true, the system.out
* and system.err will be redirected to the logger during a servlet
* execution.
*
* @param swallowOutput The new value
*/
@Override
public void setSwallowOutput(boolean swallowOutput) {
boolean oldSwallowOutput = this.swallowOutput;
this.swallowOutput = swallowOutput;
support.firePropertyChange("swallowOutput",
oldSwallowOutput,
this.swallowOutput);
}
/**
* Return the value of the unloadDelay flag.
*/
public long getUnloadDelay() {
return (this.unloadDelay);
}
/**
* Set the value of the unloadDelay flag, which represents the amount
* of ms that the container will wait when unloading servlets.
* Setting this to a small value may cause more requests to fail
* to complete when stopping a web application.
*
* @param unloadDelay The new value
*/
public void setUnloadDelay(long unloadDelay) {
long oldUnloadDelay = this.unloadDelay;
this.unloadDelay = unloadDelay;
support.firePropertyChange("unloadDelay",
Long.valueOf(oldUnloadDelay),
Long.valueOf(this.unloadDelay));
}
/**
* Unpack WAR flag accessor.
*/
public boolean getUnpackWAR() {
return (unpackWAR);
}
/**
* Unpack WAR flag mutator.
*/
public void setUnpackWAR(boolean unpackWAR) {
this.unpackWAR = unpackWAR;
}
public boolean getCopyXML() {
return copyXML;
}
public void setCopyXML(boolean copyXML) {
this.copyXML = copyXML;
}
/**
* Return the Java class name of the Wrapper implementation used
* for servlets registered in this Context.
*/
@Override
public String getWrapperClass() {
return (this.wrapperClassName);
}
/**
* Set the Java class name of the Wrapper implementation used
* for servlets registered in this Context.
*
* @param wrapperClassName The new wrapper class name
*
* @throws IllegalArgumentException if the specified wrapper class
* cannot be found or is not a subclass of StandardWrapper
*/
@Override
public void setWrapperClass(String wrapperClassName) {
this.wrapperClassName = wrapperClassName;
try {
wrapperClass = Class.forName(wrapperClassName);
if (!StandardWrapper.class.isAssignableFrom(wrapperClass)) {
throw new IllegalArgumentException(
sm.getString("standardContext.invalidWrapperClass",
wrapperClassName));
}
} catch (ClassNotFoundException cnfe) {
throw new IllegalArgumentException(cnfe.getMessage());
}
}
@Override
public WebResourceRoot getResources() {
Lock readLock = resourcesLock.readLock();
readLock.lock();
try {
return resources;
} finally {
readLock.unlock();
}
}
@Override
public void setResources(WebResourceRoot resources) {
Lock writeLock = resourcesLock.writeLock();
writeLock.lock();
WebResourceRoot oldResources = null;
try {
if (getState().isAvailable()) {
throw new IllegalStateException
(sm.getString("standardContext.resources.started"));
}
oldResources = this.resources;
if (oldResources == resources)
return;
this.resources = resources;
if (oldResources != null) {
oldResources.setContext(null);
}
if (resources != null) {
resources.setContext(this);
}
support.firePropertyChange("resources", oldResources,
resources);
} finally {
writeLock.unlock();
}
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
return jspConfigDescriptor;
}
@Override
public void setJspConfigDescriptor(JspConfigDescriptor descriptor) {
this.jspConfigDescriptor = descriptor;
}
// ------------------------------------------------------ Public Properties
/**
* Returns whether or not an attempt to modify the JNDI context will trigger
* an exception or if the request will be ignored.
*/
public boolean getJndiExceptionOnFailedWrite() {
return jndiExceptionOnFailedWrite;
}
/**
* Controls whether or not an attempt to modify the JNDI context will
* trigger an exception or if the request will be ignored.
*
* @param jndiExceptionOnFailedWrite
*/
public void setJndiExceptionOnFailedWrite(
boolean jndiExceptionOnFailedWrite) {
this.jndiExceptionOnFailedWrite = jndiExceptionOnFailedWrite;
}
/**
* Return the Locale to character set mapper class for this Context.
*/
public String getCharsetMapperClass() {
return (this.charsetMapperClass);
}
/**
* Set the Locale to character set mapper class for this Context.
*
* @param mapper The new mapper class
*/
public void setCharsetMapperClass(String mapper) {
String oldCharsetMapperClass = this.charsetMapperClass;
this.charsetMapperClass = mapper;
support.firePropertyChange("charsetMapperClass",
oldCharsetMapperClass,
this.charsetMapperClass);
}
/** Get the absolute path to the work dir.
* To avoid duplication.
*
* @return The work path
*/
public String getWorkPath() {
if (getWorkDir() == null) {
return null;
}
File workDir = new File(getWorkDir());
if (!workDir.isAbsolute()) {
try {
workDir = new File(getCatalinaBase().getCanonicalFile(),
getWorkDir());
} catch (IOException e) {
log.warn(sm.getString("standardContext.workPath", getName()),
e);
}
}
return workDir.getAbsolutePath();
}
/**
* Return the work directory for this Context.
*/
public String getWorkDir() {
return (this.workDir);
}
/**
* Set the work directory for this Context.
*
* @param workDir The new work directory
*/
public void setWorkDir(String workDir) {
this.workDir = workDir;
if (getState().isAvailable()) {
postWorkDirectory();
}
}
/**
* Return the clearReferencesStatic flag for this Context.
*/
public boolean getClearReferencesStatic() {
return (this.clearReferencesStatic);
}
/**
* Set the clearReferencesStatic feature for this Context.
*
* @param clearReferencesStatic The new flag value
*/
public void setClearReferencesStatic(boolean clearReferencesStatic) {
boolean oldClearReferencesStatic = this.clearReferencesStatic;
this.clearReferencesStatic = clearReferencesStatic;
support.firePropertyChange("clearReferencesStatic",
oldClearReferencesStatic,
this.clearReferencesStatic);
}
/**
* Return the clearReferencesStopThreads flag for this Context.
*/
public boolean getClearReferencesStopThreads() {
return (this.clearReferencesStopThreads);
}
/**
* Set the clearReferencesStopThreads feature for this Context.
*
* @param clearReferencesStopThreads The new flag value
*/
public void setClearReferencesStopThreads(
boolean clearReferencesStopThreads) {
boolean oldClearReferencesStopThreads = this.clearReferencesStopThreads;
this.clearReferencesStopThreads = clearReferencesStopThreads;
support.firePropertyChange("clearReferencesStopThreads",
oldClearReferencesStopThreads,
this.clearReferencesStopThreads);
}
/**
* Return the clearReferencesStopTimerThreads flag for this Context.
*/
public boolean getClearReferencesStopTimerThreads() {
return (this.clearReferencesStopTimerThreads);
}
/**
* Set the clearReferencesStopTimerThreads feature for this Context.
*
* @param clearReferencesStopTimerThreads The new flag value
*/
public void setClearReferencesStopTimerThreads(
boolean clearReferencesStopTimerThreads) {
boolean oldClearReferencesStopTimerThreads =
this.clearReferencesStopTimerThreads;
this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads;
support.firePropertyChange("clearReferencesStopTimerThreads",
oldClearReferencesStopTimerThreads,
this.clearReferencesStopTimerThreads);
}
/**
* Return the clearReferencesHttpClientKeepAliveThread flag for this
* Context.
*/
public boolean getClearReferencesHttpClientKeepAliveThread() {
return (this.clearReferencesHttpClientKeepAliveThread);
}
/**
* Set the clearReferencesHttpClientKeepAliveThread feature for this
* Context.
*
* @param clearReferencesHttpClientKeepAliveThread The new flag value
*/
public void setClearReferencesHttpClientKeepAliveThread(
boolean clearReferencesHttpClientKeepAliveThread) {
this.clearReferencesHttpClientKeepAliveThread =
clearReferencesHttpClientKeepAliveThread;
}
public boolean getRenewThreadsWhenStoppingContext() {
return this.renewThreadsWhenStoppingContext;
}
public void setRenewThreadsWhenStoppingContext(
boolean renewThreadsWhenStoppingContext) {
boolean oldRenewThreadsWhenStoppingContext =
this.renewThreadsWhenStoppingContext;
this.renewThreadsWhenStoppingContext = renewThreadsWhenStoppingContext;
support.firePropertyChange("renewThreadsWhenStoppingContext",
oldRenewThreadsWhenStoppingContext,
this.renewThreadsWhenStoppingContext);
}
// -------------------------------------------------------- Context Methods
/**
* Add a new Listener class name to the set of Listeners
* configured for this application.
*
* @param listener Java class name of a listener class
*/
@Override
public void addApplicationListener(ApplicationListener listener) {
synchronized (applicationListenersLock) {
ApplicationListener results[] =
new ApplicationListener[applicationListeners.length + 1];
for (int i = 0; i < applicationListeners.length; i++) {
if (listener.equals(applicationListeners[i])) {
log.info(sm.getString(
"standardContext.duplicateListener",listener));
return;
}
results[i] = applicationListeners[i];
}
results[applicationListeners.length] = listener;
applicationListeners = results;
}
fireContainerEvent("addApplicationListener", listener);
// FIXME - add instance if already started?
}
/**
* Add a new application parameter for this application.
*
* @param parameter The new application parameter
*/
@Override
public void addApplicationParameter(ApplicationParameter parameter) {
synchronized (applicationParametersLock) {
String newName = parameter.getName();
for (ApplicationParameter p : applicationParameters) {
if (newName.equals(p.getName()) && !p.getOverride())
return;
}
ApplicationParameter results[] = Arrays.copyOf(
applicationParameters, applicationParameters.length + 1);
results[applicationParameters.length] = parameter;
applicationParameters = results;
}
fireContainerEvent("addApplicationParameter", parameter);
}
/**
* Add a child Container, only if the proposed child is an implementation
* of Wrapper.
*
* @param child Child container to be added
*
* @exception IllegalArgumentException if the proposed container is
* not an implementation of Wrapper
*/
@Override
public void addChild(Container child) {
// Global JspServlet
Wrapper oldJspServlet = null;
if (!(child instanceof Wrapper)) {
throw new IllegalArgumentException
(sm.getString("standardContext.notWrapper"));
}
boolean isJspServlet = "jsp".equals(child.getName());
// Allow webapp to override JspServlet inherited from global web.xml.
if (isJspServlet) {
oldJspServlet = (Wrapper) findChild("jsp");
if (oldJspServlet != null) {
removeChild(oldJspServlet);
}
}
super.addChild(child);
if (isJspServlet && oldJspServlet != null) {
/*
* The webapp-specific JspServlet inherits all the mappings
* specified in the global web.xml, and may add additional ones.
*/
String[] jspMappings = oldJspServlet.findMappings();
for (int i=0; jspMappings!=null && i<jspMappings.length; i++) {
addServletMapping(jspMappings[i], child.getName());
}
}
}
/**
* Add a security constraint to the set for this web application.
*/
@Override
public void addConstraint(SecurityConstraint constraint) {
// Validate the proposed constraint
SecurityCollection collections[] = constraint.findCollections();
for (int i = 0; i < collections.length; i++) {
String patterns[] = collections[i].findPatterns();
for (int j = 0; j < patterns.length; j++) {
patterns[j] = adjustURLPattern(patterns[j]);
if (!validateURLPattern(patterns[j]))
throw new IllegalArgumentException
(sm.getString
("standardContext.securityConstraint.pattern",
patterns[j]));
}
if (collections[i].findMethods().length > 0 &&
collections[i].findOmittedMethods().length > 0) {
throw new IllegalArgumentException(sm.getString(
"standardContext.securityConstraint.mixHttpMethod"));
}
}
// Add this constraint to the set for our web application
synchronized (constraintsLock) {
SecurityConstraint results[] =
new SecurityConstraint[constraints.length + 1];
for (int i = 0; i < constraints.length; i++)
results[i] = constraints[i];
results[constraints.length] = constraint;
constraints = results;
}
}
/**
* Add an error page for the specified error or Java exception.
*
* @param errorPage The error page definition to be added
*/
@Override
public void addErrorPage(ErrorPage errorPage) {
// Validate the input parameters
if (errorPage == null)
throw new IllegalArgumentException
(sm.getString("standardContext.errorPage.required"));
String location = errorPage.getLocation();
if ((location != null) && !location.startsWith("/")) {
if (isServlet22()) {
if(log.isDebugEnabled())
log.debug(sm.getString("standardContext.errorPage.warning",
location));
errorPage.setLocation("/" + location);
} else {
throw new IllegalArgumentException
(sm.getString("standardContext.errorPage.error",
location));
}
}
// Add the specified error page to our internal collections
String exceptionType = errorPage.getExceptionType();
if (exceptionType != null) {
synchronized (exceptionPages) {
exceptionPages.put(exceptionType, errorPage);
}
} else {
synchronized (statusPages) {
statusPages.put(Integer.valueOf(errorPage.getErrorCode()),
errorPage);
}
}
fireContainerEvent("addErrorPage", errorPage);
}
/**
* Add a filter definition to this Context.
*
* @param filterDef The filter definition to be added
*/
@Override
public void addFilterDef(FilterDef filterDef) {
synchronized (filterDefs) {
filterDefs.put(filterDef.getFilterName(), filterDef);
}
fireContainerEvent("addFilterDef", filterDef);
}
/**
* Add a filter mapping to this Context at the end of the current set
* of filter mappings.
*
* @param filterMap The filter mapping to be added
*
* @exception IllegalArgumentException if the specified filter name
* does not match an existing filter definition, or the filter mapping
* is malformed
*/
@Override
public void addFilterMap(FilterMap filterMap) {
validateFilterMap(filterMap);
// Add this filter mapping to our registered set
filterMaps.add(filterMap);
fireContainerEvent("addFilterMap", filterMap);
}
/**
* Add a filter mapping to this Context before the mappings defined in the
* deployment descriptor but after any other mappings added via this method.
*
* @param filterMap The filter mapping to be added
*
* @exception IllegalArgumentException if the specified filter name
* does not match an existing filter definition, or the filter mapping
* is malformed
*/
@Override
public void addFilterMapBefore(FilterMap filterMap) {
validateFilterMap(filterMap);
// Add this filter mapping to our registered set
filterMaps.addBefore(filterMap);
fireContainerEvent("addFilterMap", filterMap);
}
/**
* Validate the supplied FilterMap.
*/
private void validateFilterMap(FilterMap filterMap) {
// Validate the proposed filter mapping
String filterName = filterMap.getFilterName();
String[] servletNames = filterMap.getServletNames();
String[] urlPatterns = filterMap.getURLPatterns();
if (findFilterDef(filterName) == null)
throw new IllegalArgumentException
(sm.getString("standardContext.filterMap.name", filterName));
if (!filterMap.getMatchAllServletNames() &&
!filterMap.getMatchAllUrlPatterns() &&
(servletNames.length == 0) && (urlPatterns.length == 0))
throw new IllegalArgumentException
(sm.getString("standardContext.filterMap.either"));
// FIXME: Older spec revisions may still check this
/*
if ((servletNames.length != 0) && (urlPatterns.length != 0))
throw new IllegalArgumentException
(sm.getString("standardContext.filterMap.either"));
*/
for (int i = 0; i < urlPatterns.length; i++) {
if (!validateURLPattern(urlPatterns[i])) {
throw new IllegalArgumentException
(sm.getString("standardContext.filterMap.pattern",
urlPatterns[i]));
}
}
}
/**
* Add the classname of an InstanceListener to be added to each
* Wrapper appended to this Context.
*
* @param listener Java class name of an InstanceListener class
*/
@Override
public void addInstanceListener(String listener) {
synchronized (instanceListenersLock) {
String results[] =new String[instanceListeners.length + 1];
for (int i = 0; i < instanceListeners.length; i++)
results[i] = instanceListeners[i];
results[instanceListeners.length] = listener;
instanceListeners = results;
}
fireContainerEvent("addInstanceListener", listener);
}
/**
* Add a Locale Encoding Mapping (see Sec 5.4 of Servlet spec 2.4)
*
* @param locale locale to map an encoding for
* @param encoding encoding to be used for a give locale
*/
@Override
public void addLocaleEncodingMappingParameter(String locale, String encoding){
getCharsetMapper().addCharsetMappingFromDeploymentDescriptor(locale, encoding);
}
/**
* Add a message destination for this web application.
*
* @param md New message destination
*/
public void addMessageDestination(MessageDestination md) {
synchronized (messageDestinations) {
messageDestinations.put(md.getName(), md);
}
fireContainerEvent("addMessageDestination", md.getName());
}
/**
* Add a message destination reference for this web application.
*
* @param mdr New message destination reference
*/
public void addMessageDestinationRef
(MessageDestinationRef mdr) {
namingResources.addMessageDestinationRef(mdr);
fireContainerEvent("addMessageDestinationRef", mdr.getName());
}
/**
* Add a new MIME mapping, replacing any existing mapping for
* the specified extension.
*
* @param extension Filename extension being mapped
* @param mimeType Corresponding MIME type
*/
@Override
public void addMimeMapping(String extension, String mimeType) {
synchronized (mimeMappings) {
mimeMappings.put(extension.toLowerCase(Locale.ENGLISH), mimeType);
}
fireContainerEvent("addMimeMapping", extension);
}
/**
* Add a new context initialization parameter.
*
* @param name Name of the new parameter
* @param value Value of the new parameter
*
* @exception IllegalArgumentException if the name or value is missing,
* or if this context initialization parameter has already been
* registered
*/
@Override
public void addParameter(String name, String value) {
// Validate the proposed context initialization parameter
if ((name == null) || (value == null))
throw new IllegalArgumentException
(sm.getString("standardContext.parameter.required"));
if (parameters.get(name) != null)
throw new IllegalArgumentException
(sm.getString("standardContext.parameter.duplicate", name));
// Add this parameter to our defined set
synchronized (parameters) {
parameters.put(name, value);
}
fireContainerEvent("addParameter", name);
}
/**
* Add a security role reference for this web application.
*
* @param role Security role used in the application
* @param link Actual security role to check for
*/
@Override
public void addRoleMapping(String role, String link) {
synchronized (roleMappings) {
roleMappings.put(role, link);
}
fireContainerEvent("addRoleMapping", role);
}
/**
* Add a new security role for this web application.
*
* @param role New security role
*/
@Override
public void addSecurityRole(String role) {
synchronized (securityRolesLock) {
String results[] =new String[securityRoles.length + 1];
for (int i = 0; i < securityRoles.length; i++)
results[i] = securityRoles[i];
results[securityRoles.length] = role;
securityRoles = results;
}
fireContainerEvent("addSecurityRole", role);
}
/**
* Add a new servlet mapping, replacing any existing mapping for
* the specified pattern.
*
* @param pattern URL pattern to be mapped
* @param name Name of the corresponding servlet to execute
*
* @exception IllegalArgumentException if the specified servlet name
* is not known to this Context
*/
@Override
public void addServletMapping(String pattern, String name) {
addServletMapping(pattern, name, false);
}
/**
* Add a new servlet mapping, replacing any existing mapping for
* the specified pattern.
*
* @param pattern URL pattern to be mapped
* @param name Name of the corresponding servlet to execute
* @param jspWildCard true if name identifies the JspServlet
* and pattern contains a wildcard; false otherwise
*
* @exception IllegalArgumentException if the specified servlet name
* is not known to this Context
*/
@Override
public void addServletMapping(String pattern, String name,
boolean jspWildCard) {
// Validate the proposed mapping
if (findChild(name) == null)
throw new IllegalArgumentException
(sm.getString("standardContext.servletMap.name", name));
String decodedPattern = adjustURLPattern(UDecoder.URLDecode(pattern));
if (!validateURLPattern(decodedPattern))
throw new IllegalArgumentException
(sm.getString("standardContext.servletMap.pattern", decodedPattern));
// Add this mapping to our registered set
synchronized (servletMappingsLock) {
String name2 = servletMappings.get(decodedPattern);
if (name2 != null) {
// Don't allow more than one servlet on the same pattern
Wrapper wrapper = (Wrapper) findChild(name2);
wrapper.removeMapping(decodedPattern);
}
servletMappings.put(decodedPattern, name);
}
Wrapper wrapper = (Wrapper) findChild(name);
wrapper.addMapping(decodedPattern);
fireContainerEvent("addServletMapping", decodedPattern);
}
/**
* Add a new watched resource to the set recognized by this Context.
*
* @param name New watched resource file name
*/
@Override
public void addWatchedResource(String name) {
synchronized (watchedResourcesLock) {
String results[] = new String[watchedResources.length + 1];
for (int i = 0; i < watchedResources.length; i++)
results[i] = watchedResources[i];
results[watchedResources.length] = name;
watchedResources = results;
}
fireContainerEvent("addWatchedResource", name);
}
/**
* Add a new welcome file to the set recognized by this Context.
*
* @param name New welcome file name
*/
@Override
public void addWelcomeFile(String name) {
synchronized (welcomeFilesLock) {
// Welcome files from the application deployment descriptor
// completely replace those from the default conf/web.xml file
if (replaceWelcomeFiles) {
fireContainerEvent(CLEAR_WELCOME_FILES_EVENT, null);
welcomeFiles = new String[0];
setReplaceWelcomeFiles(false);
}
String results[] =new String[welcomeFiles.length + 1];
for (int i = 0; i < welcomeFiles.length; i++)
results[i] = welcomeFiles[i];
results[welcomeFiles.length] = name;
welcomeFiles = results;
}
if(this.getState().equals(LifecycleState.STARTED))
fireContainerEvent(ADD_WELCOME_FILE_EVENT, name);
}
/**
* Add the classname of a LifecycleListener to be added to each
* Wrapper appended to this Context.
*
* @param listener Java class name of a LifecycleListener class
*/
@Override
public void addWrapperLifecycle(String listener) {
synchronized (wrapperLifecyclesLock) {
String results[] =new String[wrapperLifecycles.length + 1];
for (int i = 0; i < wrapperLifecycles.length; i++)
results[i] = wrapperLifecycles[i];
results[wrapperLifecycles.length] = listener;
wrapperLifecycles = results;
}
fireContainerEvent("addWrapperLifecycle", listener);
}
/**
* Add the classname of a ContainerListener to be added to each
* Wrapper appended to this Context.
*
* @param listener Java class name of a ContainerListener class
*/
@Override
public void addWrapperListener(String listener) {
synchronized (wrapperListenersLock) {
String results[] =new String[wrapperListeners.length + 1];
for (int i = 0; i < wrapperListeners.length; i++)
results[i] = wrapperListeners[i];
results[wrapperListeners.length] = listener;
wrapperListeners = results;
}
fireContainerEvent("addWrapperListener", listener);
}
/**
* Factory method to create and return a new Wrapper instance, of
* the Java implementation class appropriate for this Context
* implementation. The constructor of the instantiated Wrapper
* will have been called, but no properties will have been set.
*/
@Override
public Wrapper createWrapper() {
Wrapper wrapper = null;
if (wrapperClass != null) {
try {
wrapper = (Wrapper) wrapperClass.newInstance();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error("createWrapper", t);
return (null);
}
} else {
wrapper = new StandardWrapper();
}
synchronized (instanceListenersLock) {
for (int i = 0; i < instanceListeners.length; i++) {
try {
Class<?> clazz = Class.forName(instanceListeners[i]);
InstanceListener listener =
(InstanceListener) clazz.newInstance();
wrapper.addInstanceListener(listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error("createWrapper", t);
return (null);
}
}
}
synchronized (wrapperLifecyclesLock) {
for (int i = 0; i < wrapperLifecycles.length; i++) {
try {
Class<?> clazz = Class.forName(wrapperLifecycles[i]);
LifecycleListener listener =
(LifecycleListener) clazz.newInstance();
wrapper.addLifecycleListener(listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error("createWrapper", t);
return (null);
}
}
}
synchronized (wrapperListenersLock) {
for (int i = 0; i < wrapperListeners.length; i++) {
try {
Class<?> clazz = Class.forName(wrapperListeners[i]);
ContainerListener listener =
(ContainerListener) clazz.newInstance();
wrapper.addContainerListener(listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error("createWrapper", t);
return (null);
}
}
}
return (wrapper);
}
/**
* Return the set of application listener class names configured
* for this application.
*/
@Override
public ApplicationListener[] findApplicationListeners() {
return (applicationListeners);
}
/**
* Return the set of application parameters for this application.
*/
@Override
public ApplicationParameter[] findApplicationParameters() {
synchronized (applicationParametersLock) {
return (applicationParameters);
}
}
/**
* Return the security constraints for this web application.
* If there are none, a zero-length array is returned.
*/
@Override
public SecurityConstraint[] findConstraints() {
return (constraints);
}
/**
* Return the error page entry for the specified HTTP error code,
* if any; otherwise return <code>null</code>.
*
* @param errorCode Error code to look up
*/
@Override
public ErrorPage findErrorPage(int errorCode) {
return statusPages.get(Integer.valueOf(errorCode));
}
/**
* Return the error page entry for the specified Java exception type,
* if any; otherwise return <code>null</code>.
*
* @param exceptionType Exception type to look up
*/
@Override
public ErrorPage findErrorPage(String exceptionType) {
synchronized (exceptionPages) {
return (exceptionPages.get(exceptionType));
}
}
/**
* Return the set of defined error pages for all specified error codes
* and exception types.
*/
@Override
public ErrorPage[] findErrorPages() {
synchronized(exceptionPages) {
synchronized(statusPages) {
ErrorPage results1[] = new ErrorPage[exceptionPages.size()];
results1 = exceptionPages.values().toArray(results1);
ErrorPage results2[] = new ErrorPage[statusPages.size()];
results2 = statusPages.values().toArray(results2);
ErrorPage results[] =
new ErrorPage[results1.length + results2.length];
for (int i = 0; i < results1.length; i++)
results[i] = results1[i];
for (int i = results1.length; i < results.length; i++)
results[i] = results2[i - results1.length];
return (results);
}
}
}
/**
* Return the filter definition for the specified filter name, if any;
* otherwise return <code>null</code>.
*
* @param filterName Filter name to look up
*/
@Override
public FilterDef findFilterDef(String filterName) {
synchronized (filterDefs) {
return (filterDefs.get(filterName));
}
}
/**
* Return the set of defined filters for this Context.
*/
@Override
public FilterDef[] findFilterDefs() {
synchronized (filterDefs) {
FilterDef results[] = new FilterDef[filterDefs.size()];
return (filterDefs.values().toArray(results));
}
}
/**
* Return the set of filter mappings for this Context.
*/
@Override
public FilterMap[] findFilterMaps() {
return filterMaps.asArray();
}
/**
* Return the set of InstanceListener classes that will be added to
* newly created Wrappers automatically.
*/
@Override
public String[] findInstanceListeners() {
synchronized (instanceListenersLock) {
return (instanceListeners);
}
}
/**
* Return the message destination with the specified name, if any;
* otherwise, return <code>null</code>.
*
* @param name Name of the desired message destination
*/
public MessageDestination findMessageDestination(String name) {
synchronized (messageDestinations) {
return (messageDestinations.get(name));
}
}
/**
* Return the set of defined message destinations for this web
* application. If none have been defined, a zero-length array
* is returned.
*/
public MessageDestination[] findMessageDestinations() {
synchronized (messageDestinations) {
MessageDestination results[] =
new MessageDestination[messageDestinations.size()];
return (messageDestinations.values().toArray(results));
}
}
/**
* Return the message destination ref with the specified name, if any;
* otherwise, return <code>null</code>.
*
* @param name Name of the desired message destination ref
*/
public MessageDestinationRef findMessageDestinationRef(String name) {
return namingResources.findMessageDestinationRef(name);
}
/**
* Return the set of defined message destination refs for this web
* application. If none have been defined, a zero-length array
* is returned.
*/
public MessageDestinationRef[] findMessageDestinationRefs() {
return namingResources.findMessageDestinationRefs();
}
/**
* Return the MIME type to which the specified extension is mapped,
* if any; otherwise return <code>null</code>.
*
* @param extension Extension to map to a MIME type
*/
@Override
public String findMimeMapping(String extension) {
return (mimeMappings.get(extension.toLowerCase(Locale.ENGLISH)));
}
/**
* Return the extensions for which MIME mappings are defined. If there
* are none, a zero-length array is returned.
*/
@Override
public String[] findMimeMappings() {
synchronized (mimeMappings) {
String results[] = new String[mimeMappings.size()];
return
(mimeMappings.keySet().toArray(results));
}
}
/**
* Return the value for the specified context initialization
* parameter name, if any; otherwise return <code>null</code>.
*
* @param name Name of the parameter to return
*/
@Override
public String findParameter(String name) {
synchronized (parameters) {
return (parameters.get(name));
}
}
/**
* Return the names of all defined context initialization parameters
* for this Context. If no parameters are defined, a zero-length
* array is returned.
*/
@Override
public String[] findParameters() {
synchronized (parameters) {
String results[] = new String[parameters.size()];
return (parameters.keySet().toArray(results));
}
}
/**
* For the given security role (as used by an application), return the
* corresponding role name (as defined by the underlying Realm) if there
* is one. Otherwise, return the specified role unchanged.
*
* @param role Security role to map
*/
@Override
public String findRoleMapping(String role) {
String realRole = null;
synchronized (roleMappings) {
realRole = roleMappings.get(role);
}
if (realRole != null)
return (realRole);
else
return (role);
}
/**
* Return <code>true</code> if the specified security role is defined
* for this application; otherwise return <code>false</code>.
*
* @param role Security role to verify
*/
@Override
public boolean findSecurityRole(String role) {
synchronized (securityRolesLock) {
for (int i = 0; i < securityRoles.length; i++) {
if (role.equals(securityRoles[i]))
return (true);
}
}
return (false);
}
/**
* Return the security roles defined for this application. If none
* have been defined, a zero-length array is returned.
*/
@Override
public String[] findSecurityRoles() {
synchronized (securityRolesLock) {
return (securityRoles);
}
}
/**
* Return the servlet name mapped by the specified pattern (if any);
* otherwise return <code>null</code>.
*
* @param pattern Pattern for which a mapping is requested
*/
@Override
public String findServletMapping(String pattern) {
synchronized (servletMappingsLock) {
return (servletMappings.get(pattern));
}
}
/**
* Return the patterns of all defined servlet mappings for this
* Context. If no mappings are defined, a zero-length array is returned.
*/
@Override
public String[] findServletMappings() {
synchronized (servletMappingsLock) {
String results[] = new String[servletMappings.size()];
return
(servletMappings.keySet().toArray(results));
}
}
/**
* Return the context-relative URI of the error page for the specified
* HTTP status code, if any; otherwise return <code>null</code>.
*
* @param status HTTP status code to look up
*/
@Override
public String findStatusPage(int status) {
ErrorPage errorPage = statusPages.get(Integer.valueOf(status));
if (errorPage!=null) {
return errorPage.getLocation();
}
return null;
}
/**
* Return the set of HTTP status codes for which error pages have
* been specified. If none are specified, a zero-length array
* is returned.
*/
@Override
public int[] findStatusPages() {
synchronized (statusPages) {
int results[] = new int[statusPages.size()];
Iterator<Integer> elements = statusPages.keySet().iterator();
int i = 0;
while (elements.hasNext())
results[i++] = elements.next().intValue();
return (results);
}
}
/**
* Return <code>true</code> if the specified welcome file is defined
* for this Context; otherwise return <code>false</code>.
*
* @param name Welcome file to verify
*/
@Override
public boolean findWelcomeFile(String name) {
synchronized (welcomeFilesLock) {
for (int i = 0; i < welcomeFiles.length; i++) {
if (name.equals(welcomeFiles[i]))
return (true);
}
}
return (false);
}
/**
* Return the set of watched resources for this Context. If none are
* defined, a zero length array will be returned.
*/
@Override
public String[] findWatchedResources() {
synchronized (watchedResourcesLock) {
return watchedResources;
}
}
/**
* Return the set of welcome files defined for this Context. If none are
* defined, a zero-length array is returned.
*/
@Override
public String[] findWelcomeFiles() {
synchronized (welcomeFilesLock) {
return (welcomeFiles);
}
}
/**
* Return the set of LifecycleListener classes that will be added to
* newly created Wrappers automatically.
*/
@Override
public String[] findWrapperLifecycles() {
synchronized (wrapperLifecyclesLock) {
return (wrapperLifecycles);
}
}
/**
* Return the set of ContainerListener classes that will be added to
* newly created Wrappers automatically.
*/
@Override
public String[] findWrapperListeners() {
synchronized (wrapperListenersLock) {
return (wrapperListeners);
}
}
/**
* Reload this web application, if reloading is supported.
* <p>
* <b>IMPLEMENTATION NOTE</b>: This method is designed to deal with
* reloads required by changes to classes in the underlying repositories
* of our class loader and changes to the web.xml file. It does not handle
* changes to any context.xml file. If the context.xml has changed, you
* should stop this Context and create (and start) a new Context instance
* instead. Note that there is additional code in
* <code>CoyoteAdapter#postParseRequest()</code> to handle mapping requests
* to paused Contexts.
*
* @exception IllegalStateException if the <code>reloadable</code>
* property is set to <code>false</code>.
*/
@Override
public synchronized void reload() {
// Validate our current component state
if (!getState().isAvailable())
throw new IllegalStateException
(sm.getString("standardContext.notStarted", getName()));
if(log.isInfoEnabled())
log.info(sm.getString("standardContext.reloadingStarted",
getName()));
// Stop accepting requests temporarily.
setPaused(true);
try {
stop();
} catch (LifecycleException e) {
log.error(
sm.getString("standardContext.stoppingContext", getName()), e);
}
try {
start();
} catch (LifecycleException e) {
log.error(
sm.getString("standardContext.startingContext", getName()), e);
}
setPaused(false);
if(log.isInfoEnabled())
log.info(sm.getString("standardContext.reloadingCompleted",
getName()));
}
/**
* Remove the specified application listener class from the set of
* listeners for this application.
*
* @param listener Java class name of the listener to be removed
*/
@Override
public void removeApplicationListener(String listener) {
synchronized (applicationListenersLock) {
// Make sure this welcome file is currently present
int n = -1;
for (int i = 0; i < applicationListeners.length; i++) {
if (applicationListeners[i].getClassName().equals(listener)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified constraint
int j = 0;
ApplicationListener results[] =
new ApplicationListener[applicationListeners.length - 1];
for (int i = 0; i < applicationListeners.length; i++) {
if (i != n)
results[j++] = applicationListeners[i];
}
applicationListeners = results;
}
// Inform interested listeners
fireContainerEvent("removeApplicationListener", listener);
// FIXME - behavior if already started?
}
/**
* Remove the application parameter with the specified name from
* the set for this application.
*
* @param name Name of the application parameter to remove
*/
@Override
public void removeApplicationParameter(String name) {
synchronized (applicationParametersLock) {
// Make sure this parameter is currently present
int n = -1;
for (int i = 0; i < applicationParameters.length; i++) {
if (name.equals(applicationParameters[i].getName())) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified parameter
int j = 0;
ApplicationParameter results[] =
new ApplicationParameter[applicationParameters.length - 1];
for (int i = 0; i < applicationParameters.length; i++) {
if (i != n)
results[j++] = applicationParameters[i];
}
applicationParameters = results;
}
// Inform interested listeners
fireContainerEvent("removeApplicationParameter", name);
}
/**
* Add a child Container, only if the proposed child is an implementation
* of Wrapper.
*
* @param child Child container to be added
*
* @exception IllegalArgumentException if the proposed container is
* not an implementation of Wrapper
*/
@Override
public void removeChild(Container child) {
if (!(child instanceof Wrapper)) {
throw new IllegalArgumentException
(sm.getString("standardContext.notWrapper"));
}
super.removeChild(child);
}
/**
* Remove the specified security constraint from this web application.
*
* @param constraint Constraint to be removed
*/
@Override
public void removeConstraint(SecurityConstraint constraint) {
synchronized (constraintsLock) {
// Make sure this constraint is currently present
int n = -1;
for (int i = 0; i < constraints.length; i++) {
if (constraints[i].equals(constraint)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified constraint
int j = 0;
SecurityConstraint results[] =
new SecurityConstraint[constraints.length - 1];
for (int i = 0; i < constraints.length; i++) {
if (i != n)
results[j++] = constraints[i];
}
constraints = results;
}
// Inform interested listeners
fireContainerEvent("removeConstraint", constraint);
}
/**
* Remove the error page for the specified error code or
* Java language exception, if it exists; otherwise, no action is taken.
*
* @param errorPage The error page definition to be removed
*/
@Override
public void removeErrorPage(ErrorPage errorPage) {
String exceptionType = errorPage.getExceptionType();
if (exceptionType != null) {
synchronized (exceptionPages) {
exceptionPages.remove(exceptionType);
}
} else {
synchronized (statusPages) {
statusPages.remove(Integer.valueOf(errorPage.getErrorCode()));
}
}
fireContainerEvent("removeErrorPage", errorPage);
}
/**
* Remove the specified filter definition from this Context, if it exists;
* otherwise, no action is taken.
*
* @param filterDef Filter definition to be removed
*/
@Override
public void removeFilterDef(FilterDef filterDef) {
synchronized (filterDefs) {
filterDefs.remove(filterDef.getFilterName());
}
fireContainerEvent("removeFilterDef", filterDef);
}
/**
* Remove a filter mapping from this Context.
*
* @param filterMap The filter mapping to be removed
*/
@Override
public void removeFilterMap(FilterMap filterMap) {
filterMaps.remove(filterMap);
// Inform interested listeners
fireContainerEvent("removeFilterMap", filterMap);
}
/**
* Remove a class name from the set of InstanceListener classes that
* will be added to newly created Wrappers.
*
* @param listener Class name of an InstanceListener class to be removed
*/
@Override
public void removeInstanceListener(String listener) {
synchronized (instanceListenersLock) {
// Make sure this welcome file is currently present
int n = -1;
for (int i = 0; i < instanceListeners.length; i++) {
if (instanceListeners[i].equals(listener)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified constraint
int j = 0;
String results[] = new String[instanceListeners.length - 1];
for (int i = 0; i < instanceListeners.length; i++) {
if (i != n)
results[j++] = instanceListeners[i];
}
instanceListeners = results;
}
// Inform interested listeners
fireContainerEvent("removeInstanceListener", listener);
}
/**
* Remove any message destination with the specified name.
*
* @param name Name of the message destination to remove
*/
public void removeMessageDestination(String name) {
synchronized (messageDestinations) {
messageDestinations.remove(name);
}
fireContainerEvent("removeMessageDestination", name);
}
/**
* Remove any message destination ref with the specified name.
*
* @param name Name of the message destination ref to remove
*/
public void removeMessageDestinationRef(String name) {
namingResources.removeMessageDestinationRef(name);
fireContainerEvent("removeMessageDestinationRef", name);
}
/**
* Remove the MIME mapping for the specified extension, if it exists;
* otherwise, no action is taken.
*
* @param extension Extension to remove the mapping for
*/
@Override
public void removeMimeMapping(String extension) {
synchronized (mimeMappings) {
mimeMappings.remove(extension);
}
fireContainerEvent("removeMimeMapping", extension);
}
/**
* Remove the context initialization parameter with the specified
* name, if it exists; otherwise, no action is taken.
*
* @param name Name of the parameter to remove
*/
@Override
public void removeParameter(String name) {
synchronized (parameters) {
parameters.remove(name);
}
fireContainerEvent("removeParameter", name);
}
/**
* Remove any security role reference for the specified name
*
* @param role Security role (as used in the application) to remove
*/
@Override
public void removeRoleMapping(String role) {
synchronized (roleMappings) {
roleMappings.remove(role);
}
fireContainerEvent("removeRoleMapping", role);
}
/**
* Remove any security role with the specified name.
*
* @param role Security role to remove
*/
@Override
public void removeSecurityRole(String role) {
synchronized (securityRolesLock) {
// Make sure this security role is currently present
int n = -1;
for (int i = 0; i < securityRoles.length; i++) {
if (role.equals(securityRoles[i])) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified security role
int j = 0;
String results[] = new String[securityRoles.length - 1];
for (int i = 0; i < securityRoles.length; i++) {
if (i != n)
results[j++] = securityRoles[i];
}
securityRoles = results;
}
// Inform interested listeners
fireContainerEvent("removeSecurityRole", role);
}
/**
* Remove any servlet mapping for the specified pattern, if it exists;
* otherwise, no action is taken.
*
* @param pattern URL pattern of the mapping to remove
*/
@Override
public void removeServletMapping(String pattern) {
String name = null;
synchronized (servletMappingsLock) {
name = servletMappings.remove(pattern);
}
Wrapper wrapper = (Wrapper) findChild(name);
if( wrapper != null ) {
wrapper.removeMapping(pattern);
}
fireContainerEvent("removeServletMapping", pattern);
}
/**
* Remove the specified watched resource name from the list associated
* with this Context.
*
* @param name Name of the watched resource to be removed
*/
@Override
public void removeWatchedResource(String name) {
synchronized (watchedResourcesLock) {
// Make sure this watched resource is currently present
int n = -1;
for (int i = 0; i < watchedResources.length; i++) {
if (watchedResources[i].equals(name)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified watched resource
int j = 0;
String results[] = new String[watchedResources.length - 1];
for (int i = 0; i < watchedResources.length; i++) {
if (i != n)
results[j++] = watchedResources[i];
}
watchedResources = results;
}
fireContainerEvent("removeWatchedResource", name);
}
/**
* Remove the specified welcome file name from the list recognized
* by this Context.
*
* @param name Name of the welcome file to be removed
*/
@Override
public void removeWelcomeFile(String name) {
synchronized (welcomeFilesLock) {
// Make sure this welcome file is currently present
int n = -1;
for (int i = 0; i < welcomeFiles.length; i++) {
if (welcomeFiles[i].equals(name)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified constraint
int j = 0;
String results[] = new String[welcomeFiles.length - 1];
for (int i = 0; i < welcomeFiles.length; i++) {
if (i != n)
results[j++] = welcomeFiles[i];
}
welcomeFiles = results;
}
// Inform interested listeners
if(this.getState().equals(LifecycleState.STARTED))
fireContainerEvent(REMOVE_WELCOME_FILE_EVENT, name);
}
/**
* Remove a class name from the set of LifecycleListener classes that
* will be added to newly created Wrappers.
*
* @param listener Class name of a LifecycleListener class to be removed
*/
@Override
public void removeWrapperLifecycle(String listener) {
synchronized (wrapperLifecyclesLock) {
// Make sure this welcome file is currently present
int n = -1;
for (int i = 0; i < wrapperLifecycles.length; i++) {
if (wrapperLifecycles[i].equals(listener)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified constraint
int j = 0;
String results[] = new String[wrapperLifecycles.length - 1];
for (int i = 0; i < wrapperLifecycles.length; i++) {
if (i != n)
results[j++] = wrapperLifecycles[i];
}
wrapperLifecycles = results;
}
// Inform interested listeners
fireContainerEvent("removeWrapperLifecycle", listener);
}
/**
* Remove a class name from the set of ContainerListener classes that
* will be added to newly created Wrappers.
*
* @param listener Class name of a ContainerListener class to be removed
*/
@Override
public void removeWrapperListener(String listener) {
synchronized (wrapperListenersLock) {
// Make sure this welcome file is currently present
int n = -1;
for (int i = 0; i < wrapperListeners.length; i++) {
if (wrapperListeners[i].equals(listener)) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified constraint
int j = 0;
String results[] = new String[wrapperListeners.length - 1];
for (int i = 0; i < wrapperListeners.length; i++) {
if (i != n)
results[j++] = wrapperListeners[i];
}
wrapperListeners = results;
}
// Inform interested listeners
fireContainerEvent("removeWrapperListener", listener);
}
/**
* Gets the cumulative processing times of all servlets in this
* StandardContext.
*
* @return Cumulative processing times of all servlets in this
* StandardContext
*/
public long getProcessingTime() {
long result = 0;
Container[] children = findChildren();
if (children != null) {
for( int i=0; i< children.length; i++ ) {
result += ((StandardWrapper)children[i]).getProcessingTime();
}
}
return result;
}
/**
* Gets the maximum processing time of all servlets in this
* StandardContext.
*
* @return Maximum processing time of all servlets in this
* StandardContext
*/
public long getMaxTime() {
long result = 0;
long time;
Container[] children = findChildren();
if (children != null) {
for( int i=0; i< children.length; i++ ) {
time = ((StandardWrapper)children[i]).getMaxTime();
if (time > result)
result = time;
}
}
return result;
}
/**
* Gets the minimum processing time of all servlets in this
* StandardContext.
*
* @return Minimum processing time of all servlets in this
* StandardContext
*/
public long getMinTime() {
long result = -1;
long time;
Container[] children = findChildren();
if (children != null) {
for( int i=0; i< children.length; i++ ) {
time = ((StandardWrapper)children[i]).getMinTime();
if (result < 0 || time < result)
result = time;
}
}
return result;
}
/**
* Gets the cumulative request count of all servlets in this
* StandardContext.
*
* @return Cumulative request count of all servlets in this
* StandardContext
*/
public int getRequestCount() {
int result = 0;
Container[] children = findChildren();
if (children != null) {
for( int i=0; i< children.length; i++ ) {
result += ((StandardWrapper)children[i]).getRequestCount();
}
}
return result;
}
/**
* Gets the cumulative error count of all servlets in this
* StandardContext.
*
* @return Cumulative error count of all servlets in this
* StandardContext
*/
public int getErrorCount() {
int result = 0;
Container[] children = findChildren();
if (children != null) {
for( int i=0; i< children.length; i++ ) {
result += ((StandardWrapper)children[i]).getErrorCount();
}
}
return result;
}
/**
* Return the real path for a given virtual path, if possible; otherwise
* return <code>null</code>.
*
* @param path The path to the desired resource
*/
@Override
public String getRealPath(String path) {
if (resources != null) {
return resources.getResource(path).getCanonicalPath();
}
return null;
}
/**
* hook to register that we need to scan for security annotations.
* @param wrapper The wrapper for the Servlet that was added
*/
public ServletRegistration.Dynamic dynamicServletAdded(Wrapper wrapper) {
Servlet s = wrapper.getServlet();
if (s != null && createdServlets.contains(s)) {
// Mark the wrapper to indicate annotations need to be scanned
wrapper.setServletSecurityAnnotationScanRequired(true);
}
return new ApplicationServletRegistration(wrapper, this);
}
/**
* hook to track which registrations need annotation scanning
* @param servlet
*/
public void dynamicServletCreated(Servlet servlet) {
createdServlets.add(servlet);
}
/**
* A helper class to manage the filter mappings in a Context.
*/
private static final class ContextFilterMaps {
private final Object lock = new Object();
/**
* The set of filter mappings for this application, in the order they
* were defined in the deployment descriptor with additional mappings
* added via the {@link ServletContext} possibly both before and after
* those defined in the deployment descriptor.
*/
private FilterMap[] array = new FilterMap[0];
/**
* Filter mappings added via {@link ServletContext} may have to be
* inserted before the mappings in the deployment descriptor but must be
* inserted in the order the {@link ServletContext} methods are called.
* This isn't an issue for the mappings added after the deployment
* descriptor - they are just added to the end - but correctly the
* adding mappings before the deployment descriptor mappings requires
* knowing where the last 'before' mapping was added.
*/
private int insertPoint = 0;
/**
* Return the set of filter mappings.
*/
public FilterMap[] asArray() {
synchronized (lock) {
return array;
}
}
/**
* Add a filter mapping at the end of the current set of filter
* mappings.
*
* @param filterMap
* The filter mapping to be added
*/
public void add(FilterMap filterMap) {
synchronized (lock) {
FilterMap results[] = Arrays.copyOf(array, array.length + 1);
results[array.length] = filterMap;
array = results;
}
}
/**
* Add a filter mapping before the mappings defined in the deployment
* descriptor but after any other mappings added via this method.
*
* @param filterMap
* The filter mapping to be added
*/
public void addBefore(FilterMap filterMap) {
synchronized (lock) {
FilterMap results[] = new FilterMap[array.length + 1];
System.arraycopy(array, 0, results, 0, insertPoint);
System.arraycopy(array, insertPoint, results, insertPoint + 1,
array.length - insertPoint);
results[insertPoint] = filterMap;
array = results;
insertPoint++;
}
}
/**
* Remove a filter mapping.
*
* @param filterMap The filter mapping to be removed
*/
public void remove(FilterMap filterMap) {
synchronized (lock) {
// Make sure this filter mapping is currently present
int n = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == filterMap) {
n = i;
break;
}
}
if (n < 0)
return;
// Remove the specified filter mapping
FilterMap results[] = new FilterMap[array.length - 1];
System.arraycopy(array, 0, results, 0, n);
System.arraycopy(array, n + 1, results, n, (array.length - 1)
- n);
array = results;
if (n < insertPoint) {
insertPoint--;
}
}
}
}
// --------------------------------------------------------- Public Methods
/**
* Configure and initialize the set of filters for this Context.
* Return <code>true</code> if all filter initialization completed
* successfully, or <code>false</code> otherwise.
*/
public boolean filterStart() {
if (getLogger().isDebugEnabled())
getLogger().debug("Starting filters");
// Instantiate and record a FilterConfig for each defined filter
boolean ok = true;
synchronized (filterConfigs) {
filterConfigs.clear();
Iterator<String> names = filterDefs.keySet().iterator();
while (names.hasNext()) {
String name = names.next();
if (getLogger().isDebugEnabled())
getLogger().debug(" Starting filter '" + name + "'");
ApplicationFilterConfig filterConfig = null;
try {
filterConfig =
new ApplicationFilterConfig(this, filterDefs.get(name));
filterConfigs.put(name, filterConfig);
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
getLogger().error
(sm.getString("standardContext.filterStart", name), t);
ok = false;
}
}
}
return (ok);
}
/**
* Finalize and release the set of filters for this Context.
* Return <code>true</code> if all filter finalization completed
* successfully, or <code>false</code> otherwise.
*/
public boolean filterStop() {
if (getLogger().isDebugEnabled())
getLogger().debug("Stopping filters");
// Release all Filter and FilterConfig instances
synchronized (filterConfigs) {
Iterator<String> names = filterConfigs.keySet().iterator();
while (names.hasNext()) {
String name = names.next();
if (getLogger().isDebugEnabled())
getLogger().debug(" Stopping filter '" + name + "'");
ApplicationFilterConfig filterConfig = filterConfigs.get(name);
filterConfig.release();
}
filterConfigs.clear();
}
return (true);
}
/**
* Find and return the initialized <code>FilterConfig</code> for the
* specified filter name, if any; otherwise return <code>null</code>.
*
* @param name Name of the desired filter
*/
public FilterConfig findFilterConfig(String name) {
return (filterConfigs.get(name));
}
/**
* Configure the set of instantiated application event listeners
* for this Context. Return <code>true</code> if all listeners wre
* initialized successfully, or <code>false</code> otherwise.
*/
public boolean listenerStart() {
if (log.isDebugEnabled())
log.debug("Configuring application event listeners");
// Instantiate the required listeners
ApplicationListener listeners[] = findApplicationListeners();
Object results[] = new Object[listeners.length];
boolean ok = true;
Set<Object> noPluggabilityListeners = new HashSet<>();
for (int i = 0; i < results.length; i++) {
if (getLogger().isDebugEnabled())
getLogger().debug(" Configuring event listener class '" +
listeners[i] + "'");
try {
ApplicationListener listener = listeners[i];
results[i] = instanceManager.newInstance(
listener.getClassName());
if (listener.isPluggabilityBlocked()) {
noPluggabilityListeners.add(results[i]);
}
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
getLogger().error
(sm.getString("standardContext.applicationListener",
listeners[i]), t);
ok = false;
}
}
if (!ok) {
getLogger().error(sm.getString("standardContext.applicationSkipped"));
return (false);
}
// Sort listeners in two arrays
ArrayList<Object> eventListeners = new ArrayList<>();
ArrayList<Object> lifecycleListeners = new ArrayList<>();
for (int i = 0; i < results.length; i++) {
if ((results[i] instanceof ServletContextAttributeListener)
|| (results[i] instanceof ServletRequestAttributeListener)
|| (results[i] instanceof ServletRequestListener)
|| (results[i] instanceof HttpSessionIdListener)
|| (results[i] instanceof HttpSessionAttributeListener)) {
eventListeners.add(results[i]);
}
if ((results[i] instanceof ServletContextListener)
|| (results[i] instanceof HttpSessionListener)) {
lifecycleListeners.add(results[i]);
}
}
// Listener instances may have been added directly to this Context by
// ServletContextInitializers and other code via the pluggability APIs.
// Put them these listeners after the ones defined in web.xml and/or
// annotations then overwrite the list of instances with the new, full
// list.
for (Object eventListener: getApplicationEventListeners()) {
eventListeners.add(eventListener);
}
setApplicationEventListeners(eventListeners.toArray());
for (Object lifecycleListener: getApplicationLifecycleListeners()) {
lifecycleListeners.add(lifecycleListener);
if (lifecycleListener instanceof ServletContextListener) {
noPluggabilityListeners.add(lifecycleListener);
}
}
setApplicationLifecycleListeners(lifecycleListeners.toArray());
// Send application start events
if (getLogger().isDebugEnabled())
getLogger().debug("Sending application start events");
// Ensure context is not null
getServletContext();
context.setNewServletContextListenerAllowed(false);
Object instances[] = getApplicationLifecycleListeners();
if (instances == null || instances.length == 0) {
return ok;
}
ServletContextEvent event =
new ServletContextEvent(getServletContext());
ServletContextEvent tldEvent = null;
if (noPluggabilityListeners.size() > 0) {
tldEvent = new ServletContextEvent(new NoPluggabilityServletContext(
getServletContext()));
}
for (int i = 0; i < instances.length; i++) {
if (instances[i] == null)
continue;
if (!(instances[i] instanceof ServletContextListener))
continue;
ServletContextListener listener =
(ServletContextListener) instances[i];
try {
fireContainerEvent("beforeContextInitialized", listener);
if (noPluggabilityListeners.contains(listener)) {
listener.contextInitialized(tldEvent);
} else {
listener.contextInitialized(event);
}
fireContainerEvent("afterContextInitialized", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
fireContainerEvent("afterContextInitialized", listener);
getLogger().error
(sm.getString("standardContext.listenerStart",
instances[i].getClass().getName()), t);
ok = false;
}
}
return (ok);
}
/**
* Send an application stop event to all interested listeners.
* Return <code>true</code> if all events were sent successfully,
* or <code>false</code> otherwise.
*/
public boolean listenerStop() {
if (log.isDebugEnabled())
log.debug("Sending application stop events");
boolean ok = true;
Object listeners[] = getApplicationLifecycleListeners();
if (listeners != null && listeners.length > 0) {
ServletContextEvent event =
new ServletContextEvent(getServletContext());
for (int i = 0; i < listeners.length; i++) {
int j = (listeners.length - 1) - i;
if (listeners[j] == null)
continue;
if (listeners[j] instanceof ServletContextListener) {
ServletContextListener listener =
(ServletContextListener) listeners[j];
try {
fireContainerEvent("beforeContextDestroyed", listener);
listener.contextDestroyed(event);
fireContainerEvent("afterContextDestroyed", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
fireContainerEvent("afterContextDestroyed", listener);
getLogger().error
(sm.getString("standardContext.listenerStop",
listeners[j].getClass().getName()), t);
ok = false;
}
}
try {
getInstanceManager().destroyInstance(listeners[j]);
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
getLogger().error
(sm.getString("standardContext.listenerStop",
listeners[j].getClass().getName()), t);
ok = false;
}
}
}
// Annotation processing
listeners = getApplicationEventListeners();
if (listeners != null) {
for (int i = 0; i < listeners.length; i++) {
int j = (listeners.length - 1) - i;
if (listeners[j] == null)
continue;
try {
getInstanceManager().destroyInstance(listeners[j]);
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
getLogger().error
(sm.getString("standardContext.listenerStop",
listeners[j].getClass().getName()), t);
ok = false;
}
}
}
setApplicationEventListeners(null);
setApplicationLifecycleListeners(null);
return (ok);
}
/**
* Allocate resources, including proxy.
* Return <code>true</code> if initialization was successfull,
* or <code>false</code> otherwise.
*/
public boolean resourcesStart() throws LifecycleException {
boolean ok = true;
resources.setAllowLinking(isAllowLinking());
resources.setCachingAllowed(isCachingAllowed());
resources.setCacheTtl(getCacheTTL());
resources.setCacheMaxSize(getCacheMaxSize());
resources.setCacheMaxObjectSize(getCacheObjectMaxSize());
// May have been started (but not fully configured) in init() so no need
// to start the resources if they are already available
if (!resources.getState().isAvailable()) {
resources.start();
}
if (effectiveMajorVersion >=3 && addWebinfClassesResources) {
WebResource webinfClassesResource = resources.getResource(
"/WEB-INF/classes/META-INF/resources");
if (webinfClassesResource.isDirectory()) {
getResources().createWebResourceSet(
WebResourceRoot.ResourceSetType.RESOURCE_JAR,
webinfClassesResource.getURL(), "/", "/");
}
}
return ok;
}
/**
* Deallocate resources and destroy proxy.
*/
public boolean resourcesStop() {
boolean ok = true;
Lock writeLock = resourcesLock.writeLock();
writeLock.lock();
try {
if (resources != null) {
resources.stop();
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("standardContext.resourcesStop"), t);
ok = false;
} finally {
writeLock.unlock();
}
return ok;
}
/**
* Load and initialize all servlets marked "load on startup" in the
* web application deployment descriptor.
*
* @param children Array of wrappers for all currently defined
* servlets (including those not declared load on startup)
*/
public void loadOnStartup(Container children[]) {
// Collect "load on startup" servlets that need to be initialized
TreeMap<Integer, ArrayList<Wrapper>> map = new TreeMap<>();
for (int i = 0; i < children.length; i++) {
Wrapper wrapper = (Wrapper) children[i];
int loadOnStartup = wrapper.getLoadOnStartup();
if (loadOnStartup < 0)
continue;
Integer key = Integer.valueOf(loadOnStartup);
ArrayList<Wrapper> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
map.put(key, list);
}
list.add(wrapper);
}
// Load the collected "load on startup" servlets
for (ArrayList<Wrapper> list : map.values()) {
for (Wrapper wrapper : list) {
try {
wrapper.load();
} catch (ServletException e) {
getLogger().error(sm.getString("standardWrapper.loadException",
getName()), StandardWrapper.getRootCause(e));
// NOTE: load errors (including a servlet that throws
// UnavailableException from tht init() method) are NOT
// fatal to application startup
}
}
}
}
/**
* Start this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void startInternal() throws LifecycleException {
if(log.isDebugEnabled())
log.debug("Starting " + getBaseName());
// Send j2ee.state.starting notification
if (this.getObjectName() != null) {
Notification notification = new Notification("j2ee.state.starting",
this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
setConfigured(false);
boolean ok = true;
// Currently this is effectively a NO-OP but needs to be called to
// ensure the NamingResources follows the correct lifecycle
if (namingResources != null) {
namingResources.start();
}
// Add missing components as necessary
if (getResources() == null) { // (1) Required by Loader
if (log.isDebugEnabled())
log.debug("Configuring default Resources");
try {
setResources(new StandardRoot(this));
} catch (IllegalArgumentException e) {
log.error("Error initializing resources: " + e.getMessage());
ok = false;
}
}
if (ok) {
if (!resourcesStart()) {
log.error( "Error in resourceStart()");
ok = false;
}
}
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
boolean dependencyCheck = true;
try {
dependencyCheck = ExtensionValidator.validateApplication
(getResources(), this);
} catch (IOException ioe) {
log.error("Error in dependencyCheck", ioe);
dependencyCheck = false;
}
if (!dependencyCheck) {
// do not make application available if depency check fails
ok = false;
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
useNaming = false;
}
if (ok && isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener ncl = new NamingContextListener();
ncl.setName(getNamingContextName());
ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());
addLifecycleListener(ncl);
setNamingContextListener(ncl);
}
}
// Standard container startup
if (log.isDebugEnabled())
log.debug("Processing standard container startup");
// Binding thread
ClassLoader oldCCL = bindThread();
try {
if (ok) {
// Start our subordinate components, if any
Loader loader = getLoader();
if ((loader != null) && (loader instanceof Lifecycle))
((Lifecycle) loader).start();
// since the loader just started, the webapp classloader is now
// created.
setClassLoaderProperty("antiJARLocking", getAntiJARLocking());
setClassLoaderProperty("clearReferencesStatic",
getClearReferencesStatic());
setClassLoaderProperty("clearReferencesStopThreads",
getClearReferencesStopThreads());
setClassLoaderProperty("clearReferencesStopTimerThreads",
getClearReferencesStopTimerThreads());
setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread",
getClearReferencesHttpClientKeepAliveThread());
// By calling unbindThread and bindThread in a row, we setup the
// current Thread CCL to be the webapp classloader
unbindThread(oldCCL);
oldCCL = bindThread();
// Initialize logger again. Other components might have used it
// too early, so it should be reset.
logger = null;
getLogger();
Cluster cluster = getClusterInternal();
if ((cluster != null) && (cluster instanceof Lifecycle))
((Lifecycle) cluster).start();
Realm realm = getRealmInternal();
if ((realm != null) && (realm instanceof Lifecycle))
((Lifecycle) realm).start();
// Notify our interested LifecycleListeners
fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);
// Start our child containers, if not already started
for (Container child : findChildren()) {
if (!child.getState().isAvailable()) {
child.start();
}
}
// Start the Valves in our pipeline (including the basic),
// if any
if (pipeline instanceof Lifecycle) {
((Lifecycle) pipeline).start();
}
// Acquire clustered manager
Manager contextManager = null;
Manager manager = getManager();
if (manager == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("standardContext.cluster.noManager",
Boolean.valueOf((getCluster() != null)),
Boolean.valueOf(distributable)));
}
if ( (getCluster() != null) && distributable) {
try {
contextManager = getCluster().createManager(getName());
} catch (Exception ex) {
log.error("standardContext.clusterFail", ex);
ok = false;
}
} else {
contextManager = new StandardManager();
}
}
// Configure default manager if none was specified
if (contextManager != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("standardContext.manager",
contextManager.getClass().getName()));
}
setManager(contextManager);
}
if (manager!=null && (getCluster() != null) && distributable) {
//let the cluster know that there is a context that is distributable
//and that it has its own manager
getCluster().registerManager(manager);
}
}
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
if (!getConfigured()) {
log.error( "Error getConfigured");
ok = false;
}
// We put the resources into the servlet context
if (ok)
getServletContext().setAttribute
(Globals.RESOURCES_ATTR, getResources());
// Binding thread
oldCCL = bindThread();
if (ok ) {
if (getInstanceManager() == null) {
javax.naming.Context context = null;
if (isUseNaming() && getNamingContextListener() != null) {
context = getNamingContextListener().getEnvContext();
}
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResourcesImpl(): getNamingResources());
setInstanceManager(new DefaultInstanceManager(context,
injectionMap, this, this.getClass().getClassLoader()));
getServletContext().setAttribute(
InstanceManager.class.getName(), getInstanceManager());
}
}
try {
// Create context attributes that will be required
if (ok) {
getServletContext().setAttribute(
JarScanner.class.getName(), getJarScanner());
}
// Set up the context init params
mergeParameters();
// Call ServletContainerInitializers
for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry :
initializers.entrySet()) {
try {
entry.getKey().onStartup(entry.getValue(),
getServletContext());
} catch (ServletException e) {
log.error(sm.getString("standardContext.sciFail"), e);
ok = false;
break;
}
}
// Configure and call application event listeners
if (ok) {
if (!listenerStart()) {
log.error( "Error listenerStart");
ok = false;
}
}
// Check constraints for uncovered HTTP methods
// Needs to be after SCIs and listeners as they may programatically
// change constraints
if (ok) {
checkConstraintsForUncoveredMethods(findConstraints());
}
try {
// Start manager
Manager manager = getManager();
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) getManager()).start();
}
} catch(Exception e) {
log.error("Error manager.start()", e);
ok = false;
}
// Configure and call application filters
if (ok) {
if (!filterStart()) {
log.error("Error filterStart");
ok = false;
}
}
// Load and initialize all "load on startup" servlets
if (ok) {
loadOnStartup(findChildren());
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (ok) {
if (log.isDebugEnabled())
log.debug("Starting completed");
} else {
log.error(sm.getString("standardContext.startFailed", getName()));
}
startTime=System.currentTimeMillis();
// Send j2ee.state.running notification
if (ok && (this.getObjectName() != null)) {
Notification notification =
new Notification("j2ee.state.running", this.getObjectName(),
sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
// Close all JARs right away to avoid always opening a peak number
// of files on startup
if (getLoader() instanceof WebappLoader) {
((WebappLoader) getLoader()).closeJARs(true);
}
// Reinitializing if something went wrong
if (!ok) {
setState(LifecycleState.FAILED);
} else {
setState(LifecycleState.STARTING);
}
}
private void checkConstraintsForUncoveredMethods(
SecurityConstraint[] constraints) {
SecurityConstraint[] newConstraints =
SecurityConstraint.findUncoveredHttpMethods(constraints,
getDenyUncoveredHttpMethods(), getLogger());
for (SecurityConstraint constraint : newConstraints) {
addConstraint(constraint);
}
}
private void setClassLoaderProperty(String name, boolean value) {
ClassLoader cl = getLoader().getClassLoader();
if (!IntrospectionUtils.setProperty(cl, name, Boolean.toString(value))) {
// Failed to set
log.info(sm.getString(
"standardContext.webappClassLoader.missingProperty",
name, Boolean.toString(value)));
}
}
private Map<String, Map<String, String>> buildInjectionMap(NamingResourcesImpl namingResources) {
Map<String, Map<String, String>> injectionMap = new HashMap<>();
for (Injectable resource: namingResources.findLocalEjbs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findEjbs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findEnvironments()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findMessageDestinationRefs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findResourceEnvRefs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findResources()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findServices()) {
addInjectionTarget(resource, injectionMap);
}
return injectionMap;
}
private void addInjectionTarget(Injectable resource, Map<String, Map<String, String>> injectionMap) {
List<InjectionTarget> injectionTargets = resource.getInjectionTargets();
if (injectionTargets != null && injectionTargets.size() > 0) {
String jndiName = resource.getName();
for (InjectionTarget injectionTarget: injectionTargets) {
String clazz = injectionTarget.getTargetClass();
Map<String, String> injections = injectionMap.get(clazz);
if (injections == null) {
injections = new HashMap<>();
injectionMap.put(clazz, injections);
}
injections.put(injectionTarget.getTargetName(), jndiName);
}
}
}
/**
* Merge the context initialization parameters specified in the application
* deployment descriptor with the application parameters described in the
* server configuration, respecting the <code>override</code> property of
* the application parameters appropriately.
*/
private void mergeParameters() {
Map<String,String> mergedParams = new HashMap<>();
String names[] = findParameters();
for (int i = 0; i < names.length; i++) {
mergedParams.put(names[i], findParameter(names[i]));
}
ApplicationParameter params[] = findApplicationParameters();
for (int i = 0; i < params.length; i++) {
if (params[i].getOverride()) {
if (mergedParams.get(params[i].getName()) == null) {
mergedParams.put(params[i].getName(),
params[i].getValue());
}
} else {
mergedParams.put(params[i].getName(), params[i].getValue());
}
}
ServletContext sc = getServletContext();
for (Map.Entry<String,String> entry : mergedParams.entrySet()) {
sc.setInitParameter(entry.getKey(), entry.getValue());
}
}
/**
* Stop this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void stopInternal() throws LifecycleException {
// Send j2ee.state.stopping notification
if (this.getObjectName() != null) {
Notification notification =
new Notification("j2ee.state.stopping", this.getObjectName(),
sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
setState(LifecycleState.STOPPING);
// Binding thread
ClassLoader oldCCL = bindThread();
try {
// Stop our child containers, if any
final Container[] children = findChildren();
ClassLoader old = bindThread();
try {
// Stop ContainerBackgroundProcessor thread
threadStop();
for (int i = 0; i < children.length; i++) {
children[i].stop();
}
// Stop our filters
filterStop();
Manager manager = getManager();
if (manager != null && manager instanceof Lifecycle &&
((Lifecycle) manager).getState().isAvailable()) {
((Lifecycle) manager).stop();
}
// Stop our application listeners
listenerStop();
} finally{
unbindThread(old);
}
// Finalize our character set mapper
setCharsetMapper(null);
// Normal container shutdown processing
if (log.isDebugEnabled())
log.debug("Processing standard container shutdown");
// JNDI resources are unbound in CONFIGURE_STOP_EVENT so stop
// naming resoucres before they are unbound since NamingResoucres
// does a JNDI lookup to retrieve the resource. This needs to be
// after the application has finished with the resource
if (namingResources != null) {
namingResources.stop();
}
fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null);
// Stop the Valves in our pipeline (including the basic), if any
if (pipeline instanceof Lifecycle &&
((Lifecycle) pipeline).getState().isAvailable()) {
((Lifecycle) pipeline).stop();
}
// Clear all application-originated servlet context attributes
if (context != null)
context.clearAttributes();
Realm realm = getRealmInternal();
if ((realm != null) && (realm instanceof Lifecycle)) {
((Lifecycle) realm).stop();
}
Cluster cluster = getClusterInternal();
if ((cluster != null) && (cluster instanceof Lifecycle)) {
((Lifecycle) cluster).stop();
}
Loader loader = getLoader();
if ((loader != null) && (loader instanceof Lifecycle)) {
((Lifecycle) loader).stop();
}
// Stop resources
resourcesStop();
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Send j2ee.state.stopped notification
if (this.getObjectName() != null) {
Notification notification =
new Notification("j2ee.state.stopped", this.getObjectName(),
sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
// Reset application context
context = null;
// This object will no longer be visible or used.
try {
resetContext();
} catch( Exception ex ) {
log.error( "Error reseting context " + this + " " + ex, ex );
}
//reset the instance manager
instanceManager = null;
if (log.isDebugEnabled())
log.debug("Stopping complete");
}
/** Destroy needs to clean up the context completely.
*
* The problem is that undoing all the config in start() and restoring
* a 'fresh' state is impossible. After stop()/destroy()/init()/start()
* we should have the same state as if a fresh start was done - i.e
* read modified web.xml, etc. This can only be done by completely
* removing the context object and remapping a new one, or by cleaning
* up everything.
*
* XXX Should this be done in stop() ?
*
*/
@Override
protected void destroyInternal() throws LifecycleException {
// If in state NEW when destroy is called, the object name will never
// have been set so the notification can't be created
if (getObjectName() != null) {
// Send j2ee.object.deleted notification
Notification notification =
new Notification("j2ee.object.deleted", this.getObjectName(),
sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
if (namingResources != null) {
namingResources.destroy();
}
synchronized (instanceListenersLock) {
instanceListeners = new String[0];
}
Loader loader = getLoader();
if ((loader != null) && (loader instanceof Lifecycle)) {
((Lifecycle) loader).destroy();
}
Manager manager = getManager();
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) manager).destroy();
}
if (resources != null) {
resources.destroy();
}
super.destroyInternal();
}
@Override
public void backgroundProcess() {
if (!getState().isAvailable())
return;
Loader loader = getLoader();
if (loader != null) {
try {
loader.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.loader", loader), e);
}
}
Manager manager = getManager();
if (manager != null) {
try {
manager.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.manager", manager),
e);
}
}
WebResourceRoot resources = getResources();
if (resources != null) {
try {
resources.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.resources",
resources), e);
}
}
super.backgroundProcess();
}
private void resetContext() throws Exception {
// Restore the original state ( pre reading web.xml in start )
// If you extend this - override this method and make sure to clean up
// Don't reset anything that is read from a <Context.../> element since
// <Context .../> elements are read at initialisation will not be read
// again for this object
for (Container child : findChildren()) {
removeChild(child);
}
startupTime = 0;
startTime = 0;
tldScanTime = 0;
// Bugzilla 32867
distributable = false;
applicationListeners = new ApplicationListener[0];
applicationEventListenersObjects = new Object[0];
applicationLifecycleListenersObjects = new Object[0];
jspConfigDescriptor = null;
initializers.clear();
createdServlets.clear();
postConstructMethods.clear();
preDestroyMethods.clear();
if(log.isDebugEnabled())
log.debug("resetContext " + getObjectName());
}
/**
* Return a String representation of this component.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (getParent() != null) {
sb.append(getParent().toString());
sb.append(".");
}
sb.append("StandardContext[");
sb.append(getName());
sb.append("]");
return (sb.toString());
}
// ------------------------------------------------------ Protected Methods
/**
* Adjust the URL pattern to begin with a leading slash, if appropriate
* (i.e. we are running a servlet 2.2 application). Otherwise, return
* the specified URL pattern unchanged.
*
* @param urlPattern The URL pattern to be adjusted (if needed)
* and returned
*/
protected String adjustURLPattern(String urlPattern) {
if (urlPattern == null)
return (urlPattern);
if (urlPattern.startsWith("/") || urlPattern.startsWith("*."))
return (urlPattern);
if (!isServlet22())
return (urlPattern);
if(log.isDebugEnabled())
log.debug(sm.getString("standardContext.urlPattern.patternWarning",
urlPattern));
return ("/" + urlPattern);
}
/**
* Are we processing a version 2.2 deployment descriptor?
*/
@Override
public boolean isServlet22() {
return XmlIdentifiers.WEB_22_PUBLIC.equals(publicId);
}
@Override
public Set<String> addServletSecurity(
ServletRegistration.Dynamic registration,
ServletSecurityElement servletSecurityElement) {
Set<String> conflicts = new HashSet<>();
Collection<String> urlPatterns = registration.getMappings();
for (String urlPattern : urlPatterns) {
boolean foundConflict = false;
SecurityConstraint[] securityConstraints =
findConstraints();
for (SecurityConstraint securityConstraint : securityConstraints) {
SecurityCollection[] collections =
securityConstraint.findCollections();
for (SecurityCollection collection : collections) {
if (collection.findPattern(urlPattern)) {
// First pattern found will indicate if there is a
// conflict since for any given pattern all matching
// constraints will be from either the descriptor or
// not. It is not permitted to have a mixture
if (collection.isFromDescriptor()) {
// Skip this pattern
foundConflict = true;
conflicts.add(urlPattern);
break;
} else {
// Need to overwrite constraint for this pattern
collection.removePattern(urlPattern);
// If the collection is now empty, remove it
if (collection.findPatterns().length == 0) {
securityConstraint.removeCollection(collection);
}
}
}
}
// If the constraint now has no collections - remove it
if (securityConstraint.findCollections().length == 0) {
removeConstraint(securityConstraint);
}
// No need to check other constraints for the current pattern
// once a conflict has been found
if (foundConflict) {
break;
}
}
// Note: For progammatically added Servlets this may not be the
// complete set of security constraints since additional
// URL patterns can be added after the application has called
// setSecurity. For all programmatically added servilets, the
// #dynamicServletAdded() method sets a flag that ensures that
// the constraints are re-evaluated before the servlet is
// first used
// If the pattern did not conflict, add the new constraint(s).
if (!foundConflict) {
SecurityConstraint[] newSecurityConstraints =
SecurityConstraint.createConstraints(
servletSecurityElement,
urlPattern);
for (SecurityConstraint securityConstraint :
newSecurityConstraints) {
addConstraint(securityConstraint);
}
checkConstraintsForUncoveredMethods(newSecurityConstraints);
}
}
return conflicts;
}
/**
* Bind current thread, both for CL purposes and for JNDI ENC support
* during : startup, shutdown and realoading of the context.
*
* @return the previous context class loader
*/
protected ClassLoader bindThread() {
ClassLoader oldContextClassLoader =
Thread.currentThread().getContextClassLoader();
if (getLoader() != null && getLoader().getClassLoader() != null) {
Thread.currentThread().setContextClassLoader
(getLoader().getClassLoader());
}
if (isUseNaming()) {
try {
ContextBindings.bindThread(this, this);
} catch (NamingException e) {
// Silent catch, as this is a normal case during the early
// startup stages
}
}
return oldContextClassLoader;
}
/**
* Unbind thread.
*/
protected void unbindThread(ClassLoader oldContextClassLoader) {
if (isUseNaming()) {
ContextBindings.unbindThread(this, this);
}
Thread.currentThread().setContextClassLoader(oldContextClassLoader);
}
/**
* Get base path.
*/
protected String getBasePath() {
String docBase = null;
Container container = this;
while (container != null) {
if (container instanceof Host)
break;
container = container.getParent();
}
File file = new File(getDocBase());
if (!file.isAbsolute()) {
if (container == null) {
docBase = (new File(getCatalinaBase(), getDocBase())).getPath();
} else {
// Use the "appBase" property of this container
file = ((Host) container).getAppBaseFile();
docBase = (new File(file, getDocBase())).getPath();
}
} else {
docBase = file.getPath();
}
return docBase;
}
/**
* Get naming context full name.
*/
private String getNamingContextName() {
if (namingContextName == null) {
Container parent = getParent();
if (parent == null) {
namingContextName = getName();
} else {
Stack<String> stk = new Stack<>();
StringBuilder buff = new StringBuilder();
while (parent != null) {
stk.push(parent.getName());
parent = parent.getParent();
}
while (!stk.empty()) {
buff.append("/" + stk.pop());
}
buff.append(getName());
namingContextName = buff.toString();
}
}
return namingContextName;
}
/**
* Naming context listener accessor.
*/
public NamingContextListener getNamingContextListener() {
return namingContextListener;
}
/**
* Naming context listener setter.
*/
public void setNamingContextListener(NamingContextListener namingContextListener) {
this.namingContextListener = namingContextListener;
}
/**
* Return the request processing paused flag for this Context.
*/
@Override
public boolean getPaused() {
return (this.paused);
}
@Override
public boolean fireRequestInitEvent(ServletRequest request) {
Object instances[] = getApplicationEventListeners();
if ((instances != null) && (instances.length > 0)) {
ServletRequestEvent event =
new ServletRequestEvent(getServletContext(), request);
for (int i = 0; i < instances.length; i++) {
if (instances[i] == null)
continue;
if (!(instances[i] instanceof ServletRequestListener))
continue;
ServletRequestListener listener =
(ServletRequestListener) instances[i];
try {
listener.requestInitialized(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLogger().error(sm.getString(
"standardContext.requestListener.requestInit",
instances[i].getClass().getName()), t);
request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
return false;
}
}
}
return true;
}
@Override
public boolean fireRequestDestroyEvent(ServletRequest request) {
Object instances[] = getApplicationEventListeners();
if ((instances != null) && (instances.length > 0)) {
ServletRequestEvent event =
new ServletRequestEvent(getServletContext(), request);
for (int i = 0; i < instances.length; i++) {
int j = (instances.length -1) -i;
if (instances[j] == null)
continue;
if (!(instances[j] instanceof ServletRequestListener))
continue;
ServletRequestListener listener =
(ServletRequestListener) instances[j];
try {
listener.requestDestroyed(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLogger().error(sm.getString(
"standardContext.requestListener.requestInit",
instances[j].getClass().getName()), t);
request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
return false;
}
}
}
return true;
}
@Override
public void addPostConstructMethod(String clazz, String method) {
if (clazz == null || method == null)
throw new IllegalArgumentException(
sm.getString("standardContext.postconstruct.required"));
if (postConstructMethods.get(clazz) != null)
throw new IllegalArgumentException(sm.getString(
"standardContext.postconstruct.duplicate", clazz));
postConstructMethods.put(clazz, method);
fireContainerEvent("addPostConstructMethod", clazz);
}
@Override
public void removePostConstructMethod(String clazz) {
postConstructMethods.remove(clazz);
fireContainerEvent("removePostConstructMethod", clazz);
}
@Override
public void addPreDestroyMethod(String clazz, String method) {
if (clazz == null || method == null)
throw new IllegalArgumentException(
sm.getString("standardContext.predestroy.required"));
if (preDestroyMethods.get(clazz) != null)
throw new IllegalArgumentException(sm.getString(
"standardContext.predestroy.duplicate", clazz));
preDestroyMethods.put(clazz, method);
fireContainerEvent("addPreDestroyMethod", clazz);
}
@Override
public void removePreDestroyMethod(String clazz) {
preDestroyMethods.remove(clazz);
fireContainerEvent("removePreDestroyMethod", clazz);
}
@Override
public String findPostConstructMethod(String clazz) {
return postConstructMethods.get(clazz);
}
@Override
public String findPreDestroyMethod(String clazz) {
return preDestroyMethods.get(clazz);
}
@Override
public Map<String, String> findPostConstructMethods() {
return postConstructMethods;
}
@Override
public Map<String, String> findPreDestroyMethods() {
return preDestroyMethods;
}
/**
* Set the appropriate context attribute for our work directory.
*/
private void postWorkDirectory() {
// Acquire (or calculate) the work directory path
String workDir = getWorkDir();
if (workDir == null || workDir.length() == 0) {
// Retrieve our parent (normally a host) name
String hostName = null;
String engineName = null;
String hostWorkDir = null;
Container parentHost = getParent();
if (parentHost != null) {
hostName = parentHost.getName();
if (parentHost instanceof StandardHost) {
hostWorkDir = ((StandardHost)parentHost).getWorkDir();
}
Container parentEngine = parentHost.getParent();
if (parentEngine != null) {
engineName = parentEngine.getName();
}
}
if ((hostName == null) || (hostName.length() < 1))
hostName = "_";
if ((engineName == null) || (engineName.length() < 1))
engineName = "_";
String temp = getBaseName();
if (temp.startsWith("/"))
temp = temp.substring(1);
temp = temp.replace('/', '_');
temp = temp.replace('\\', '_');
if (temp.length() < 1)
temp = ContextName.ROOT_NAME;
if (hostWorkDir != null ) {
workDir = hostWorkDir + File.separator + temp;
} else {
workDir = "work" + File.separator + engineName +
File.separator + hostName + File.separator + temp;
}
setWorkDir(workDir);
}
// Create this directory if necessary
File dir = new File(workDir);
if (!dir.isAbsolute()) {
String catalinaHomePath = null;
try {
catalinaHomePath = getCatalinaBase().getCanonicalPath();
dir = new File(catalinaHomePath, workDir);
} catch (IOException e) {
log.warn(sm.getString("standardContext.workCreateException",
workDir, catalinaHomePath, getName()), e);
}
}
if (!dir.mkdirs() && !dir.isDirectory()) {
log.warn(sm.getString("standardContext.workCreateFail", dir,
getName()));
}
// Set the appropriate servlet context attribute
if (context == null) {
getServletContext();
}
context.setAttribute(ServletContext.TEMPDIR, dir);
context.setAttributeReadOnly(ServletContext.TEMPDIR);
}
/**
* Set the request processing paused flag for this Context.
*
* @param paused The new request processing paused flag
*/
private void setPaused(boolean paused) {
this.paused = paused;
}
/**
* Validate the syntax of a proposed <code><url-pattern></code>
* for conformance with specification requirements.
*
* @param urlPattern URL pattern to be validated
*/
private boolean validateURLPattern(String urlPattern) {
if (urlPattern == null)
return (false);
if (urlPattern.indexOf('\n') >= 0 || urlPattern.indexOf('\r') >= 0) {
return (false);
}
if (urlPattern.equals("")) {
return true;
}
if (urlPattern.startsWith("*.")) {
if (urlPattern.indexOf('/') < 0) {
checkUnusualURLPattern(urlPattern);
return (true);
} else
return (false);
}
if ( (urlPattern.startsWith("/")) &&
(urlPattern.indexOf("*.") < 0)) {
checkUnusualURLPattern(urlPattern);
return (true);
} else
return (false);
}
/**
* Check for unusual but valid <code><url-pattern></code>s.
* See Bugzilla 34805, 43079 & 43080
*/
private void checkUnusualURLPattern(String urlPattern) {
if (log.isInfoEnabled()) {
if(urlPattern.endsWith("*") && (urlPattern.length() < 2 ||
urlPattern.charAt(urlPattern.length()-2) != '/')) {
log.info("Suspicious url pattern: \"" + urlPattern + "\"" +
" in context [" + getName() + "] - see" +
" section SRV.11.2 of the Servlet specification" );
}
}
}
// ------------------------------------------------------------- Operations
/**
* JSR77 deploymentDescriptor attribute
*
* @return string deployment descriptor
*/
public String getDeploymentDescriptor() {
InputStream stream = null;
ServletContext servletContext = getServletContext();
if (servletContext != null) {
stream = servletContext.getResourceAsStream(
org.apache.catalina.startup.Constants.ApplicationWebXml);
}
if (stream == null) {
return "";
}
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(stream));
String strRead = "";
while (strRead != null) {
sb.append(strRead);
strRead = br.readLine();
}
} catch (IOException e) {
return "";
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ioe) {/*Ignore*/}
}
}
return sb.toString();
}
/**
* JSR77 servlets attribute
*
* @return list of all servlets ( we know about )
*/
public String[] getServlets() {
String[] result = null;
Container[] children = findChildren();
if (children != null) {
result = new String[children.length];
for( int i=0; i< children.length; i++ ) {
result[i] = children[i].getObjectName().toString();
}
}
return result;
}
@Override
protected String getObjectNameKeyProperties() {
StringBuilder keyProperties =
new StringBuilder("j2eeType=WebModule,");
keyProperties.append(getObjectKeyPropertiesNameOnly());
keyProperties.append(",J2EEApplication=");
keyProperties.append(getJ2EEApplication());
keyProperties.append(",J2EEServer=");
keyProperties.append(getJ2EEServer());
return keyProperties.toString();
}
private String getObjectKeyPropertiesNameOnly() {
StringBuilder result = new StringBuilder("name=//");
String hostname = getParent().getName();
if (hostname == null) {
result.append("DEFAULT");
} else {
result.append(hostname);
}
String contextName = getName();
if (!contextName.startsWith("/")) {
result.append('/');
}
result.append(contextName);
return result.toString();
}
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
if (processTlds) {
this.addLifecycleListener(new TldConfig());
}
// Register the naming resources
if (namingResources != null) {
namingResources.init();
}
if (resources != null) {
resources.start();
}
// Send j2ee.object.created notification
if (this.getObjectName() != null) {
Notification notification = new Notification("j2ee.object.created",
this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
}
/* Remove a JMX notficationListener
* @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void removeNotificationListener(NotificationListener listener,
NotificationFilter filter, Object object) throws ListenerNotFoundException {
broadcaster.removeNotificationListener(listener,filter,object);
}
private MBeanNotificationInfo[] notificationInfo;
/* Get JMX Broadcaster Info
* @TODO use StringManager for international support!
* @TODO This two events we not send j2ee.state.failed and j2ee.attribute.changed!
* @see javax.management.NotificationBroadcaster#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
// FIXME: i18n
if(notificationInfo == null) {
notificationInfo = new MBeanNotificationInfo[]{
new MBeanNotificationInfo(new String[] {
"j2ee.object.created"},
Notification.class.getName(),
"web application is created"
),
new MBeanNotificationInfo(new String[] {
"j2ee.state.starting"},
Notification.class.getName(),
"change web application is starting"
),
new MBeanNotificationInfo(new String[] {
"j2ee.state.running"},
Notification.class.getName(),
"web application is running"
),
new MBeanNotificationInfo(new String[] {
"j2ee.state.stopping"},
Notification.class.getName(),
"web application start to stopped"
),
new MBeanNotificationInfo(new String[] {
"j2ee.object.stopped"},
Notification.class.getName(),
"web application is stopped"
),
new MBeanNotificationInfo(new String[] {
"j2ee.object.deleted"},
Notification.class.getName(),
"web application is deleted"
)
};
}
return notificationInfo;
}
/* Add a JMX-NotificationListener
* @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void addNotificationListener(NotificationListener listener,
NotificationFilter filter, Object object) throws IllegalArgumentException {
broadcaster.addNotificationListener(listener,filter,object);
}
/**
* Remove a JMX-NotificationListener
* @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
*/
@Override
public void removeNotificationListener(NotificationListener listener)
throws ListenerNotFoundException {
broadcaster.removeNotificationListener(listener);
}
// ------------------------------------------------------------- Attributes
/**
* Return the naming resources associated with this web application.
*/
public String[] getWelcomeFiles() {
return findWelcomeFiles();
}
/**
* Set the validation feature of the XML parser used when
* parsing xml instances.
* @param webXmlValidation true to enable xml instance validation
*/
@Override
public void setXmlValidation(boolean webXmlValidation){
this.webXmlValidation = webXmlValidation;
}
/**
* Get the server.xml <context> attribute's xmlValidation.
* @return true if validation is enabled.
*
*/
@Override
public boolean getXmlValidation(){
return webXmlValidation;
}
/**
* Get the server.xml <context> attribute's xmlNamespaceAware.
* @return true if namespace awarenes is enabled.
*/
@Override
public boolean getXmlNamespaceAware(){
return webXmlNamespaceAware;
}
/**
* Set the namespace aware feature of the XML parser used when
* parsing xml instances.
* @param webXmlNamespaceAware true to enable namespace awareness
*/
@Override
public void setXmlNamespaceAware(boolean webXmlNamespaceAware){
this.webXmlNamespaceAware= webXmlNamespaceAware;
}
/**
* Set the validation feature of the XML parser used when
* parsing tlds files.
* @param tldValidation true to enable xml instance validation
*/
@Override
public void setTldValidation(boolean tldValidation){
this.tldValidation = tldValidation;
}
/**
* Get the server.xml <context> attribute's webXmlValidation.
* @return true if validation is enabled.
*
*/
@Override
public boolean getTldValidation(){
return tldValidation;
}
/**
* Sets the process TLDs attribute.
*
* @param newProcessTlds The new value
*/
public void setProcessTlds(boolean newProcessTlds) {
processTlds = newProcessTlds;
}
/**
* Returns the processTlds attribute value.
*/
public boolean getProcessTlds() {
return processTlds;
}
/**
* Get the server.xml <host> attribute's xmlNamespaceAware.
* @return true if namespace awarenes is enabled.
*/
@Override
public boolean getTldNamespaceAware(){
return tldNamespaceAware;
}
/**
* Set the namespace aware feature of the XML parser used when
* parsing xml instances.
* @param tldNamespaceAware true to enable namespace awareness
*/
@Override
public void setTldNamespaceAware(boolean tldNamespaceAware){
this.tldNamespaceAware= tldNamespaceAware;
}
/**
* Support for "stateManageable" JSR77
*/
public boolean isStateManageable() {
return true;
}
/**
* The J2EE Server ObjectName this module is deployed on.
*/
private String server = null;
/**
* The Java virtual machines on which this module is running.
*/
private String[] javaVMs = null;
public String getServer() {
return server;
}
public String setServer(String server) {
return this.server=server;
}
public String[] getJavaVMs() {
return javaVMs;
}
public String[] setJavaVMs(String[] javaVMs) {
return this.javaVMs = javaVMs;
}
/**
* Gets the time this context was started.
*
* @return Time (in milliseconds since January 1, 1970, 00:00:00) when this
* context was started
*/
public long getStartTime() {
return startTime;
}
private static class NoPluggabilityServletContext
implements ServletContext {
private final ServletContext sc;
public NoPluggabilityServletContext(ServletContext sc) {
this.sc = sc;
}
@Override
public String getContextPath() {
return sc.getContextPath();
}
@Override
public ServletContext getContext(String uripath) {
return sc.getContext(uripath);
}
@Override
public int getMajorVersion() {
return sc.getMajorVersion();
}
@Override
public int getMinorVersion() {
return sc.getMinorVersion();
}
@Override
public int getEffectiveMajorVersion() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public int getEffectiveMinorVersion() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public String getMimeType(String file) {
return sc.getMimeType(file);
}
@Override
public Set<String> getResourcePaths(String path) {
return sc.getResourcePaths(path);
}
@Override
public URL getResource(String path) throws MalformedURLException {
return sc.getResource(path);
}
@Override
public InputStream getResourceAsStream(String path) {
return sc.getResourceAsStream(path);
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return sc.getRequestDispatcher(path);
}
@Override
public RequestDispatcher getNamedDispatcher(String name) {
return sc.getNamedDispatcher(name);
}
@Override
@Deprecated
public Servlet getServlet(String name) throws ServletException {
return sc.getServlet(name);
}
@Override
@Deprecated
public Enumeration<Servlet> getServlets() {
return sc.getServlets();
}
@Override
@Deprecated
public Enumeration<String> getServletNames() {
return sc.getServletNames();
}
@Override
public void log(String msg) {
sc.log(msg);
}
@Override
@Deprecated
public void log(Exception exception, String msg) {
sc.log(exception, msg);
}
@Override
public void log(String message, Throwable throwable) {
sc.log(message, throwable);
}
@Override
public String getRealPath(String path) {
return sc.getRealPath(path);
}
@Override
public String getServerInfo() {
return sc.getServerInfo();
}
@Override
public String getInitParameter(String name) {
return sc.getInitParameter(name);
}
@Override
public Enumeration<String> getInitParameterNames() {
return sc.getInitParameterNames();
}
@Override
public boolean setInitParameter(String name, String value) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Object getAttribute(String name) {
return sc.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return sc.getAttributeNames();
}
@Override
public void setAttribute(String name, Object object) {
sc.setAttribute(name, object);
}
@Override
public void removeAttribute(String name) {
sc.removeAttribute(name);
}
@Override
public String getServletContextName() {
return sc.getServletContextName();
}
@Override
public Dynamic addServlet(String servletName, String className) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Dynamic addServlet(String servletName, Servlet servlet) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Dynamic addServlet(String servletName,
Class<? extends Servlet> servletClass) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public <T extends Servlet> T createServlet(Class<T> c)
throws ServletException {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public ServletRegistration getServletRegistration(String servletName) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Map<String,? extends ServletRegistration> getServletRegistrations() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public javax.servlet.FilterRegistration.Dynamic addFilter(
String filterName, String className) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public javax.servlet.FilterRegistration.Dynamic addFilter(
String filterName, Filter filter) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public javax.servlet.FilterRegistration.Dynamic addFilter(
String filterName, Class<? extends Filter> filterClass) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public <T extends Filter> T createFilter(Class<T> c)
throws ServletException {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public FilterRegistration getFilterRegistration(String filterName) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Map<String,? extends FilterRegistration> getFilterRegistrations() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public void setSessionTrackingModes(
Set<SessionTrackingMode> sessionTrackingModes) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public void addListener(String className) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public <T extends EventListener> void addListener(T t) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public void addListener(Class<? extends EventListener> listenerClass) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public <T extends EventListener> T createListener(Class<T> c)
throws ServletException {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public ClassLoader getClassLoader() {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public void declareRoles(String... roleNames) {
throw new UnsupportedOperationException(
sm.getString("noPluggabilityServletContext.notAllowed"));
}
@Override
public String getVirtualServerName() {
return sc.getVirtualServerName();
}
}
}
|
52,092
|
Bug 52092 Please make AsyncFileHandler and OneLineFormatter the default for logging.properties
|
Apache Tomcat 7 has created some very important enhancements to logging, and we should exploit them. Please make the org.apache.juli.AsyncFileHandler and org.apache.juli.OneLineFormatter the defaults for shipped conf/logging.properties. These enhancements have been vetted with over 20 releases of Apache Tomcat, let's give them some first class status.
|
resolved fixed
|
7d0408e
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-07T21:14:55Z
| 2011-10-26T14:40:00Z
|
java/org/apache/juli/FileHandler.java
|
/*
* 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.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
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.
*
* <p>The following configuration properties are available:</p>
*
* <ul>
* <li><code>directory</code> - The directory where to create the log file.
* If the path is not absolute, it is relative to the current working
* directory of the application. The Apache Tomcat configuration files usually
* specify an absolute path for this property,
* <code>${catalina.base}/logs</code>
* Default value: <code>logs</code></li>
* <li><code>rotatable</code> - If <code>true</code>, the log file will be
* rotated on the first write past midnight and the filename will be
* <code>{prefix}{date}{suffix}</code>, where date is yyyy-MM-dd. If <code>false</code>,
* the file will not be rotated and the filename will be <code>{prefix}{suffix}</code>.
* Default value: <code>true</code></li>
* <li><code>prefix</code> - The leading part of the log file name.
* Default value: <code>juli.</code></li>
* <li><code>suffix</code> - The trailing part of the log file name. Default value: <code>.log</code></li>
* <li><code>bufferSize</code> - Configures buffering. The value of <code>0</code>
* uses system default buffering (typically an 8K buffer will be used). A
* value of <code><0</code> forces a writer flush upon each log write. A
* value <code>>0</code> uses a BufferedOutputStream with the defined
* value but note that the system default buffering will also be
* applied. Default value: <code>-1</code></li>
* <li><code>encoding</code> - Character set used by the log file. Default value:
* empty string, which means to use the system default character set.</li>
* <li><code>level</code> - The level threshold for this Handler. See the
* <code>java.util.logging.Level</code> class for the possible levels.
* Default value: <code>ALL</code></li>
* <li><code>filter</code> - The <code>java.util.logging.Filter</code>
* implementation class name for this Handler. Default value: unset</li>
* <li><code>formatter</code> - The <code>java.util.logging.Formatter</code>
* implementation class name for this Handler. Default value:
* <code>java.util.logging.SimpleFormatter</code></li>
* </ul>
*
* @version $Id$
*/
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();
openWriter();
}
// ----------------------------------------------------- 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 volatile 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;
/**
* Determines whether the logfile is rotatable
*/
private boolean rotatable = true;
/**
* The PrintWriter to which we are currently logging, if any.
*/
private volatile PrintWriter writer = null;
/**
* Lock used to control access to the writer.
*/
protected final ReadWriteLock writerLock = new ReentrantReadWriteLock();
/**
* Log buffer size.
*/
private int bufferSize = -1;
// --------------------------------------------------------- Public Methods
/**
* Format and publish a <tt>LogRecord</tt>.
*
* @param record description of the log event
*/
@Override
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);
try {
writerLock.readLock().lock();
// If the date has changed, switch log files
if (rotatable && !date.equals(tsDate)) {
try {
// Update to writeLock before we switch
writerLock.readLock().unlock();
writerLock.writeLock().lock();
// Make sure another thread hasn't already done this
if (!date.equals(tsDate)) {
closeWriter();
date = tsDate;
openWriter();
}
} finally {
writerLock.writeLock().unlock();
// Down grade to read-lock. This ensures the writer remains valid
// until the log message is written
writerLock.readLock().lock();
}
}
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);
if (bufferSize < 0) {
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;
}
} finally {
writerLock.readLock().unlock();
}
}
// -------------------------------------------------------- Private Methods
/**
* Close the currently open log file (if any).
*/
@Override
public void close() {
closeWriter();
}
protected void closeWriter() {
writerLock.writeLock().lock();
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);
} finally {
writerLock.writeLock().unlock();
}
}
/**
* Flush the writer.
*/
@Override
public void flush() {
writerLock.readLock().lock();
try {
if (writer == null)
return;
writer.flush();
} catch (Exception e) {
reportError(null, e, ErrorManager.FLUSH_FAILURE);
} finally {
writerLock.readLock().unlock();
}
}
/**
* 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 = this.getClass().getName(); //allow classes to override
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// Retrieve configuration of logging file name
rotatable = Boolean.parseBoolean(getProperty(className + ".rotatable", "true"));
if (directory == null)
directory = getProperty(className + ".directory", "logs");
if (prefix == null)
prefix = getProperty(className + ".prefix", "juli.");
if (suffix == null)
suffix = getProperty(className + ".suffix", ".log");
String sBufferSize = getProperty(className + ".bufferSize", String.valueOf(bufferSize));
try {
bufferSize = Integer.parseInt(sBufferSize);
} catch (NumberFormatException ignore) {
//no op
}
// Get encoding for the logging file
String encoding = getProperty(className + ".encoding", null);
if (encoding != null && encoding.length() > 0) {
try {
setEncoding(encoding);
} catch (UnsupportedEncodingException ex) {
// Ignore
}
}
// 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 and fallback to defaults
setFormatter(new SimpleFormatter());
}
} 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>.
*/
protected void open() {
openWriter();
}
protected void openWriter() {
// Create the directory if necessary
File dir = new File(directory);
if (!dir.mkdirs() && !dir.isDirectory()) {
reportError("Unable to create [" + dir + "]", null,
ErrorManager.OPEN_FAILURE);
writer = null;
return;
}
// Open the current log file
writerLock.writeLock().lock();
FileOutputStream fos = null;
OutputStream os = null;
try {
File pathname = new File(dir.getAbsoluteFile(), prefix
+ (rotatable ? date : "") + suffix);
File parent = pathname.getParentFile();
if (!parent.mkdirs() && !parent.isDirectory()) {
reportError("Unable to create [" + parent + "]", null,
ErrorManager.OPEN_FAILURE);
writer = null;
return;
}
String encoding = getEncoding();
fos = new FileOutputStream(pathname, true);
os = bufferSize>0?new BufferedOutputStream(fos,bufferSize):fos;
writer = new PrintWriter(
(encoding != null) ? new OutputStreamWriter(os, encoding)
: new OutputStreamWriter(os), false);
writer.write(getFormatter().getHead(this));
} catch (Exception e) {
reportError(null, e, ErrorManager.OPEN_FAILURE);
writer = null;
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
// Ignore
}
}
if (os != null) {
try {
os.close();
} catch (IOException e1) {
// Ignore
}
}
} finally {
writerLock.writeLock().unlock();
}
}
}
|
55,404
|
Bug 55404 ContextConfig#validateSecurityRoles emits three info log messages which contain a warning
| null |
resolved fixed
|
df02b95
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-12T14:27:33Z
| 2013-08-12T17:53:20Z
|
java/org/apache/catalina/startup/ContextConfig.java
|
/*
* 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.startup;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.SessionCookieConfig;
import javax.servlet.annotation.HandlesTypes;
import org.apache.catalina.Authenticator;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Pipeline;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.Valve;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.util.ContextName;
import org.apache.catalina.util.Introspection;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.JarScanType;
import org.apache.tomcat.JarScanner;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.bcel.classfile.AnnotationElementValue;
import org.apache.tomcat.util.bcel.classfile.AnnotationEntry;
import org.apache.tomcat.util.bcel.classfile.ArrayElementValue;
import org.apache.tomcat.util.bcel.classfile.ClassFormatException;
import org.apache.tomcat.util.bcel.classfile.ClassParser;
import org.apache.tomcat.util.bcel.classfile.ElementValue;
import org.apache.tomcat.util.bcel.classfile.ElementValuePair;
import org.apache.tomcat.util.bcel.classfile.JavaClass;
import org.apache.tomcat.util.descriptor.XmlErrorHandler;
import org.apache.tomcat.util.descriptor.web.ApplicationListener;
import org.apache.tomcat.util.descriptor.web.ContextEjb;
import org.apache.tomcat.util.descriptor.web.ContextEnvironment;
import org.apache.tomcat.util.descriptor.web.ContextLocalEjb;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef;
import org.apache.tomcat.util.descriptor.web.ContextService;
import org.apache.tomcat.util.descriptor.web.ErrorPage;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.apache.tomcat.util.descriptor.web.FragmentJarScannerCallback;
import org.apache.tomcat.util.descriptor.web.JspPropertyGroup;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
import org.apache.tomcat.util.descriptor.web.MessageDestinationRef;
import org.apache.tomcat.util.descriptor.web.MultipartDef;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.util.descriptor.web.SecurityRoleRef;
import org.apache.tomcat.util.descriptor.web.ServletDef;
import org.apache.tomcat.util.descriptor.web.SessionConfig;
import org.apache.tomcat.util.descriptor.web.WebXml;
import org.apache.tomcat.util.descriptor.web.WebXmlParser;
import org.apache.tomcat.util.digester.Digester;
import org.apache.tomcat.util.digester.RuleSet;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.scan.Jar;
import org.apache.tomcat.util.scan.JarFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
/**
* Startup event listener for a <b>Context</b> that configures the properties
* of that Context, and the associated defined servlets.
*
* @author Craig R. McClanahan
* @author Jean-Francois Arcand
* @version $Id$
*/
public class ContextConfig implements LifecycleListener {
private static final Log log = LogFactory.getLog( ContextConfig.class );
/**
* The string resources for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
protected static final LoginConfig DUMMY_LOGIN_CONFIG =
new LoginConfig("NONE", null, null, null);
/**
* The set of Authenticators that we know how to configure. The key is
* the name of the implemented authentication method, and the value is
* the fully qualified Java class name of the corresponding Valve.
*/
protected static final Properties authenticators;
static {
// Load our mapping properties for the standard authenticators
InputStream is =
ContextConfig.class.getClassLoader().getResourceAsStream(
"org/apache/catalina/startup/Authenticators.properties");
Properties props = null;
props = new Properties();
if (is != null) {
try {
props.load(is);
} catch (IOException e) {
props = null;
}
}
authenticators = props;
}
/**
* Deployment count.
*/
protected static long deploymentCount = 0L;
/**
* Cache of default web.xml fragments per Host
*/
protected static final Map<Host,DefaultWebXmlCacheEntry> hostWebXmlCache =
new ConcurrentHashMap<>();
// ----------------------------------------------------- Instance Variables
/**
* Custom mappings of login methods to authenticators
*/
protected Map<String,Authenticator> customAuthenticators;
/**
* The Context we are associated with.
*/
protected Context context = null;
/**
* The default web application's deployment descriptor location.
*/
protected String defaultWebXml = null;
/**
* Track any fatal errors during startup configuration processing.
*/
protected boolean ok = false;
/**
* Original docBase.
*/
protected String originalDocBase = null;
/**
* Anti-locking docBase. It is a path to a copy of the web application
* in the java.io.tmpdir directory. This path is always an absolute one.
*/
private File antiLockingDocBase = null;
/**
* Map of ServletContainerInitializer to classes they expressed interest in.
*/
protected final Map<ServletContainerInitializer, Set<Class<?>>> initializerClassMap =
new LinkedHashMap<>();
/**
* Map of Types to ServletContainerInitializer that are interested in those
* types.
*/
protected final Map<Class<?>, Set<ServletContainerInitializer>> typeInitializerMap =
new HashMap<>();
/**
* Cache of JavaClass objects (byte code) by fully qualified class name.
* Only populated if it is necessary to scan the super types and interfaces
* as part of the processing for {@link HandlesTypes}.
*/
protected final Map<String,JavaClassCacheEntry> javaClassCache =
new HashMap<>();
/**
* Flag that indicates if at least one {@link HandlesTypes} entry is present
* that represents an annotation.
*/
protected boolean handlesTypesAnnotations = false;
/**
* Flag that indicates if at least one {@link HandlesTypes} entry is present
* that represents a non-annotation.
*/
protected boolean handlesTypesNonAnnotations = false;
private WebXmlParser webXmlParser;
// ------------------------------------------------------------- Properties
/**
* Return the location of the default deployment descriptor
*/
public String getDefaultWebXml() {
if( defaultWebXml == null ) {
defaultWebXml=Constants.DefaultWebXml;
}
return (this.defaultWebXml);
}
/**
* Set the location of the default deployment descriptor
*
* @param path Absolute/relative path to the default web.xml
*/
public void setDefaultWebXml(String path) {
this.defaultWebXml = path;
}
/**
* Sets custom mappings of login methods to authenticators.
*
* @param customAuthenticators Custom mappings of login methods to
* authenticators
*/
public void setCustomAuthenticators(
Map<String,Authenticator> customAuthenticators) {
this.customAuthenticators = customAuthenticators;
}
// --------------------------------------------------------- Public Methods
/**
* Process events for an associated Context.
*
* @param event The lifecycle event that has occurred
*/
@Override
public void lifecycleEvent(LifecycleEvent event) {
// Identify the context we are associated with
try {
context = (Context) event.getLifecycle();
} catch (ClassCastException e) {
log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e);
return;
}
// Process the event that has occurred
if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
configureStart();
} else if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) {
beforeStart();
} else if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) {
// Restore docBase for management tools
if (originalDocBase != null) {
context.setDocBase(originalDocBase);
}
} else if (event.getType().equals(Lifecycle.CONFIGURE_STOP_EVENT)) {
configureStop();
} else if (event.getType().equals(Lifecycle.AFTER_INIT_EVENT)) {
init();
} else if (event.getType().equals(Lifecycle.AFTER_DESTROY_EVENT)) {
destroy();
}
}
// -------------------------------------------------------- protected Methods
/**
* Process the application classes annotations, if it exists.
*/
protected void applicationAnnotationsConfig() {
long t1=System.currentTimeMillis();
WebAnnotationSet.loadApplicationAnnotations(context);
long t2=System.currentTimeMillis();
if (context instanceof StandardContext) {
((StandardContext) context).setStartupTime(t2-t1+
((StandardContext) context).getStartupTime());
}
}
/**
* Set up an Authenticator automatically if required, and one has not
* already been configured.
*/
protected void authenticatorConfig() {
LoginConfig loginConfig = context.getLoginConfig();
SecurityConstraint constraints[] = context.findConstraints();
if (context.getIgnoreAnnotations() &&
(constraints == null || constraints.length ==0) &&
!context.getPreemptiveAuthentication()) {
return;
} else {
if (loginConfig == null) {
// Not metadata-complete or security constraints present, need
// an authenticator to support @ServletSecurity annotations
// and/or constraints
loginConfig = DUMMY_LOGIN_CONFIG;
context.setLoginConfig(loginConfig);
}
}
// Has an authenticator been configured already?
if (context.getAuthenticator() != null) {
return;
}
// Has a Realm been configured for us to authenticate against?
if (context.getRealm() == null) {
log.error(sm.getString("contextConfig.missingRealm"));
ok = false;
return;
}
/*
* First check to see if there is a custom mapping for the login
* method. If so, use it. Otherwise, check if there is a mapping in
* org/apache/catalina/startup/Authenticators.properties.
*/
Valve authenticator = null;
if (customAuthenticators != null) {
authenticator = (Valve)
customAuthenticators.get(loginConfig.getAuthMethod());
}
if (authenticator == null) {
if (authenticators == null) {
log.error(sm.getString("contextConfig.authenticatorResources"));
ok = false;
return;
}
// Identify the class name of the Valve we should configure
String authenticatorName = null;
authenticatorName =
authenticators.getProperty(loginConfig.getAuthMethod());
if (authenticatorName == null) {
log.error(sm.getString("contextConfig.authenticatorMissing",
loginConfig.getAuthMethod()));
ok = false;
return;
}
// Instantiate and install an Authenticator of the requested class
try {
Class<?> authenticatorClass = Class.forName(authenticatorName);
authenticator = (Valve) authenticatorClass.newInstance();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString(
"contextConfig.authenticatorInstantiate",
authenticatorName),
t);
ok = false;
}
}
if (authenticator != null) {
Pipeline pipeline = context.getPipeline();
if (pipeline != null) {
pipeline.addValve(authenticator);
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"contextConfig.authenticatorConfigured",
loginConfig.getAuthMethod()));
}
}
}
}
/**
* Create (if necessary) and return a Digester configured to process the
* context configuration descriptor for an application.
*/
protected Digester createContextDigester() {
Digester digester = new Digester();
digester.setValidating(false);
digester.setRulesValidation(true);
HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>();
ArrayList<String> attrs = new ArrayList<>();
attrs.add("className");
fakeAttributes.put(Object.class, attrs);
digester.setFakeAttributes(fakeAttributes);
RuleSet contextRuleSet = new ContextRuleSet("", false);
digester.addRuleSet(contextRuleSet);
RuleSet namingRuleSet = new NamingRuleSet("Context/");
digester.addRuleSet(namingRuleSet);
return digester;
}
/**
* Process the default configuration file, if it exists.
*/
protected void contextConfig(Digester digester) {
String defaultContextXml = null;
// Open the default context.xml file, if it exists
if (context instanceof StandardContext) {
defaultContextXml = ((StandardContext)context).getDefaultContextXml();
}
// set the default if we don't have any overrides
if (defaultContextXml == null) {
defaultContextXml = Constants.DefaultContextXml;
}
if (!context.getOverride()) {
File defaultContextFile = new File(defaultContextXml);
if (!defaultContextFile.isAbsolute()) {
defaultContextFile =
new File(context.getCatalinaBase(), defaultContextXml);
}
if (defaultContextFile.exists()) {
try {
URL defaultContextUrl = defaultContextFile.toURI().toURL();
processContextConfig(digester, defaultContextUrl);
} catch (MalformedURLException e) {
log.error(sm.getString(
"contextConfig.badUrl", defaultContextFile), e);
}
}
File hostContextFile = new File(getHostConfigBase(), Constants.HostContextXml);
if (hostContextFile.exists()) {
try {
URL hostContextUrl = hostContextFile.toURI().toURL();
processContextConfig(digester, hostContextUrl);
} catch (MalformedURLException e) {
log.error(sm.getString(
"contextConfig.badUrl", hostContextFile), e);
}
}
}
if (context.getConfigFile() != null) {
processContextConfig(digester, context.getConfigFile());
}
}
/**
* Process a context.xml.
*/
protected void processContextConfig(Digester digester, URL contextXml) {
if (log.isDebugEnabled()) {
log.debug("Processing context [" + context.getName()
+ "] configuration file [" + contextXml + "]");
}
InputSource source = null;
InputStream stream = null;
try {
source = new InputSource(contextXml.toString());
URLConnection xmlConn = contextXml.openConnection();
xmlConn.setUseCaches(false);
stream = xmlConn.getInputStream();
} catch (Exception e) {
log.error(sm.getString("contextConfig.contextMissing",
contextXml) , e);
}
if (source == null) {
return;
}
try {
source.setByteStream(stream);
digester.setClassLoader(this.getClass().getClassLoader());
digester.setUseContextClassLoader(false);
digester.push(context.getParent());
digester.push(context);
XmlErrorHandler errorHandler = new XmlErrorHandler();
digester.setErrorHandler(errorHandler);
digester.parse(source);
if (errorHandler.getWarnings().size() > 0 ||
errorHandler.getErrors().size() > 0) {
errorHandler.logFindings(log, contextXml.toString());
ok = false;
}
if (log.isDebugEnabled()) {
log.debug("Successfully processed context [" + context.getName()
+ "] configuration file [" + contextXml + "]");
}
} catch (SAXParseException e) {
log.error(sm.getString("contextConfig.contextParse",
context.getName()), e);
log.error(sm.getString("contextConfig.defaultPosition",
"" + e.getLineNumber(),
"" + e.getColumnNumber()));
ok = false;
} catch (Exception e) {
log.error(sm.getString("contextConfig.contextParse",
context.getName()), e);
ok = false;
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
log.error(sm.getString("contextConfig.contextClose"), e);
}
}
}
/**
* Adjust docBase.
*/
protected void fixDocBase()
throws IOException {
Host host = (Host) context.getParent();
File appBase = host.getAppBaseFile();
String docBase = context.getDocBase();
if (docBase == null) {
// Trying to guess the docBase according to the path
String path = context.getPath();
if (path == null) {
return;
}
ContextName cn = new ContextName(path, context.getWebappVersion());
docBase = cn.getBaseName();
}
File file = new File(docBase);
if (!file.isAbsolute()) {
docBase = (new File(appBase, docBase)).getPath();
} else {
docBase = file.getCanonicalPath();
}
file = new File(docBase);
String origDocBase = docBase;
ContextName cn = new ContextName(context.getPath(),
context.getWebappVersion());
String pathName = cn.getBaseName();
boolean unpackWARs = true;
if (host instanceof StandardHost &&
context instanceof StandardContext) {
unpackWARs = ((StandardHost) host).isUnpackWARs() &&
((StandardContext) context).getUnpackWAR();
}
if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && unpackWARs) {
URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/");
docBase = ExpandWar.expand(host, war, pathName);
file = new File(docBase);
docBase = file.getCanonicalPath();
if (context instanceof StandardContext) {
((StandardContext) context).setOriginalDocBase(origDocBase);
}
} else if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") &&
!file.isDirectory() && !unpackWARs) {
URL war =
new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/");
ExpandWar.validate(host, war, pathName);
} else {
File docDir = new File(docBase);
if (!docDir.exists()) {
File warFile = new File(docBase + ".war");
if (warFile.exists()) {
URL war =
new URL("jar:" + warFile.toURI().toURL() + "!/");
if (unpackWARs) {
docBase = ExpandWar.expand(host, war, pathName);
file = new File(docBase);
docBase = file.getCanonicalPath();
} else {
docBase = warFile.getCanonicalPath();
ExpandWar.validate(host, war, pathName);
}
}
if (context instanceof StandardContext) {
((StandardContext) context).setOriginalDocBase(origDocBase);
}
}
}
if (docBase.startsWith(appBase.getPath() + File.separatorChar)) {
docBase = docBase.substring(appBase.getPath().length());
docBase = docBase.replace(File.separatorChar, '/');
if (docBase.startsWith("/")) {
docBase = docBase.substring(1);
}
} else {
docBase = docBase.replace(File.separatorChar, '/');
}
context.setDocBase(docBase);
}
protected void antiLocking() {
if ((context instanceof StandardContext)
&& ((StandardContext) context).getAntiResourceLocking()) {
Host host = (Host) context.getParent();
String docBase = context.getDocBase();
if (docBase == null) {
return;
}
originalDocBase = docBase;
File docBaseFile = new File(docBase);
if (!docBaseFile.isAbsolute()) {
docBaseFile = new File(host.getAppBaseFile(), docBase);
}
String path = context.getPath();
if (path == null) {
return;
}
ContextName cn = new ContextName(path, context.getWebappVersion());
docBase = cn.getBaseName();
if (originalDocBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
antiLockingDocBase = new File(
System.getProperty("java.io.tmpdir"),
deploymentCount++ + "-" + docBase + ".war");
} else {
antiLockingDocBase = new File(
System.getProperty("java.io.tmpdir"),
deploymentCount++ + "-" + docBase);
}
antiLockingDocBase = antiLockingDocBase.getAbsoluteFile();
if (log.isDebugEnabled()) {
log.debug("Anti locking context[" + context.getName()
+ "] setting docBase to " +
antiLockingDocBase.getPath());
}
// Cleanup just in case an old deployment is lying around
ExpandWar.delete(antiLockingDocBase);
if (ExpandWar.copy(docBaseFile, antiLockingDocBase)) {
context.setDocBase(antiLockingDocBase.getPath());
}
}
}
/**
* Process a "init" event for this Context.
*/
protected void init() {
// Called from StandardContext.init()
Digester contextDigester = createContextDigester();
contextDigester.getParser();
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.init"));
}
context.setConfigured(false);
ok = true;
contextConfig(contextDigester);
webXmlParser = new WebXmlParser(context.getXmlNamespaceAware(),
context.getXmlValidation());
}
/**
* Process a "before start" event for this Context.
*/
protected synchronized void beforeStart() {
try {
fixDocBase();
} catch (IOException e) {
log.error(sm.getString(
"contextConfig.fixDocBase", context.getName()), e);
}
antiLocking();
}
/**
* Process a "contextConfig" event for this Context.
*/
protected synchronized void configureStart() {
// Called from StandardContext.start()
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.start"));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.xmlSettings",
context.getName(),
Boolean.valueOf(context.getXmlValidation()),
Boolean.valueOf(context.getXmlNamespaceAware())));
}
webConfig();
if (!context.getIgnoreAnnotations()) {
applicationAnnotationsConfig();
}
if (ok) {
validateSecurityRoles();
}
// Configure an authenticator if we need one
if (ok) {
authenticatorConfig();
}
// Dump the contents of this pipeline if requested
if (log.isDebugEnabled()) {
log.debug("Pipeline Configuration:");
Pipeline pipeline = context.getPipeline();
Valve valves[] = null;
if (pipeline != null) {
valves = pipeline.getValves();
}
if (valves != null) {
for (int i = 0; i < valves.length; i++) {
log.debug(" " + valves[i].getClass().getName());
}
}
log.debug("======================");
}
// Make our application available if no problems were encountered
if (ok) {
context.setConfigured(true);
} else {
log.error(sm.getString("contextConfig.unavailable"));
context.setConfigured(false);
}
}
/**
* Process a "stop" event for this Context.
*/
protected synchronized void configureStop() {
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.stop"));
}
int i;
// Removing children
Container[] children = context.findChildren();
for (i = 0; i < children.length; i++) {
context.removeChild(children[i]);
}
// Removing application parameters
/*
ApplicationParameter[] applicationParameters =
context.findApplicationParameters();
for (i = 0; i < applicationParameters.length; i++) {
context.removeApplicationParameter
(applicationParameters[i].getName());
}
*/
// Removing security constraints
SecurityConstraint[] securityConstraints = context.findConstraints();
for (i = 0; i < securityConstraints.length; i++) {
context.removeConstraint(securityConstraints[i]);
}
// Removing Ejbs
/*
ContextEjb[] contextEjbs = context.findEjbs();
for (i = 0; i < contextEjbs.length; i++) {
context.removeEjb(contextEjbs[i].getName());
}
*/
// Removing environments
/*
ContextEnvironment[] contextEnvironments = context.findEnvironments();
for (i = 0; i < contextEnvironments.length; i++) {
context.removeEnvironment(contextEnvironments[i].getName());
}
*/
// Removing errors pages
ErrorPage[] errorPages = context.findErrorPages();
for (i = 0; i < errorPages.length; i++) {
context.removeErrorPage(errorPages[i]);
}
// Removing filter defs
FilterDef[] filterDefs = context.findFilterDefs();
for (i = 0; i < filterDefs.length; i++) {
context.removeFilterDef(filterDefs[i]);
}
// Removing filter maps
FilterMap[] filterMaps = context.findFilterMaps();
for (i = 0; i < filterMaps.length; i++) {
context.removeFilterMap(filterMaps[i]);
}
// Removing local ejbs
/*
ContextLocalEjb[] contextLocalEjbs = context.findLocalEjbs();
for (i = 0; i < contextLocalEjbs.length; i++) {
context.removeLocalEjb(contextLocalEjbs[i].getName());
}
*/
// Removing Mime mappings
String[] mimeMappings = context.findMimeMappings();
for (i = 0; i < mimeMappings.length; i++) {
context.removeMimeMapping(mimeMappings[i]);
}
// Removing parameters
String[] parameters = context.findParameters();
for (i = 0; i < parameters.length; i++) {
context.removeParameter(parameters[i]);
}
// Removing resource env refs
/*
String[] resourceEnvRefs = context.findResourceEnvRefs();
for (i = 0; i < resourceEnvRefs.length; i++) {
context.removeResourceEnvRef(resourceEnvRefs[i]);
}
*/
// Removing resource links
/*
ContextResourceLink[] contextResourceLinks =
context.findResourceLinks();
for (i = 0; i < contextResourceLinks.length; i++) {
context.removeResourceLink(contextResourceLinks[i].getName());
}
*/
// Removing resources
/*
ContextResource[] contextResources = context.findResources();
for (i = 0; i < contextResources.length; i++) {
context.removeResource(contextResources[i].getName());
}
*/
// Removing security role
String[] securityRoles = context.findSecurityRoles();
for (i = 0; i < securityRoles.length; i++) {
context.removeSecurityRole(securityRoles[i]);
}
// Removing servlet mappings
String[] servletMappings = context.findServletMappings();
for (i = 0; i < servletMappings.length; i++) {
context.removeServletMapping(servletMappings[i]);
}
// FIXME : Removing status pages
// Removing welcome files
String[] welcomeFiles = context.findWelcomeFiles();
for (i = 0; i < welcomeFiles.length; i++) {
context.removeWelcomeFile(welcomeFiles[i]);
}
// Removing wrapper lifecycles
String[] wrapperLifecycles = context.findWrapperLifecycles();
for (i = 0; i < wrapperLifecycles.length; i++) {
context.removeWrapperLifecycle(wrapperLifecycles[i]);
}
// Removing wrapper listeners
String[] wrapperListeners = context.findWrapperListeners();
for (i = 0; i < wrapperListeners.length; i++) {
context.removeWrapperListener(wrapperListeners[i]);
}
// Remove (partially) folders and files created by antiLocking
if (antiLockingDocBase != null) {
// No need to log failure - it is expected in this case
ExpandWar.delete(antiLockingDocBase, false);
}
// Reset ServletContextInitializer scanning
initializerClassMap.clear();
typeInitializerMap.clear();
ok = true;
}
/**
* Process a "destroy" event for this Context.
*/
protected synchronized void destroy() {
// Called from StandardContext.destroy()
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.destroy"));
}
// Skip clearing the work directory if Tomcat is being shutdown
Server s = getServer();
if (s != null && !s.getState().isAvailable()) {
return;
}
// Changed to getWorkPath per Bugzilla 35819.
if (context instanceof StandardContext) {
String workDir = ((StandardContext) context).getWorkPath();
if (workDir != null) {
ExpandWar.delete(new File(workDir));
}
}
}
private Server getServer() {
Container c = context;
while (c != null && !(c instanceof Engine)) {
c = c.getParent();
}
if (c == null) {
return null;
}
Service s = ((Engine)c).getService();
if (s == null) {
return null;
}
return s.getServer();
}
/**
* Validate the usage of security role names in the web application
* deployment descriptor. If any problems are found, issue warning
* messages (for backwards compatibility) and add the missing roles.
* (To make these problems fatal instead, simply set the <code>ok</code>
* instance variable to <code>false</code> as well).
*/
protected void validateSecurityRoles() {
// Check role names used in <security-constraint> elements
SecurityConstraint constraints[] = context.findConstraints();
for (int i = 0; i < constraints.length; i++) {
String roles[] = constraints[i].findAuthRoles();
for (int j = 0; j < roles.length; j++) {
if (!"*".equals(roles[j]) &&
!context.findSecurityRole(roles[j])) {
log.info(sm.getString("contextConfig.role.auth", roles[j]));
context.addSecurityRole(roles[j]);
}
}
}
// Check role names used in <servlet> elements
Container wrappers[] = context.findChildren();
for (int i = 0; i < wrappers.length; i++) {
Wrapper wrapper = (Wrapper) wrappers[i];
String runAs = wrapper.getRunAs();
if ((runAs != null) && !context.findSecurityRole(runAs)) {
log.info(sm.getString("contextConfig.role.runas", runAs));
context.addSecurityRole(runAs);
}
String names[] = wrapper.findSecurityReferences();
for (int j = 0; j < names.length; j++) {
String link = wrapper.findSecurityReference(names[j]);
if ((link != null) && !context.findSecurityRole(link)) {
log.info(sm.getString("contextConfig.role.link", link));
context.addSecurityRole(link);
}
}
}
}
protected File getHostConfigBase() {
File file = null;
if (context.getParent() instanceof Host) {
file = ((Host)context.getParent()).getConfigBaseFile();
}
return file;
}
/**
* Scan the web.xml files that apply to the web application and merge them
* using the rules defined in the spec. For the global web.xml files,
* where there is duplicate configuration, the most specific level wins. ie
* an application's web.xml takes precedence over the host level or global
* web.xml file.
*/
protected void webConfig() {
/*
* Anything and everything can override the global and host defaults.
* This is implemented in two parts
* - Handle as a web fragment that gets added after everything else so
* everything else takes priority
* - Mark Servlets as overridable so SCI configuration can replace
* configuration from the defaults
*/
/*
* The rules for annotation scanning are not as clear-cut as one might
* think. Tomcat implements the following process:
* - As per SRV.1.6.2, Tomcat will scan for annotations regardless of
* which Servlet spec version is declared in web.xml. The EG has
* confirmed this is the expected behaviour.
* - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main
* web.xml is marked as metadata-complete, JARs are still processed
* for SCIs.
* - If metadata-complete=true and an absolute ordering is specified,
* JARs excluded from the ordering are also excluded from the SCI
* processing.
* - If an SCI has a @HandlesType annotation then all classes (except
* those in JARs excluded from an absolute ordering) need to be
* scanned to check if they match.
*/
Set<WebXml> defaults = new HashSet<>();
defaults.add(getDefaultWebXmlFragment());
WebXml webXml = createWebXml();
// Parse context level web.xml
InputSource contextWebXml = getContextWebXmlSource();
if (!webXmlParser.parseWebXml(contextWebXml, webXml, false)) {
ok = false;
}
ServletContext sContext = context.getServletContext();
// Ordering is important here
// Step 1. Identify all the JARs packaged with the application and those
// provided by the container. If any of the application JARs have a
// web-fragment.xml it will be parsed at this point. web-fragment.xml
// files are ignored for container provided JARs.
Map<String,WebXml> fragments = processJarsForWebFragments();
// Step 2. Order the fragments.
Set<WebXml> orderedFragments = null;
orderedFragments =
WebXml.orderWebFragments(webXml, fragments, sContext);
// Step 3. Look for ServletContainerInitializer implementations
if (ok) {
processServletContainerInitializers(context.getServletContext());
}
if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) {
// Step 4. Process /WEB-INF/classes for annotations and
// @HandlesTypes matches
if (ok) {
WebResource[] webResources =
context.getResources().listResources("/WEB-INF/classes");
for (WebResource webResource : webResources) {
processAnnotationsWebResource(webResource, webXml,
webXml.isMetadataComplete());
}
}
// Step 5. Process JARs for annotations for annotations and
// @HandlesTypes matches - only need to process those fragments we
// are going to use (remember orderedFragments includes any
// container fragments)
if (ok) {
processAnnotations(
orderedFragments, webXml.isMetadataComplete());
}
// Cache, if used, is no longer required so clear it
javaClassCache.clear();
}
if (!webXml.isMetadataComplete()) {
// Step 6. Merge web-fragment.xml files into the main web.xml
// file.
if (ok) {
ok = webXml.merge(orderedFragments);
}
// Step 7. Apply global defaults
// Have to merge defaults before JSP conversion since defaults
// provide JSP servlet definition.
webXml.merge(defaults);
// Step 8. Convert explicitly mentioned jsps to servlets
if (ok) {
convertJsps(webXml);
}
// Step 9. Apply merged web.xml to Context
if (ok) {
configureContext(webXml);
}
} else {
webXml.merge(defaults);
convertJsps(webXml);
configureContext(webXml);
}
// Step 9a. Make the merged web.xml available to other
// components, specifically Jasper, to save those components
// from having to re-generate it.
// TODO Use a ServletContainerInitializer for Jasper
String mergedWebXml = webXml.toXml();
sContext.setAttribute(
org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML,
mergedWebXml);
if (context.getLogEffectiveWebXml()) {
log.info("web.xml:\n" + mergedWebXml);
}
// Always need to look for static resources
// Step 10. Look for static resources packaged in JARs
if (ok) {
// Spec does not define an order.
// Use ordered JARs followed by remaining JARs
Set<WebXml> resourceJars = new LinkedHashSet<>();
if (orderedFragments != null) {
for (WebXml fragment : orderedFragments) {
resourceJars.add(fragment);
}
}
for (WebXml fragment : fragments.values()) {
if (!resourceJars.contains(fragment)) {
resourceJars.add(fragment);
}
}
processResourceJARs(resourceJars);
// See also StandardContext.resourcesStart() for
// WEB-INF/classes/META-INF/resources configuration
}
// Step 11. Apply the ServletContainerInitializer config to the
// context
if (ok) {
for (Map.Entry<ServletContainerInitializer,
Set<Class<?>>> entry :
initializerClassMap.entrySet()) {
if (entry.getValue().isEmpty()) {
context.addServletContainerInitializer(
entry.getKey(), null);
} else {
context.addServletContainerInitializer(
entry.getKey(), entry.getValue());
}
}
}
}
private void configureContext(WebXml webxml) {
// As far as possible, process in alphabetical order so it is easy to
// check everything is present
// Some validation depends on correct public ID
context.setPublicId(webxml.getPublicId());
// Everything else in order
context.setEffectiveMajorVersion(webxml.getMajorVersion());
context.setEffectiveMinorVersion(webxml.getMinorVersion());
for (Entry<String, String> entry : webxml.getContextParams().entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
context.setDenyUncoveredHttpMethods(
webxml.getDenyUncoveredHttpMethods());
context.setDisplayName(webxml.getDisplayName());
context.setDistributable(webxml.isDistributable());
for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) {
context.getNamingResources().addLocalEjb(ejbLocalRef);
}
for (ContextEjb ejbRef : webxml.getEjbRefs().values()) {
context.getNamingResources().addEjb(ejbRef);
}
for (ContextEnvironment environment : webxml.getEnvEntries().values()) {
context.getNamingResources().addEnvironment(environment);
}
for (ErrorPage errorPage : webxml.getErrorPages().values()) {
context.addErrorPage(errorPage);
}
for (FilterDef filter : webxml.getFilters().values()) {
if (filter.getAsyncSupported() == null) {
filter.setAsyncSupported("false");
}
context.addFilterDef(filter);
}
for (FilterMap filterMap : webxml.getFilterMappings()) {
context.addFilterMap(filterMap);
}
context.setJspConfigDescriptor(webxml.getJspConfigDescriptor());
for (String listener : webxml.getListeners()) {
context.addApplicationListener(
new ApplicationListener(listener, false));
}
for (Entry<String, String> entry :
webxml.getLocaleEncodingMappings().entrySet()) {
context.addLocaleEncodingMappingParameter(entry.getKey(),
entry.getValue());
}
// Prevents IAE
if (webxml.getLoginConfig() != null) {
context.setLoginConfig(webxml.getLoginConfig());
}
for (MessageDestinationRef mdr :
webxml.getMessageDestinationRefs().values()) {
context.getNamingResources().addMessageDestinationRef(mdr);
}
// messageDestinations were ignored in Tomcat 6, so ignore here
context.setIgnoreAnnotations(webxml.isMetadataComplete());
for (Entry<String, String> entry :
webxml.getMimeMappings().entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
// Name is just used for ordering
for (ContextResourceEnvRef resource :
webxml.getResourceEnvRefs().values()) {
context.getNamingResources().addResourceEnvRef(resource);
}
for (ContextResource resource : webxml.getResourceRefs().values()) {
context.getNamingResources().addResource(resource);
}
boolean allAuthenticatedUsersIsAppRole =
webxml.getSecurityRoles().contains(
SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS);
for (SecurityConstraint constraint : webxml.getSecurityConstraints()) {
if (allAuthenticatedUsersIsAppRole) {
constraint.treatAllAuthenticatedUsersAsApplicationRole();
}
context.addConstraint(constraint);
}
for (String role : webxml.getSecurityRoles()) {
context.addSecurityRole(role);
}
for (ContextService service : webxml.getServiceRefs().values()) {
context.getNamingResources().addService(service);
}
for (ServletDef servlet : webxml.getServlets().values()) {
Wrapper wrapper = context.createWrapper();
// Description is ignored
// Display name is ignored
// Icons are ignored
// jsp-file gets passed to the JSP Servlet as an init-param
if (servlet.getLoadOnStartup() != null) {
wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue());
}
if (servlet.getEnabled() != null) {
wrapper.setEnabled(servlet.getEnabled().booleanValue());
}
wrapper.setName(servlet.getServletName());
Map<String,String> params = servlet.getParameterMap();
for (Entry<String, String> entry : params.entrySet()) {
wrapper.addInitParameter(entry.getKey(), entry.getValue());
}
wrapper.setRunAs(servlet.getRunAs());
Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs();
for (SecurityRoleRef roleRef : roleRefs) {
wrapper.addSecurityReference(
roleRef.getName(), roleRef.getLink());
}
wrapper.setServletClass(servlet.getServletClass());
MultipartDef multipartdef = servlet.getMultipartDef();
if (multipartdef != null) {
if (multipartdef.getMaxFileSize() != null &&
multipartdef.getMaxRequestSize()!= null &&
multipartdef.getFileSizeThreshold() != null) {
wrapper.setMultipartConfigElement(new MultipartConfigElement(
multipartdef.getLocation(),
Long.parseLong(multipartdef.getMaxFileSize()),
Long.parseLong(multipartdef.getMaxRequestSize()),
Integer.parseInt(
multipartdef.getFileSizeThreshold())));
} else {
wrapper.setMultipartConfigElement(new MultipartConfigElement(
multipartdef.getLocation()));
}
}
if (servlet.getAsyncSupported() != null) {
wrapper.setAsyncSupported(
servlet.getAsyncSupported().booleanValue());
}
wrapper.setOverridable(servlet.isOverridable());
context.addChild(wrapper);
}
for (Entry<String, String> entry :
webxml.getServletMappings().entrySet()) {
context.addServletMapping(entry.getKey(), entry.getValue());
}
SessionConfig sessionConfig = webxml.getSessionConfig();
if (sessionConfig != null) {
if (sessionConfig.getSessionTimeout() != null) {
context.setSessionTimeout(
sessionConfig.getSessionTimeout().intValue());
}
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
scc.setName(sessionConfig.getCookieName());
scc.setDomain(sessionConfig.getCookieDomain());
scc.setPath(sessionConfig.getCookiePath());
scc.setComment(sessionConfig.getCookieComment());
if (sessionConfig.getCookieHttpOnly() != null) {
scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue());
}
if (sessionConfig.getCookieSecure() != null) {
scc.setSecure(sessionConfig.getCookieSecure().booleanValue());
}
if (sessionConfig.getCookieMaxAge() != null) {
scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue());
}
if (sessionConfig.getSessionTrackingModes().size() > 0) {
context.getServletContext().setSessionTrackingModes(
sessionConfig.getSessionTrackingModes());
}
}
// Context doesn't use version directly
for (String welcomeFile : webxml.getWelcomeFiles()) {
/*
* The following will result in a welcome file of "" so don't add
* that to the context
* <welcome-file-list>
* <welcome-file/>
* </welcome-file-list>
*/
if (welcomeFile != null && welcomeFile.length() > 0) {
context.addWelcomeFile(welcomeFile);
}
}
// Do this last as it depends on servlets
for (JspPropertyGroup jspPropertyGroup :
webxml.getJspPropertyGroups()) {
String jspServletName = context.findServletMapping("*.jsp");
if (jspServletName == null) {
jspServletName = "jsp";
}
if (context.findChild(jspServletName) != null) {
for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
context.addServletMapping(urlPattern, jspServletName, true);
}
} else {
if(log.isDebugEnabled()) {
for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
log.debug("Skiping " + urlPattern + " , no servlet " +
jspServletName);
}
}
}
}
for (Entry<String, String> entry :
webxml.getPostConstructMethods().entrySet()) {
context.addPostConstructMethod(entry.getKey(), entry.getValue());
}
for (Entry<String, String> entry :
webxml.getPreDestroyMethods().entrySet()) {
context.addPreDestroyMethod(entry.getKey(), entry.getValue());
}
}
private WebXml getDefaultWebXmlFragment() {
// Host should never be null
Host host = (Host) context.getParent();
DefaultWebXmlCacheEntry entry = hostWebXmlCache.get(host);
InputSource globalWebXml = getGlobalWebXmlSource();
InputSource hostWebXml = getHostWebXmlSource();
long globalTimeStamp = 0;
long hostTimeStamp = 0;
if (globalWebXml != null) {
try {
URL url = new URL(globalWebXml.getSystemId());
globalTimeStamp = url.openConnection().getLastModified();
} catch (MalformedURLException e) {
globalTimeStamp = -1;
} catch (IOException e) {
globalTimeStamp = -1;
}
}
if (hostWebXml != null) {
try {
URL url = new URL(hostWebXml.getSystemId());
hostTimeStamp = url.openConnection().getLastModified();
} catch (MalformedURLException e) {
hostTimeStamp = -1;
} catch (IOException e) {
hostTimeStamp = -1;
}
}
if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp &&
entry.getHostTimeStamp() == hostTimeStamp) {
return entry.getWebXml();
}
// Parsing global web.xml is relatively expensive. Use a sync block to
// make sure it only happens once. Use the pipeline since a lock will
// already be held on the host by another thread
synchronized (host.getPipeline()) {
entry = hostWebXmlCache.get(host);
if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp &&
entry.getHostTimeStamp() == hostTimeStamp) {
return entry.getWebXml();
}
WebXml webXmlDefaultFragment = createWebXml();
webXmlDefaultFragment.setOverridable(true);
// Set to distributable else every app will be prevented from being
// distributable when the default fragment is merged with the main
// web.xml
webXmlDefaultFragment.setDistributable(true);
// When merging, the default welcome files are only used if the app has
// not defined any welcomes files.
webXmlDefaultFragment.setAlwaysAddWelcomeFiles(false);
// Parse global web.xml if present
if (globalWebXml == null) {
// This is unusual enough to log
log.info(sm.getString("contextConfig.defaultMissing"));
} else {
if (!webXmlParser.parseWebXml(
globalWebXml, webXmlDefaultFragment, false)) {
ok = false;
}
}
// Parse host level web.xml if present
// Additive apart from welcome pages
webXmlDefaultFragment.setReplaceWelcomeFiles(true);
if (!webXmlParser.parseWebXml(
hostWebXml, webXmlDefaultFragment, false)) {
ok = false;
}
// Don't update the cache if an error occurs
if (globalTimeStamp != -1 && hostTimeStamp != -1) {
entry = new DefaultWebXmlCacheEntry(webXmlDefaultFragment,
globalTimeStamp, hostTimeStamp);
hostWebXmlCache.put(host, entry);
}
return webXmlDefaultFragment;
}
}
private void convertJsps(WebXml webXml) {
Map<String,String> jspInitParams;
ServletDef jspServlet = webXml.getServlets().get("jsp");
if (jspServlet == null) {
jspInitParams = new HashMap<>();
Wrapper w = (Wrapper) context.findChild("jsp");
if (w != null) {
String[] params = w.findInitParameters();
for (String param : params) {
jspInitParams.put(param, w.findInitParameter(param));
}
}
} else {
jspInitParams = jspServlet.getParameterMap();
}
for (ServletDef servletDef: webXml.getServlets().values()) {
if (servletDef.getJspFile() != null) {
convertJsp(servletDef, jspInitParams);
}
}
}
private void convertJsp(ServletDef servletDef,
Map<String,String> jspInitParams) {
servletDef.setServletClass(org.apache.catalina.core.Constants.JSP_SERVLET_CLASS);
String jspFile = servletDef.getJspFile();
if ((jspFile != null) && !jspFile.startsWith("/")) {
if (context.isServlet22()) {
if(log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.jspFile.warning",
jspFile));
}
jspFile = "/" + jspFile;
} else {
throw new IllegalArgumentException
(sm.getString("contextConfig.jspFile.error", jspFile));
}
}
servletDef.getParameterMap().put("jspFile", jspFile);
servletDef.setJspFile(null);
for (Map.Entry<String, String> initParam: jspInitParams.entrySet()) {
servletDef.addInitParameter(initParam.getKey(), initParam.getValue());
}
}
protected WebXml createWebXml() {
return new WebXml();
}
/**
* Scan JARs for ServletContainerInitializer implementations.
*/
protected void processServletContainerInitializers(ServletContext servletContext) {
Collection<ServletContainerInitializer> detectedScis;
try {
WebappServiceLoader<ServletContainerInitializer> loader =
new WebappServiceLoader<>(servletContext);
detectedScis = loader.load(ServletContainerInitializer.class);
} catch (IOException e) {
log.error(sm.getString(
"contextConfig.servletContainerInitializerFail",
context.getName()),
e);
ok = false;
return;
}
for (ServletContainerInitializer sci : detectedScis) {
initializerClassMap.put(sci, new HashSet<Class<?>>());
HandlesTypes ht;
try {
ht = sci.getClass().getAnnotation(HandlesTypes.class);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.info(sm.getString("contextConfig.sci.debug",
sci.getClass().getName()),
e);
} else {
log.info(sm.getString("contextConfig.sci.info",
sci.getClass().getName()));
}
continue;
}
if (ht == null) {
continue;
}
Class<?>[] types = ht.value();
if (types == null) {
continue;
}
for (Class<?> type : types) {
if (type.isAnnotation()) {
handlesTypesAnnotations = true;
} else {
handlesTypesNonAnnotations = true;
}
Set<ServletContainerInitializer> scis =
typeInitializerMap.get(type);
if (scis == null) {
scis = new HashSet<>();
typeInitializerMap.put(type, scis);
}
scis.add(sci);
}
}
}
/**
* Scan JARs that contain web-fragment.xml files that will be used to
* configure this application to see if they also contain static resources.
* If static resources are found, add them to the context. Resources are
* added in web-fragment.xml priority order.
*/
protected void processResourceJARs(Set<WebXml> fragments) {
for (WebXml fragment : fragments) {
URL url = fragment.getURL();
Jar jar = null;
try {
// Note: Ignore file URLs for now since only jar URLs will be accepted
if ("jar".equals(url.getProtocol())) {
jar = JarFactory.newInstance(url);
jar.nextEntry();
String entryName = jar.getEntryName();
while (entryName != null) {
if (entryName.startsWith("META-INF/resources/")) {
context.getResources().createWebResourceSet(
WebResourceRoot.ResourceSetType.RESOURCE_JAR,
url, "/", "/META-INF/resources");
break;
}
jar.nextEntry();
entryName = jar.getEntryName();
}
} else if ("file".equals(url.getProtocol())) {
File file = new File(url.toURI());
File resources = new File(file, "META-INF/resources/");
if (resources.isDirectory()) {
context.getResources().createWebResourceSet(
WebResourceRoot.ResourceSetType.RESOURCE_JAR,
file.getAbsolutePath(), "/", "/");
}
}
} catch (IOException ioe) {
log.error(sm.getString("contextConfig.resourceJarFail", url,
context.getName()));
} catch (URISyntaxException e) {
log.error(sm.getString("contextConfig.resourceJarFail", url,
context.getName()));
} finally {
if (jar != null) {
jar.close();
}
}
}
}
/**
* Identify the default web.xml to be used and obtain an input source for
* it.
*/
protected InputSource getGlobalWebXmlSource() {
// Is a default web.xml specified for the Context?
if (defaultWebXml == null && context instanceof StandardContext) {
defaultWebXml = ((StandardContext) context).getDefaultWebXml();
}
// Set the default if we don't have any overrides
if (defaultWebXml == null) {
getDefaultWebXml();
}
// Is it explicitly suppressed, e.g. in embedded environment?
if (Constants.NoDefaultWebXml.equals(defaultWebXml)) {
return null;
}
return getWebXmlSource(defaultWebXml,
context.getCatalinaBase().getPath());
}
/**
* Identify the host web.xml to be used and obtain an input source for
* it.
*/
protected InputSource getHostWebXmlSource() {
File hostConfigBase = getHostConfigBase();
if (hostConfigBase == null)
return null;
return getWebXmlSource(Constants.HostWebXml, hostConfigBase.getPath());
}
/**
* Identify the application web.xml to be used and obtain an input source
* for it.
*/
@SuppressWarnings("resource") // stream is meant to be left open here
protected InputSource getContextWebXmlSource() {
InputStream stream = null;
InputSource source = null;
URL url = null;
String altDDName = null;
// Open the application web.xml file, if it exists
ServletContext servletContext = context.getServletContext();
if (servletContext != null) {
altDDName = (String)servletContext.getAttribute(
Globals.ALT_DD_ATTR);
if (altDDName != null) {
try {
stream = new FileInputStream(altDDName);
url = new File(altDDName).toURI().toURL();
} catch (FileNotFoundException e) {
log.error(sm.getString("contextConfig.altDDNotFound",
altDDName));
} catch (MalformedURLException e) {
log.error(sm.getString("contextConfig.applicationUrl"));
}
}
else {
stream = servletContext.getResourceAsStream
(Constants.ApplicationWebXml);
try {
url = servletContext.getResource(
Constants.ApplicationWebXml);
} catch (MalformedURLException e) {
log.error(sm.getString("contextConfig.applicationUrl"));
}
}
}
if (stream == null || url == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.applicationMissing") + " " + context);
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
} else {
source = new InputSource(url.toExternalForm());
source.setByteStream(stream);
}
return source;
}
/**
*
* @param filename Name of the file (possibly with one or more leading path
* segments) to read
* @param path Location that filename is relative to
*/
protected InputSource getWebXmlSource(String filename, String path) {
File file = new File(filename);
if (!file.isAbsolute()) {
file = new File(path, filename);
}
InputStream stream = null;
InputSource source = null;
try {
if (!file.exists()) {
// Use getResource and getResourceAsStream
stream =
getClass().getClassLoader().getResourceAsStream(filename);
if(stream != null) {
source =
new InputSource(getClass().getClassLoader().getResource(
filename).toURI().toString());
}
} else {
source = new InputSource(file.getAbsoluteFile().toURI().toString());
stream = new FileInputStream(file);
}
if (stream != null && source != null) {
source.setByteStream(stream);
}
} catch (Exception e) {
log.error(sm.getString(
"contextConfig.defaultError", filename, file), e);
}
return source;
}
/**
* Scan /WEB-INF/lib for JARs and for each one found add it and any
* /META-INF/web-fragment.xml to the resulting Map. web-fragment.xml files
* will be parsed before being added to the map. Every JAR will be added and
* <code>null</code> will be used if no web-fragment.xml was found. Any JARs
* known not contain fragments will be skipped.
*
* @return A map of JAR name to processed web fragment (if any)
*/
protected Map<String,WebXml> processJarsForWebFragments() {
JarScanner jarScanner = context.getJarScanner();
boolean delegate = false;
if (context instanceof StandardContext) {
delegate = ((StandardContext) context).getDelegate();
}
FragmentJarScannerCallback callback =
new FragmentJarScannerCallback(webXmlParser, delegate);
jarScanner.scan(JarScanType.PLUGGABILITY,
context.getServletContext(), callback);
if (!callback.isOk()) {
ok = false;
}
return callback.getFragments();
}
protected void processAnnotations(Set<WebXml> fragments,
boolean handlesTypesOnly) {
for(WebXml fragment : fragments) {
// Only need to scan for @HandlesTypes matches if any of the
// following are true:
// - it has already been determined only @HandlesTypes is required
// (e.g. main web.xml has metadata-complete="true"
// - this fragment is for a container JAR (Servlet 3.1 section 8.1)
// - this fragment has metadata-complete="true"
boolean htOnly = handlesTypesOnly || !fragment.getWebappJar() ||
fragment.isMetadataComplete();
WebXml annotations = new WebXml();
// no impact on distributable
annotations.setDistributable(true);
URL url = fragment.getURL();
processAnnotationsUrl(url, annotations, htOnly);
Set<WebXml> set = new HashSet<>();
set.add(annotations);
// Merge annotations into fragment - fragment takes priority
fragment.merge(set);
}
}
protected void processAnnotationsWebResource(WebResource webResource,
WebXml fragment, boolean handlesTypesOnly) {
if (webResource.isDirectory()) {
WebResource[] webResources =
webResource.getWebResourceRoot().listResources(
webResource.getWebappPath());
for (WebResource r : webResources) {
processAnnotationsWebResource(r, fragment, handlesTypesOnly);
}
} else if (webResource.isFile() &&
webResource.getName().endsWith(".class")) {
InputStream is = null;
try {
is = webResource.getInputStream();
processAnnotationsStream(is, fragment, handlesTypesOnly);
} catch (IOException e) {
log.error(sm.getString("contextConfig.inputStreamWebResource",
webResource.getWebappPath()),e);
} catch (ClassFormatException e) {
log.error(sm.getString("contextConfig.inputStreamWebResource",
webResource.getWebappPath()),e);
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
}
}
}
protected void processAnnotationsUrl(URL url, WebXml fragment,
boolean handlesTypesOnly) {
if (url == null) {
// Nothing to do.
return;
} else if ("jar".equals(url.getProtocol())) {
processAnnotationsJar(url, fragment, handlesTypesOnly);
} else if ("file".equals(url.getProtocol())) {
try {
processAnnotationsFile(
new File(url.toURI()), fragment, handlesTypesOnly);
} catch (URISyntaxException e) {
log.error(sm.getString("contextConfig.fileUrl", url), e);
}
} else {
log.error(sm.getString("contextConfig.unknownUrlProtocol",
url.getProtocol(), url));
}
}
protected void processAnnotationsJar(URL url, WebXml fragment,
boolean handlesTypesOnly) {
Jar jar = null;
InputStream is;
try {
jar = JarFactory.newInstance(url);
jar.nextEntry();
String entryName = jar.getEntryName();
while (entryName != null) {
if (entryName.endsWith(".class")) {
is = null;
try {
is = jar.getEntryInputStream();
processAnnotationsStream(
is, fragment, handlesTypesOnly);
} catch (IOException e) {
log.error(sm.getString("contextConfig.inputStreamJar",
entryName, url),e);
} catch (ClassFormatException e) {
log.error(sm.getString("contextConfig.inputStreamJar",
entryName, url),e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
jar.nextEntry();
entryName = jar.getEntryName();
}
} catch (IOException e) {
log.error(sm.getString("contextConfig.jarFile", url), e);
} finally {
if (jar != null) {
jar.close();
}
}
}
protected void processAnnotationsFile(File file, WebXml fragment,
boolean handlesTypesOnly) {
if (file.isDirectory()) {
String[] dirs = file.list();
for (String dir : dirs) {
processAnnotationsFile(
new File(file,dir), fragment, handlesTypesOnly);
}
} else if (file.canRead() && file.getName().endsWith(".class")) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
processAnnotationsStream(fis, fragment, handlesTypesOnly);
} catch (IOException e) {
log.error(sm.getString("contextConfig.inputStreamFile",
file.getAbsolutePath()),e);
} catch (ClassFormatException e) {
log.error(sm.getString("contextConfig.inputStreamFile",
file.getAbsolutePath()),e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
}
}
}
protected void processAnnotationsStream(InputStream is, WebXml fragment,
boolean handlesTypesOnly)
throws ClassFormatException, IOException {
ClassParser parser = new ClassParser(is, null);
JavaClass clazz = parser.parse();
checkHandlesTypes(clazz);
if (handlesTypesOnly) {
return;
}
String className = clazz.getClassName();
AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries();
for (AnnotationEntry ae : annotationsEntries) {
String type = ae.getAnnotationType();
if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) {
processAnnotationWebServlet(className, ae, fragment);
}else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) {
processAnnotationWebFilter(className, ae, fragment);
}else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) {
fragment.addListener(className);
} else {
// Unknown annotation - ignore
}
}
}
/**
* For classes packaged with the web application, the class and each
* super class needs to be checked for a match with {@link HandlesTypes} or
* for an annotation that matches {@link HandlesTypes}.
* @param javaClass
*/
protected void checkHandlesTypes(JavaClass javaClass) {
// Skip this if we can
if (typeInitializerMap.size() == 0) {
return;
}
if ((javaClass.getAccessFlags() &
org.apache.tomcat.util.bcel.Constants.ACC_ANNOTATION) > 0) {
// Skip annotations.
return;
}
String className = javaClass.getClassName();
Class<?> clazz = null;
if (handlesTypesNonAnnotations) {
// This *might* be match for a HandlesType.
populateJavaClassCache(className, javaClass);
JavaClassCacheEntry entry = javaClassCache.get(className);
if (entry.getSciSet() == null) {
try {
populateSCIsForCacheEntry(entry);
} catch (StackOverflowError soe) {
throw new IllegalStateException(sm.getString(
"contextConfig.annotationsStackOverflow",
context.getName(),
classHierarchyToString(className, entry)));
}
}
if (entry.getSciSet().size() > 0) {
// Need to try and load the class
clazz = Introspection.loadClass(context, className);
if (clazz == null) {
// Can't load the class so no point continuing
return;
}
for (ServletContainerInitializer sci :
entry.getSciSet()) {
Set<Class<?>> classes = initializerClassMap.get(sci);
if (classes == null) {
classes = new HashSet<>();
initializerClassMap.put(sci, classes);
}
classes.add(clazz);
}
}
}
if (handlesTypesAnnotations) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
if (entry.getKey().isAnnotation()) {
AnnotationEntry[] annotationEntries =
javaClass.getAnnotationEntries();
for (AnnotationEntry annotationEntry : annotationEntries) {
if (entry.getKey().getName().equals(
getClassName(annotationEntry.getAnnotationType()))) {
if (clazz == null) {
clazz = Introspection.loadClass(
context, className);
if (clazz == null) {
// Can't load the class so no point
// continuing
return;
}
}
for (ServletContainerInitializer sci : entry.getValue()) {
initializerClassMap.get(sci).add(clazz);
}
break;
}
}
}
}
}
}
private String classHierarchyToString(String className,
JavaClassCacheEntry entry) {
JavaClassCacheEntry start = entry;
StringBuilder msg = new StringBuilder(className);
msg.append("->");
String parentName = entry.getSuperclassName();
JavaClassCacheEntry parent = javaClassCache.get(parentName);
int count = 0;
while (count < 100 && parent != null && parent != start) {
msg.append(parentName);
msg.append("->");
count ++;
parentName = parent.getSuperclassName();
parent = javaClassCache.get(parentName);
}
msg.append(parentName);
return msg.toString();
}
private void populateJavaClassCache(String className, JavaClass javaClass) {
if (javaClassCache.containsKey(className)) {
return;
}
// Add this class to the cache
javaClassCache.put(className, new JavaClassCacheEntry(javaClass));
populateJavaClassCache(javaClass.getSuperclassName());
for (String iterface : javaClass.getInterfaceNames()) {
populateJavaClassCache(iterface);
}
}
private void populateJavaClassCache(String className) {
if (!javaClassCache.containsKey(className)) {
String name = className.replace('.', '/') + ".class";
InputStream is =
context.getLoader().getClassLoader().getResourceAsStream(name);
if (is == null) {
return;
}
ClassParser parser = new ClassParser(is, null);
try {
JavaClass clazz = parser.parse();
populateJavaClassCache(clazz.getClassName(), clazz);
} catch (ClassFormatException e) {
log.debug(sm.getString("contextConfig.invalidSciHandlesTypes",
className), e);
} catch (IOException e) {
log.debug(sm.getString("contextConfig.invalidSciHandlesTypes",
className), e);
}
}
}
private void populateSCIsForCacheEntry(JavaClassCacheEntry cacheEntry) {
Set<ServletContainerInitializer> result = new HashSet<>();
// Super class
String superClassName = cacheEntry.getSuperclassName();
JavaClassCacheEntry superClassCacheEntry =
javaClassCache.get(superClassName);
// Avoid an infinite loop with java.lang.Object
if (cacheEntry.equals(superClassCacheEntry)) {
cacheEntry.setSciSet(new HashSet<ServletContainerInitializer>());
return;
}
// May be null of the class is not present or could not be loaded.
if (superClassCacheEntry != null) {
if (superClassCacheEntry.getSciSet() == null) {
populateSCIsForCacheEntry(superClassCacheEntry);
}
result.addAll(superClassCacheEntry.getSciSet());
}
result.addAll(getSCIsForClass(superClassName));
// Interfaces
for (String interfaceName : cacheEntry.getInterfaceNames()) {
JavaClassCacheEntry interfaceEntry =
javaClassCache.get(interfaceName);
// A null could mean that the class not present in application or
// that there is nothing of interest. Either way, nothing to do here
// so move along
if (interfaceEntry != null) {
if (interfaceEntry.getSciSet() == null) {
populateSCIsForCacheEntry(interfaceEntry);
}
result.addAll(interfaceEntry.getSciSet());
}
result.addAll(getSCIsForClass(interfaceName));
}
cacheEntry.setSciSet(result);
}
private Set<ServletContainerInitializer> getSCIsForClass(String className) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
Class<?> clazz = entry.getKey();
if (!clazz.isAnnotation()) {
if (clazz.getName().equals(className)) {
return entry.getValue();
}
}
}
return Collections.emptySet();
}
private static final String getClassName(String internalForm) {
if (!internalForm.startsWith("L")) {
return internalForm;
}
// Assume starts with L, ends with ; and uses / rather than .
return internalForm.substring(1,
internalForm.length() - 1).replace('/', '.');
}
protected void processAnnotationWebServlet(String className,
AnnotationEntry ae, WebXml fragment) {
String servletName = null;
// must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81
ElementValuePair[] evps = ae.getElementValuePairs();
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("name".equals(name)) {
servletName = evp.getValue().stringifyValue();
break;
}
}
if (servletName == null) {
// classname is default servletName as annotation has no name!
servletName = className;
}
ServletDef servletDef = fragment.getServlets().get(servletName);
boolean isWebXMLservletDef;
if (servletDef == null) {
servletDef = new ServletDef();
servletDef.setServletName(servletName);
servletDef.setServletClass(className);
isWebXMLservletDef = false;
} else {
isWebXMLservletDef = true;
}
boolean urlPatternsSet = false;
String[] urlPatterns = null;
// ElementValuePair[] evps = ae.getElementValuePairs();
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("value".equals(name) || "urlPatterns".equals(name)) {
if (urlPatternsSet) {
throw new IllegalArgumentException(sm.getString(
"contextConfig.urlPatternValue", className));
}
urlPatternsSet = true;
urlPatterns = processAnnotationsStringArray(evp.getValue());
} else if ("description".equals(name)) {
if (servletDef.getDescription() == null) {
servletDef.setDescription(evp.getValue().stringifyValue());
}
} else if ("displayName".equals(name)) {
if (servletDef.getDisplayName() == null) {
servletDef.setDisplayName(evp.getValue().stringifyValue());
}
} else if ("largeIcon".equals(name)) {
if (servletDef.getLargeIcon() == null) {
servletDef.setLargeIcon(evp.getValue().stringifyValue());
}
} else if ("smallIcon".equals(name)) {
if (servletDef.getSmallIcon() == null) {
servletDef.setSmallIcon(evp.getValue().stringifyValue());
}
} else if ("asyncSupported".equals(name)) {
if (servletDef.getAsyncSupported() == null) {
servletDef.setAsyncSupported(evp.getValue()
.stringifyValue());
}
} else if ("loadOnStartup".equals(name)) {
if (servletDef.getLoadOnStartup() == null) {
servletDef
.setLoadOnStartup(evp.getValue().stringifyValue());
}
} else if ("initParams".equals(name)) {
Map<String, String> initParams = processAnnotationWebInitParams(evp
.getValue());
if (isWebXMLservletDef) {
Map<String, String> webXMLInitParams = servletDef
.getParameterMap();
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
if (webXMLInitParams.get(entry.getKey()) == null) {
servletDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
} else {
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
servletDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
}
}
if (!isWebXMLservletDef && urlPatterns != null) {
fragment.addServlet(servletDef);
}
if (urlPatterns != null) {
if (!fragment.getServletMappings().containsValue(servletName)) {
for (String urlPattern : urlPatterns) {
fragment.addServletMapping(urlPattern, servletName);
}
}
}
}
/**
* process filter annotation and merge with existing one!
* FIXME: refactoring method too long and has redundant subroutines with
* processAnnotationWebServlet!
* @param className
* @param ae
* @param fragment
*/
protected void processAnnotationWebFilter(String className,
AnnotationEntry ae, WebXml fragment) {
String filterName = null;
// must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81
ElementValuePair[] evps = ae.getElementValuePairs();
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("filterName".equals(name)) {
filterName = evp.getValue().stringifyValue();
break;
}
}
if (filterName == null) {
// classname is default filterName as annotation has no name!
filterName = className;
}
FilterDef filterDef = fragment.getFilters().get(filterName);
FilterMap filterMap = new FilterMap();
boolean isWebXMLfilterDef;
if (filterDef == null) {
filterDef = new FilterDef();
filterDef.setFilterName(filterName);
filterDef.setFilterClass(className);
isWebXMLfilterDef = false;
} else {
isWebXMLfilterDef = true;
}
boolean urlPatternsSet = false;
boolean servletNamesSet = false;
boolean dispatchTypesSet = false;
String[] urlPatterns = null;
for (ElementValuePair evp : evps) {
String name = evp.getNameString();
if ("value".equals(name) || "urlPatterns".equals(name)) {
if (urlPatternsSet) {
throw new IllegalArgumentException(sm.getString(
"contextConfig.urlPatternValue", className));
}
urlPatterns = processAnnotationsStringArray(evp.getValue());
urlPatternsSet = urlPatterns.length > 0;
for (String urlPattern : urlPatterns) {
filterMap.addURLPattern(urlPattern);
}
} else if ("servletNames".equals(name)) {
String[] servletNames = processAnnotationsStringArray(evp
.getValue());
servletNamesSet = servletNames.length > 0;
for (String servletName : servletNames) {
filterMap.addServletName(servletName);
}
} else if ("dispatcherTypes".equals(name)) {
String[] dispatcherTypes = processAnnotationsStringArray(evp
.getValue());
dispatchTypesSet = dispatcherTypes.length > 0;
for (String dispatcherType : dispatcherTypes) {
filterMap.setDispatcher(dispatcherType);
}
} else if ("description".equals(name)) {
if (filterDef.getDescription() == null) {
filterDef.setDescription(evp.getValue().stringifyValue());
}
} else if ("displayName".equals(name)) {
if (filterDef.getDisplayName() == null) {
filterDef.setDisplayName(evp.getValue().stringifyValue());
}
} else if ("largeIcon".equals(name)) {
if (filterDef.getLargeIcon() == null) {
filterDef.setLargeIcon(evp.getValue().stringifyValue());
}
} else if ("smallIcon".equals(name)) {
if (filterDef.getSmallIcon() == null) {
filterDef.setSmallIcon(evp.getValue().stringifyValue());
}
} else if ("asyncSupported".equals(name)) {
if (filterDef.getAsyncSupported() == null) {
filterDef
.setAsyncSupported(evp.getValue().stringifyValue());
}
} else if ("initParams".equals(name)) {
Map<String, String> initParams = processAnnotationWebInitParams(evp
.getValue());
if (isWebXMLfilterDef) {
Map<String, String> webXMLInitParams = filterDef
.getParameterMap();
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
if (webXMLInitParams.get(entry.getKey()) == null) {
filterDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
} else {
for (Map.Entry<String, String> entry : initParams
.entrySet()) {
filterDef.addInitParameter(entry.getKey(), entry
.getValue());
}
}
}
}
if (!isWebXMLfilterDef) {
fragment.addFilter(filterDef);
if (urlPatternsSet || servletNamesSet) {
filterMap.setFilterName(filterName);
fragment.addFilterMapping(filterMap);
}
}
if (urlPatternsSet || dispatchTypesSet) {
Set<FilterMap> fmap = fragment.getFilterMappings();
FilterMap descMap = null;
for (FilterMap map : fmap) {
if (filterName.equals(map.getFilterName())) {
descMap = map;
break;
}
}
if (descMap != null) {
String[] urlsPatterns = descMap.getURLPatterns();
if (urlPatternsSet
&& (urlsPatterns == null || urlsPatterns.length == 0)) {
for (String urlPattern : filterMap.getURLPatterns()) {
descMap.addURLPattern(urlPattern);
}
}
String[] dispatcherNames = descMap.getDispatcherNames();
if (dispatchTypesSet
&& (dispatcherNames == null || dispatcherNames.length == 0)) {
for (String dis : filterMap.getDispatcherNames()) {
descMap.setDispatcher(dis);
}
}
}
}
}
protected String[] processAnnotationsStringArray(ElementValue ev) {
ArrayList<String> values = new ArrayList<>();
if (ev instanceof ArrayElementValue) {
ElementValue[] arrayValues =
((ArrayElementValue) ev).getElementValuesArray();
for (ElementValue value : arrayValues) {
values.add(value.stringifyValue());
}
} else {
values.add(ev.stringifyValue());
}
String[] result = new String[values.size()];
return values.toArray(result);
}
protected Map<String,String> processAnnotationWebInitParams(
ElementValue ev) {
Map<String, String> result = new HashMap<>();
if (ev instanceof ArrayElementValue) {
ElementValue[] arrayValues =
((ArrayElementValue) ev).getElementValuesArray();
for (ElementValue value : arrayValues) {
if (value instanceof AnnotationElementValue) {
ElementValuePair[] evps = ((AnnotationElementValue)
value).getAnnotationEntry().getElementValuePairs();
String initParamName = null;
String initParamValue = null;
for (ElementValuePair evp : evps) {
if ("name".equals(evp.getNameString())) {
initParamName = evp.getValue().stringifyValue();
} else if ("value".equals(evp.getNameString())) {
initParamValue = evp.getValue().stringifyValue();
} else {
// Ignore
}
}
result.put(initParamName, initParamValue);
}
}
}
return result;
}
private static class DefaultWebXmlCacheEntry {
private final WebXml webXml;
private final long globalTimeStamp;
private final long hostTimeStamp;
public DefaultWebXmlCacheEntry(WebXml webXml, long globalTimeStamp,
long hostTimeStamp) {
this.webXml = webXml;
this.globalTimeStamp = globalTimeStamp;
this.hostTimeStamp = hostTimeStamp;
}
public WebXml getWebXml() {
return webXml;
}
public long getGlobalTimeStamp() {
return globalTimeStamp;
}
public long getHostTimeStamp() {
return hostTimeStamp;
}
}
private static class JavaClassCacheEntry {
public final String superclassName;
public final String[] interfaceNames;
private Set<ServletContainerInitializer> sciSet = null;
public JavaClassCacheEntry(JavaClass javaClass) {
superclassName = javaClass.getSuperclassName();
interfaceNames = javaClass.getInterfaceNames();
}
public String getSuperclassName() {
return superclassName;
}
public String[] getInterfaceNames() {
return interfaceNames;
}
public Set<ServletContainerInitializer> getSciSet() {
return sciSet;
}
public void setSciSet(Set<ServletContainerInitializer> sciSet) {
this.sciSet = sciSet;
}
}
}
|
55,400
|
Bug 55400 WsFilter not compatible with async sample applications
| null |
resolved fixed
|
3490f73
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-14T12:29:03Z
| 2013-08-11T00:13:20Z
|
java/org/apache/tomcat/websocket/server/WsServerContainer.java
|
/*
* 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.websocket.server;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Encoder;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.WsSession;
import org.apache.tomcat.websocket.WsWebSocketContainer;
import org.apache.tomcat.websocket.pojo.PojoEndpointServer;
import org.apache.tomcat.websocket.pojo.PojoMethodMapping;
/**
* Provides a per class loader (i.e. per web application) instance of a
* ServerContainer. Web application wide defaults may be configured by setting
* the following servlet context initialisation parameters to the desired
* values.
* <ul>
* <li>{@link Constants#BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li>
* <li>{@link Constants#TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li>
* </ul>
*/
public class WsServerContainer extends WsWebSocketContainer
implements ServerContainer {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static final CloseReason AUTHENTICATED_HTTP_SESSION_CLOSED =
new CloseReason(CloseCodes.VIOLATED_POLICY,
"This connection was established under an authenticated " +
"HTTP session that has ended.");
private final WsWriteTimeout wsWriteTimeout = new WsWriteTimeout();
private final ServletContext servletContext;
private final Map<String,ServerEndpointConfig> configExactMatchMap =
new ConcurrentHashMap<>();
private final ConcurrentHashMap<Integer,SortedSet<TemplatePathMatch>>
configTemplateMatchMap = new ConcurrentHashMap<>();
private volatile boolean enforceNoAddAfterHandshake =
org.apache.tomcat.websocket.Constants.STRICT_SPEC_COMPLIANCE;
private volatile boolean addAllowed = true;
private final ConcurrentHashMap<String,Set<WsSession>> authenticatedSessions =
new ConcurrentHashMap<>();
WsServerContainer(ServletContext servletContext) {
this.servletContext = servletContext;
// Configure servlet context wide defaults
String value = servletContext.getInitParameter(
Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
if (value != null) {
setDefaultMaxBinaryMessageBufferSize(Integer.parseInt(value));
}
value = servletContext.getInitParameter(
Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
if (value != null) {
setDefaultMaxTextMessageBufferSize(Integer.parseInt(value));
}
value = servletContext.getInitParameter(
Constants.ENFORCE_NO_ADD_AFTER_HANDSHAKE_CONTEXT_INIT_PARAM);
if (value != null) {
setEnforceNoAddAfterHandshake(Boolean.parseBoolean(value));
}
FilterRegistration fr = servletContext.addFilter(
WsFilter.class.getName(), new WsFilter(this));
EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.REQUEST,
DispatcherType.FORWARD);
fr.addMappingForUrlPatterns(types, true, "/*");
}
/**
* Published the provided endpoint implementation at the specified path with
* the specified configuration. {@link #WsServerContainer(ServletContext)}
* must be called before calling this method.
*
* @param sec The configuration to use when creating endpoint instances
* @throws DeploymentException
*/
@Override
public void addEndpoint(ServerEndpointConfig sec)
throws DeploymentException {
if (enforceNoAddAfterHandshake && !addAllowed) {
throw new DeploymentException(
sm.getString("serverContainer.addNotAllowed"));
}
if (servletContext == null) {
throw new DeploymentException(
sm.getString("serverContainer.servletContextMissing"));
}
String path = sec.getPath();
UriTemplate uriTemplate = new UriTemplate(path);
if (uriTemplate.hasParameters()) {
Integer key = Integer.valueOf(uriTemplate.getSegmentCount());
SortedSet<TemplatePathMatch> templateMatches =
configTemplateMatchMap.get(key);
if (templateMatches == null) {
// Ensure that if concurrent threads execute this block they
// both end up using the same TreeSet instance
templateMatches = new TreeSet<>(
TemplatePathMatchComparator.getInstance());
configTemplateMatchMap.putIfAbsent(key, templateMatches);
templateMatches = configTemplateMatchMap.get(key);
}
if (!templateMatches.add(new TemplatePathMatch(sec, uriTemplate))) {
// Duplicate uriTemplate;
throw new DeploymentException(
sm.getString("serverContainer.duplicatePaths", path));
}
} else {
// Exact match
ServerEndpointConfig old = configExactMatchMap.put(path, sec);
if (old != null) {
// Duplicate path mappings
throw new DeploymentException(
sm.getString("serverContainer.duplicatePaths", path));
}
}
}
/**
* Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)}
* for publishing plain old java objects (POJOs) that have been annotated as
* WebSocket endpoints.
*
* @param pojo The annotated POJO
*/
@Override
public void addEndpoint(Class<?> pojo) throws DeploymentException {
ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
if (annotation == null) {
throw new DeploymentException(
sm.getString("serverContainer.missingAnnotation",
pojo.getName()));
}
String path = annotation.value();
// Validate encoders
validateEncoders(annotation.encoders());
// Method mapping
PojoMethodMapping methodMapping = new PojoMethodMapping(pojo,
annotation.decoders(), path);
// ServerEndpointConfig
ServerEndpointConfig sec;
Class<? extends Configurator> configuratorClazz =
annotation.configurator();
Configurator configurator = null;
if (!configuratorClazz.equals(Configurator.class)) {
try {
configurator = annotation.configurator().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new DeploymentException(sm.getString(
"serverContainer.configuratorFail",
annotation.configurator().getName(),
pojo.getClass().getName()), e);
}
}
sec = ServerEndpointConfig.Builder.create(pojo, path).
decoders(Arrays.asList(annotation.decoders())).
encoders(Arrays.asList(annotation.encoders())).
subprotocols(Arrays.asList(annotation.subprotocols())).
configurator(configurator).
build();
sec.getUserProperties().put(
PojoEndpointServer.POJO_METHOD_MAPPING_KEY,
methodMapping);
addEndpoint(sec);
}
public WsMappingResult findMapping(String path) {
// Prevent registering additional endpoints once the first attempt has
// been made to use one
if (addAllowed) {
addAllowed = false;
}
// Check an exact match. Simple case as there are no templates.
ServerEndpointConfig sec = configExactMatchMap.get(path);
if (sec != null) {
return new WsMappingResult(sec,
Collections.<String, String> emptyMap());
}
// No exact match. Need to look for template matches.
UriTemplate pathUriTemplate = null;
try {
pathUriTemplate = new UriTemplate(path);
} catch (DeploymentException e) {
// Path is not valid so can't be matched to a WebSocketEndpoint
return null;
}
// Number of segments has to match
Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount());
SortedSet<TemplatePathMatch> templateMatches =
configTemplateMatchMap.get(key);
if (templateMatches == null) {
// No templates with an equal number of segments so there will be
// no matches
return null;
}
// List is in alphabetical order of normalised templates.
// Correct match is the first one that matches.
Map<String,String> pathParams = null;
for (TemplatePathMatch templateMatch : templateMatches) {
pathParams = templateMatch.getUriTemplate().match(pathUriTemplate);
if (pathParams != null) {
sec = templateMatch.getConfig();
break;
}
}
if (sec == null) {
// No match
return null;
}
if (!PojoEndpointServer.class.isAssignableFrom(sec.getEndpointClass())) {
// Need to make path params available to POJO
sec.getUserProperties().put(
PojoEndpointServer.POJO_PATH_PARAM_KEY,
pathParams);
}
return new WsMappingResult(sec, pathParams);
}
public boolean isEnforceNoAddAfterHandshake() {
return enforceNoAddAfterHandshake;
}
public void setEnforceNoAddAfterHandshake(
boolean enforceNoAddAfterHandshake) {
this.enforceNoAddAfterHandshake = enforceNoAddAfterHandshake;
}
protected WsWriteTimeout getTimeout() {
return wsWriteTimeout;
}
/**
* {@inheritDoc}
*
* Overridden to make it visible to other classes in this package.
*/
@Override
protected void registerSession(Endpoint endpoint, WsSession wsSession) {
super.registerSession(endpoint, wsSession);
if (wsSession.getUserPrincipal() != null &&
wsSession.getHttpSessionId() != null) {
registerAuthenticatedSession(wsSession,
wsSession.getHttpSessionId());
}
}
/**
* {@inheritDoc}
*
* Overridden to make it visible to other classes in this package.
*/
@Override
protected void unregisterSession(Endpoint endpoint, WsSession wsSession) {
if (wsSession.getUserPrincipal() != null &&
wsSession.getHttpSessionId() != null) {
unregisterAuthenticatedSession(wsSession,
wsSession.getHttpSessionId());
}
super.unregisterSession(endpoint, wsSession);
}
private void registerAuthenticatedSession(WsSession wsSession,
String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
if (wsSessions == null) {
wsSessions = Collections.newSetFromMap(
new ConcurrentHashMap<WsSession,Boolean>());
authenticatedSessions.putIfAbsent(httpSessionId, wsSessions);
wsSessions = authenticatedSessions.get(httpSessionId);
}
wsSessions.add(wsSession);
}
private void unregisterAuthenticatedSession(WsSession wsSession,
String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
wsSessions.remove(wsSession);
}
public void closeAuthenticatedSession(String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.remove(httpSessionId);
if (wsSessions != null && !wsSessions.isEmpty()) {
for (WsSession wsSession : wsSessions) {
try {
wsSession.close(AUTHENTICATED_HTTP_SESSION_CLOSED);
} catch (IOException e) {
// Any IOExceptions during close will have been caught and the
// onError method called.
}
}
}
}
private static void validateEncoders(Class<? extends Encoder>[] encoders)
throws DeploymentException {
for (Class<? extends Encoder> encoder : encoders) {
// Need to instantiate decoder to ensure it is valid and that
// deployment can be failed if it is not
@SuppressWarnings("unused")
Encoder instance;
try {
encoder.newInstance();
} catch(InstantiationException | IllegalAccessException e) {
throw new DeploymentException(sm.getString(
"serverContainer.encoderFail", encoder.getName()), e);
}
}
}
private static class TemplatePathMatch {
private final ServerEndpointConfig config;
private final UriTemplate uriTemplate;
public TemplatePathMatch(ServerEndpointConfig config,
UriTemplate uriTemplate) {
this.config = config;
this.uriTemplate = uriTemplate;
}
public ServerEndpointConfig getConfig() {
return config;
}
public UriTemplate getUriTemplate() {
return uriTemplate;
}
}
/**
* This Comparator implementation is thread-safe so only create a single
* instance.
*/
private static class TemplatePathMatchComparator
implements Comparator<TemplatePathMatch> {
private static final TemplatePathMatchComparator INSTANCE =
new TemplatePathMatchComparator();
public static TemplatePathMatchComparator getInstance() {
return INSTANCE;
}
private TemplatePathMatchComparator() {
// Hide default constructor
}
@Override
public int compare(TemplatePathMatch tpm1, TemplatePathMatch tpm2) {
return tpm1.getUriTemplate().getNormalizedPath().compareTo(
tpm2.getUriTemplate().getNormalizedPath());
}
}
}
|
55,357
|
Bug 55357 Cannot deserialize session when it contains Externalizable objects (using PersistentManager)
|
I'm using PersistentManager with JDBCStore to store sessions in my database. But in my webapplication, there is an object in my session which is an instance of org.apache.el.MethodExpressionImpl. This class implements the Externalizable interface but in this readExternal method it uses org.apache.el.util.ReflectionUtil.forName(String) which use Thread.currentThread().getContextClassLoader() as its ClassLoader. It seems to be incorrect because this method return a StandardClassLoader which cannot find my classes in WEB-INF/lib directory of my webapp. Is it the problem of the MethodExpressionImpl class which use this method or the JDBCStore which does not set the thread contextClassLoader as the WebappClassLoader ? Here is the stacktrace : SEVERE: Error processing request java.lang.IllegalStateException: Erreur lors de la deserialisation de la session 1634C328D27A31CB9FC4D52392FDB05F: {1} at org.apache.catalina.session.PersistentManagerBase.swapIn(PersistentManagerBase.java:713) at org.apache.catalina.session.PersistentManagerBase.findSession(PersistentManagerBase.java:503) at org.apache.catalina.connector.Request.isRequestedSessionIdValid(Request.java:2391) at org.apache.catalina.connector.CoyoteAdapter.parseSessionCookiesId(CoyoteAdapter.java:954) at org.apache.catalina.connector.CoyoteAdapter.postParseRequest(CoyoteAdapter.java:688) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:402) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.ClassNotFoundException: javax.faces.event.ActionEvent at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:266) at org.apache.el.util.ReflectionUtil.forName(ReflectionUtil.java:62) at org.apache.el.util.ReflectionUtil.toTypeArray(ReflectionUtil.java:88) at org.apache.el.MethodExpressionImpl.readExternal(MethodExpressionImpl.java:290) at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1835) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1794) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at com.sun.facelets.el.TagMethodExpression.readExternal(TagMethodExpression.java:101) at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1835) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1794) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1989) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1913) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at java.util.ArrayList.readObject(ArrayList.java:733) at sun.reflect.GeneratedMethodAccessor90.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1989) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1913) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at java.util.HashMap.readObject(HashMap.java:1155) at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at java.util.HashMap.readObject(HashMap.java:1155) at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1989) at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:499) at org.ajax4jsf.application.AjaxStateHolder.readObject(AjaxStateHolder.java:204) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1595) at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1060) at org.apache.catalina.session.JDBCStore.load(JDBCStore.java:657) at org.apache.catalina.session.PersistentManagerBase.swapIn(PersistentManagerBase.java:707) ... 11 more
|
resolved fixed
|
e19e794
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-15T14:06:20Z
| 2013-08-05T19:13:20Z
|
java/org/apache/catalina/session/FileStore.java
|
/*
* 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.session;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import org.apache.catalina.Context;
import org.apache.catalina.Loader;
import org.apache.catalina.Session;
import org.apache.catalina.util.CustomObjectInputStream;
/**
* Concrete implementation of the <b>Store</b> interface that utilizes
* a file per saved Session in a configured directory. Sessions that are
* saved are still subject to being expired based on inactivity.
*
* @author Craig R. McClanahan
* @version $Id$
*/
public final class FileStore extends StoreBase {
// ----------------------------------------------------- Constants
/**
* The extension to use for serialized session filenames.
*/
private static final String FILE_EXT = ".session";
// ----------------------------------------------------- Instance Variables
/**
* The pathname of the directory in which Sessions are stored.
* This may be an absolute pathname, or a relative path that is
* resolved against the temporary work directory for this application.
*/
private String directory = ".";
/**
* A File representing the directory in which Sessions are stored.
*/
private File directoryFile = null;
/**
* Name to register for this Store, used for logging.
*/
private static final String storeName = "fileStore";
/**
* Name to register for the background thread.
*/
private static final String threadName = "FileStore";
// ------------------------------------------------------------- Properties
/**
* Return the directory path for this Store.
*/
public String getDirectory() {
return (directory);
}
/**
* Set the directory path for this Store.
*
* @param path The new directory path
*/
public void setDirectory(String path) {
String oldDirectory = this.directory;
this.directory = path;
this.directoryFile = null;
support.firePropertyChange("directory", oldDirectory,
this.directory);
}
/**
* Return the thread name for this Store.
*/
public String getThreadName() {
return(threadName);
}
/**
* Return the name for this Store, used for logging.
*/
@Override
public String getStoreName() {
return(storeName);
}
/**
* Return the number of Sessions present in this Store.
*
* @exception IOException if an input/output error occurs
*/
@Override
public int getSize() throws IOException {
// Acquire the list of files in our storage directory
File file = directory();
if (file == null) {
return (0);
}
String files[] = file.list();
// Figure out which files are sessions
int keycount = 0;
for (int i = 0; i < files.length; i++) {
if (files[i].endsWith(FILE_EXT)) {
keycount++;
}
}
return (keycount);
}
// --------------------------------------------------------- Public Methods
/**
* Remove all of the Sessions in this Store.
*
* @exception IOException if an input/output error occurs
*/
@Override
public void clear()
throws IOException {
String[] keys = keys();
for (int i = 0; i < keys.length; i++) {
remove(keys[i]);
}
}
/**
* Return an array containing the session identifiers of all Sessions
* currently saved in this Store. If there are no such Sessions, a
* zero-length array is returned.
*
* @exception IOException if an input/output error occurred
*/
@Override
public String[] keys() throws IOException {
// Acquire the list of files in our storage directory
File file = directory();
if (file == null) {
return (new String[0]);
}
String files[] = file.list();
// Bugzilla 32130
if((files == null) || (files.length < 1)) {
return (new String[0]);
}
// Build and return the list of session identifiers
ArrayList<String> list = new ArrayList<>();
int n = FILE_EXT.length();
for (int i = 0; i < files.length; i++) {
if (files[i].endsWith(FILE_EXT)) {
list.add(files[i].substring(0, files[i].length() - n));
}
}
return list.toArray(new String[list.size()]);
}
/**
* Load and return the Session associated with the specified session
* identifier from this Store, without removing it. If there is no
* such stored Session, return <code>null</code>.
*
* @param id Session identifier of the session to load
*
* @exception ClassNotFoundException if a deserialization error occurs
* @exception IOException if an input/output error occurs
*/
@Override
public Session load(String id)
throws ClassNotFoundException, IOException {
// Open an input stream to the specified pathname, if any
File file = file(id);
if (file == null) {
return (null);
}
if (! file.exists()) {
return (null);
}
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(sm.getString(getStoreName()+".loading",
id, file.getAbsolutePath()));
}
FileInputStream fis = null;
BufferedInputStream bis = null;
ObjectInputStream ois = null;
Loader loader = null;
ClassLoader classLoader = null;
try {
fis = new FileInputStream(file.getAbsolutePath());
bis = new BufferedInputStream(fis);
Context context = manager.getContext();
if (context != null)
loader = context.getLoader();
if (loader != null)
classLoader = loader.getClassLoader();
if (classLoader != null)
ois = new CustomObjectInputStream(bis, classLoader);
else
ois = new ObjectInputStream(bis);
} catch (FileNotFoundException e) {
if (manager.getContext().getLogger().isDebugEnabled())
manager.getContext().getLogger().debug("No persisted data file found");
return (null);
} catch (IOException e) {
if (bis != null) {
try {
bis.close();
} catch (IOException f) {
// Ignore
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException f) {
// Ignore
}
}
throw e;
}
try {
StandardSession session =
(StandardSession) manager.createEmptySession();
session.readObjectData(ois);
session.setManager(manager);
return (session);
} finally {
// Close the input stream
try {
ois.close();
} catch (IOException f) {
// Ignore
}
}
}
/**
* Remove the Session with the specified session identifier from
* this Store, if present. If no such Session is present, this method
* takes no action.
*
* @param id Session identifier of the Session to be removed
*
* @exception IOException if an input/output error occurs
*/
@Override
public void remove(String id) throws IOException {
File file = file(id);
if (file == null) {
return;
}
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(sm.getString(getStoreName()+".removing",
id, file.getAbsolutePath()));
}
file.delete();
}
/**
* Save the specified Session into this Store. Any previously saved
* information for the associated session identifier is replaced.
*
* @param session Session to be saved
*
* @exception IOException if an input/output error occurs
*/
@Override
public void save(Session session) throws IOException {
// Open an output stream to the specified pathname, if any
File file = file(session.getIdInternal());
if (file == null) {
return;
}
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(sm.getString(getStoreName()+".saving",
session.getIdInternal(), file.getAbsolutePath()));
}
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(file.getAbsolutePath());
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
} catch (IOException e) {
if (fos != null) {
try {
fos.close();
} catch (IOException f) {
// Ignore
}
}
throw e;
}
try {
((StandardSession)session).writeObjectData(oos);
} finally {
oos.close();
}
}
// -------------------------------------------------------- Private Methods
/**
* Return a File object representing the pathname to our
* session persistence directory, if any. The directory will be
* created if it does not already exist.
*/
private File directory() throws IOException {
if (this.directory == null) {
return (null);
}
if (this.directoryFile != null) {
// NOTE: Race condition is harmless, so do not synchronize
return (this.directoryFile);
}
File file = new File(this.directory);
if (!file.isAbsolute()) {
Context context = manager.getContext();
if (context != null) {
ServletContext servletContext = context.getServletContext();
File work = (File)
servletContext.getAttribute(ServletContext.TEMPDIR);
file = new File(work, this.directory);
} else {
throw new IllegalArgumentException
("Parent Container is not a Context");
}
}
if (!file.exists() || !file.isDirectory()) {
if (!file.delete() && file.exists()) {
throw new IOException(
sm.getString("fileStore.deleteFailed", file));
}
if (!file.mkdirs() && !file.isDirectory()) {
throw new IOException(
sm.getString("fileStore.createFailed", file));
}
}
this.directoryFile = file;
return (file);
}
/**
* Return a File object representing the pathname to our
* session persistence file, if any.
*
* @param id The ID of the Session to be retrieved. This is
* used in the file naming.
*/
private File file(String id) throws IOException {
if (this.directory == null) {
return (null);
}
String filename = id + FILE_EXT;
File file = new File(directory(), filename);
return (file);
}
}
|
55,357
|
Bug 55357 Cannot deserialize session when it contains Externalizable objects (using PersistentManager)
|
I'm using PersistentManager with JDBCStore to store sessions in my database. But in my webapplication, there is an object in my session which is an instance of org.apache.el.MethodExpressionImpl. This class implements the Externalizable interface but in this readExternal method it uses org.apache.el.util.ReflectionUtil.forName(String) which use Thread.currentThread().getContextClassLoader() as its ClassLoader. It seems to be incorrect because this method return a StandardClassLoader which cannot find my classes in WEB-INF/lib directory of my webapp. Is it the problem of the MethodExpressionImpl class which use this method or the JDBCStore which does not set the thread contextClassLoader as the WebappClassLoader ? Here is the stacktrace : SEVERE: Error processing request java.lang.IllegalStateException: Erreur lors de la deserialisation de la session 1634C328D27A31CB9FC4D52392FDB05F: {1} at org.apache.catalina.session.PersistentManagerBase.swapIn(PersistentManagerBase.java:713) at org.apache.catalina.session.PersistentManagerBase.findSession(PersistentManagerBase.java:503) at org.apache.catalina.connector.Request.isRequestedSessionIdValid(Request.java:2391) at org.apache.catalina.connector.CoyoteAdapter.parseSessionCookiesId(CoyoteAdapter.java:954) at org.apache.catalina.connector.CoyoteAdapter.postParseRequest(CoyoteAdapter.java:688) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:402) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.ClassNotFoundException: javax.faces.event.ActionEvent at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:266) at org.apache.el.util.ReflectionUtil.forName(ReflectionUtil.java:62) at org.apache.el.util.ReflectionUtil.toTypeArray(ReflectionUtil.java:88) at org.apache.el.MethodExpressionImpl.readExternal(MethodExpressionImpl.java:290) at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1835) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1794) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at com.sun.facelets.el.TagMethodExpression.readExternal(TagMethodExpression.java:101) at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1835) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1794) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1989) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1913) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at java.util.ArrayList.readObject(ArrayList.java:733) at sun.reflect.GeneratedMethodAccessor90.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1704) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1342) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1989) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1913) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at java.util.HashMap.readObject(HashMap.java:1155) at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at java.util.HashMap.readObject(HashMap.java:1155) at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1989) at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:499) at org.ajax4jsf.application.AjaxStateHolder.readObject(AjaxStateHolder.java:204) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1595) at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:1060) at org.apache.catalina.session.JDBCStore.load(JDBCStore.java:657) at org.apache.catalina.session.PersistentManagerBase.swapIn(PersistentManagerBase.java:707) ... 11 more
|
resolved fixed
|
e19e794
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-15T14:06:20Z
| 2013-08-05T19:13:20Z
|
java/org/apache/catalina/session/JDBCStore.java
|
/*
* 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.session;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
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 javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Loader;
import org.apache.catalina.Session;
import org.apache.catalina.util.CustomObjectInputStream;
import org.apache.tomcat.util.ExceptionUtils;
/**
* Implementation of the <code>Store</code> interface that stores
* serialized session objects in a database. Sessions that are
* saved are still subject to being expired based on inactivity.
*
* @author Bip Thelin
* @version $Id$
*/
public class JDBCStore extends StoreBase {
/**
* Context name associated with this Store
*/
private String name = null;
/**
* Name to register for this Store, used for logging.
*/
protected static final String storeName = "JDBCStore";
/**
* Name to register for the background thread.
*/
protected final String threadName = "JDBCStore";
/**
* 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;
/**
* Connection string to use when connecting to the DB.
*/
protected String connectionURL = null;
/**
* The database connection.
*/
private Connection dbConnection = null;
/**
* Instance of the JDBC Driver class we use as a connection factory.
*/
protected Driver driver = null;
/**
* Driver to use.
*/
protected String driverName = null;
/**
* name of the JNDI resource
*/
protected String dataSourceName = null;
/**
* DataSource to use
*/
protected DataSource dataSource = null;
// ------------------------------------------------------------- Table & cols
/**
* Table to use.
*/
protected String sessionTable = "tomcat$sessions";
/**
* Column to use for /Engine/Host/Context name
*/
protected String sessionAppCol = "app";
/**
* Id column to use.
*/
protected String sessionIdCol = "id";
/**
* Data column to use.
*/
protected String sessionDataCol = "data";
/**
* Is Valid column to use.
*/
protected String sessionValidCol = "valid";
/**
* Max Inactive column to use.
*/
protected String sessionMaxInactiveCol = "maxinactive";
/**
* Last Accessed column to use.
*/
protected String sessionLastAccessedCol = "lastaccess";
// ------------------------------------------------------------- SQL Variables
/**
* Variable to hold the <code>getSize()</code> prepared statement.
*/
protected PreparedStatement preparedSizeSql = null;
/**
* Variable to hold the <code>keys()</code> prepared statement.
*/
protected PreparedStatement preparedKeysSql = null;
/**
* Variable to hold the <code>save()</code> prepared statement.
*/
protected PreparedStatement preparedSaveSql = null;
/**
* Variable to hold the <code>clear()</code> prepared statement.
*/
protected PreparedStatement preparedClearSql = null;
/**
* Variable to hold the <code>remove()</code> prepared statement.
*/
protected PreparedStatement preparedRemoveSql = null;
/**
* Variable to hold the <code>load()</code> prepared statement.
*/
protected PreparedStatement preparedLoadSql = null;
// ------------------------------------------------------------- Properties
/**
* Return the name for this instance (built from container name)
*/
public String getName() {
if (name == null) {
Container container = manager.getContext();
String contextName = container.getName();
if (!contextName.startsWith("/")) {
contextName = "/" + contextName;
}
String hostName = "";
String engineName = "";
if (container.getParent() != null) {
Container host = container.getParent();
hostName = host.getName();
if (host.getParent() != null) {
engineName = host.getParent().getName();
}
}
name = "/" + engineName + "/" + hostName + contextName;
}
return name;
}
/**
* Return the thread name for this Store.
*/
public String getThreadName() {
return (threadName);
}
/**
* Return the name for this Store, used for logging.
*/
@Override
public String getStoreName() {
return (storeName);
}
/**
* Set the driver for this Store.
*
* @param driverName The new driver
*/
public void setDriverName(String driverName) {
String oldDriverName = this.driverName;
this.driverName = driverName;
support.firePropertyChange("driverName",
oldDriverName,
this.driverName);
this.driverName = driverName;
}
/**
* Return the driver for this Store.
*/
public String getDriverName() {
return (this.driverName);
}
/**
* 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;
}
/**
* Set the Connection URL for this Store.
*
* @param connectionURL The new Connection URL
*/
public void setConnectionURL(String connectionURL) {
String oldConnString = this.connectionURL;
this.connectionURL = connectionURL;
support.firePropertyChange("connectionURL",
oldConnString,
this.connectionURL);
}
/**
* Return the Connection URL for this Store.
*/
public String getConnectionURL() {
return (this.connectionURL);
}
/**
* Set the table for this Store.
*
* @param sessionTable The new table
*/
public void setSessionTable(String sessionTable) {
String oldSessionTable = this.sessionTable;
this.sessionTable = sessionTable;
support.firePropertyChange("sessionTable",
oldSessionTable,
this.sessionTable);
}
/**
* Return the table for this Store.
*/
public String getSessionTable() {
return (this.sessionTable);
}
/**
* Set the App column for the table.
*
* @param sessionAppCol the column name
*/
public void setSessionAppCol(String sessionAppCol) {
String oldSessionAppCol = this.sessionAppCol;
this.sessionAppCol = sessionAppCol;
support.firePropertyChange("sessionAppCol",
oldSessionAppCol,
this.sessionAppCol);
}
/**
* Return the web application name column for the table.
*/
public String getSessionAppCol() {
return (this.sessionAppCol);
}
/**
* Set the Id column for the table.
*
* @param sessionIdCol the column name
*/
public void setSessionIdCol(String sessionIdCol) {
String oldSessionIdCol = this.sessionIdCol;
this.sessionIdCol = sessionIdCol;
support.firePropertyChange("sessionIdCol",
oldSessionIdCol,
this.sessionIdCol);
}
/**
* Return the Id column for the table.
*/
public String getSessionIdCol() {
return (this.sessionIdCol);
}
/**
* Set the Data column for the table
*
* @param sessionDataCol the column name
*/
public void setSessionDataCol(String sessionDataCol) {
String oldSessionDataCol = this.sessionDataCol;
this.sessionDataCol = sessionDataCol;
support.firePropertyChange("sessionDataCol",
oldSessionDataCol,
this.sessionDataCol);
}
/**
* Return the data column for the table
*/
public String getSessionDataCol() {
return (this.sessionDataCol);
}
/**
* Set the Is Valid column for the table
*
* @param sessionValidCol The column name
*/
public void setSessionValidCol(String sessionValidCol) {
String oldSessionValidCol = this.sessionValidCol;
this.sessionValidCol = sessionValidCol;
support.firePropertyChange("sessionValidCol",
oldSessionValidCol,
this.sessionValidCol);
}
/**
* Return the Is Valid column
*/
public String getSessionValidCol() {
return (this.sessionValidCol);
}
/**
* Set the Max Inactive column for the table
*
* @param sessionMaxInactiveCol The column name
*/
public void setSessionMaxInactiveCol(String sessionMaxInactiveCol) {
String oldSessionMaxInactiveCol = this.sessionMaxInactiveCol;
this.sessionMaxInactiveCol = sessionMaxInactiveCol;
support.firePropertyChange("sessionMaxInactiveCol",
oldSessionMaxInactiveCol,
this.sessionMaxInactiveCol);
}
/**
* Return the Max Inactive column
*/
public String getSessionMaxInactiveCol() {
return (this.sessionMaxInactiveCol);
}
/**
* Set the Last Accessed column for the table
*
* @param sessionLastAccessedCol The column name
*/
public void setSessionLastAccessedCol(String sessionLastAccessedCol) {
String oldSessionLastAccessedCol = this.sessionLastAccessedCol;
this.sessionLastAccessedCol = sessionLastAccessedCol;
support.firePropertyChange("sessionLastAccessedCol",
oldSessionLastAccessedCol,
this.sessionLastAccessedCol);
}
/**
* Return the Last Accessed column
*/
public String getSessionLastAccessedCol() {
return (this.sessionLastAccessedCol);
}
/**
* Set the JNDI name of a DataSource-factory to use for db access
*
* @param dataSourceName The JNDI name of the DataSource-factory
*/
public void setDataSourceName(String dataSourceName) {
if (dataSourceName == null || "".equals(dataSourceName.trim())) {
manager.getContext().getLogger().warn(
sm.getString(getStoreName() + ".missingDataSourceName"));
return;
}
this.dataSourceName = dataSourceName;
}
/**
* Return the name of the JNDI DataSource-factory
*/
public String getDataSourceName() {
return this.dataSourceName;
}
// --------------------------------------------------------- Public Methods
/**
* Return an array containing the session identifiers of all Sessions
* currently saved in this Store. If there are no such Sessions, a
* zero-length array is returned.
*
* @exception IOException if an input/output error occurred
*/
@Override
public String[] keys() throws IOException {
ResultSet rst = null;
String keys[] = null;
synchronized (this) {
int numberOfTries = 2;
while (numberOfTries > 0) {
Connection _conn = getConnection();
if (_conn == null) {
return (new String[0]);
}
try {
if (preparedKeysSql == null) {
String keysSql = "SELECT " + sessionIdCol + " FROM "
+ sessionTable + " WHERE " + sessionAppCol
+ " = ?";
preparedKeysSql = _conn.prepareStatement(keysSql);
}
preparedKeysSql.setString(1, getName());
rst = preparedKeysSql.executeQuery();
ArrayList<String> tmpkeys = new ArrayList<>();
if (rst != null) {
while (rst.next()) {
tmpkeys.add(rst.getString(1));
}
}
keys = tmpkeys.toArray(new String[tmpkeys.size()]);
// Break out after the finally block
numberOfTries = 0;
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
keys = new String[0];
// Close the connection so that it gets reopened next time
if (dbConnection != null)
close(dbConnection);
} finally {
try {
if (rst != null) {
rst.close();
}
} catch (SQLException e) {
// Ignore
}
release(_conn);
}
numberOfTries--;
}
}
return (keys);
}
/**
* Return an integer containing a count of all Sessions
* currently saved in this Store. If there are no Sessions,
* <code>0</code> is returned.
*
* @exception IOException if an input/output error occurred
*/
@Override
public int getSize() throws IOException {
int size = 0;
ResultSet rst = null;
synchronized (this) {
int numberOfTries = 2;
while (numberOfTries > 0) {
Connection _conn = getConnection();
if (_conn == null) {
return (size);
}
try {
if (preparedSizeSql == null) {
String sizeSql = "SELECT COUNT(" + sessionIdCol
+ ") FROM " + sessionTable + " WHERE "
+ sessionAppCol + " = ?";
preparedSizeSql = _conn.prepareStatement(sizeSql);
}
preparedSizeSql.setString(1, getName());
rst = preparedSizeSql.executeQuery();
if (rst.next()) {
size = rst.getInt(1);
}
// Break out after the finally block
numberOfTries = 0;
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
if (dbConnection != null)
close(dbConnection);
} finally {
try {
if (rst != null)
rst.close();
} catch (SQLException e) {
// Ignore
}
release(_conn);
}
numberOfTries--;
}
}
return (size);
}
/**
* Load the Session associated with the id <code>id</code>.
* If no such session is found <code>null</code> is returned.
*
* @param id a value of type <code>String</code>
* @return the stored <code>Session</code>
* @exception ClassNotFoundException if an error occurs
* @exception IOException if an input/output error occurred
*/
@Override
public Session load(String id)
throws ClassNotFoundException, IOException {
ResultSet rst = null;
StandardSession _session = null;
Loader loader = null;
ClassLoader classLoader = null;
ObjectInputStream ois = null;
BufferedInputStream bis = null;
org.apache.catalina.Context context = manager.getContext();
synchronized (this) {
int numberOfTries = 2;
while (numberOfTries > 0) {
Connection _conn = getConnection();
if (_conn == null) {
return (null);
}
try {
if (preparedLoadSql == null) {
String loadSql = "SELECT " + sessionIdCol + ", "
+ sessionDataCol + " FROM " + sessionTable
+ " WHERE " + sessionIdCol + " = ? AND "
+ sessionAppCol + " = ?";
preparedLoadSql = _conn.prepareStatement(loadSql);
}
preparedLoadSql.setString(1, id);
preparedLoadSql.setString(2, getName());
rst = preparedLoadSql.executeQuery();
if (rst.next()) {
bis = new BufferedInputStream(rst.getBinaryStream(2));
if (context != null) {
loader = context.getLoader();
}
if (loader != null) {
classLoader = loader.getClassLoader();
}
if (classLoader != null) {
ois = new CustomObjectInputStream(bis,
classLoader);
} else {
ois = new ObjectInputStream(bis);
}
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(sm.getString(getStoreName() + ".loading",
id, sessionTable));
}
_session = (StandardSession) manager.createEmptySession();
_session.readObjectData(ois);
_session.setManager(manager);
} else if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(getStoreName() + ": No persisted data object found");
}
// Break out after the finally block
numberOfTries = 0;
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
if (dbConnection != null)
close(dbConnection);
} finally {
try {
if (rst != null) {
rst.close();
}
} catch (SQLException e) {
// Ignore
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
// Ignore
}
}
release(_conn);
}
numberOfTries--;
}
}
return (_session);
}
/**
* Remove the Session with the specified session identifier from
* this Store, if present. If no such Session is present, this method
* takes no action.
*
* @param id Session identifier of the Session to be removed
*
* @exception IOException if an input/output error occurs
*/
@Override
public void remove(String id) throws IOException {
synchronized (this) {
int numberOfTries = 2;
while (numberOfTries > 0) {
Connection _conn = getConnection();
if (_conn == null) {
return;
}
try {
remove(id, _conn);
// Break out after the finally block
numberOfTries = 0;
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
if (dbConnection != null)
close(dbConnection);
} finally {
release(_conn);
}
numberOfTries--;
}
}
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(sm.getString(getStoreName() + ".removing", id, sessionTable));
}
}
/**
* Remove the Session with the specified session identifier from
* this Store, if present. If no such Session is present, this method
* takes no action.
*
* @param id Session identifier of the Session to be removed
* @param _conn open connection to be used
* @throws SQLException if an error occurs while talking to the database
*/
private void remove(String id, Connection _conn) throws SQLException {
if (preparedRemoveSql == null) {
String removeSql = "DELETE FROM " + sessionTable
+ " WHERE " + sessionIdCol + " = ? AND "
+ sessionAppCol + " = ?";
preparedRemoveSql = _conn.prepareStatement(removeSql);
}
preparedRemoveSql.setString(1, id);
preparedRemoveSql.setString(2, getName());
preparedRemoveSql.execute();
}
/**
* Remove all of the Sessions in this Store.
*
* @exception IOException if an input/output error occurs
*/
@Override
public void clear() throws IOException {
synchronized (this) {
int numberOfTries = 2;
while (numberOfTries > 0) {
Connection _conn = getConnection();
if (_conn == null) {
return;
}
try {
if (preparedClearSql == null) {
String clearSql = "DELETE FROM " + sessionTable
+ " WHERE " + sessionAppCol + " = ?";
preparedClearSql = _conn.prepareStatement(clearSql);
}
preparedClearSql.setString(1, getName());
preparedClearSql.execute();
// Break out after the finally block
numberOfTries = 0;
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
if (dbConnection != null)
close(dbConnection);
} finally {
release(_conn);
}
numberOfTries--;
}
}
}
/**
* Save a session to the Store.
*
* @param session the session to be stored
* @exception IOException if an input/output error occurs
*/
@Override
public void save(Session session) throws IOException {
ObjectOutputStream oos = null;
ByteArrayOutputStream bos = null;
ByteArrayInputStream bis = null;
InputStream in = null;
synchronized (this) {
int numberOfTries = 2;
while (numberOfTries > 0) {
Connection _conn = getConnection();
if (_conn == null) {
return;
}
try {
// If sessions already exist in DB, remove and insert again.
// TODO:
// * Check if ID exists in database and if so use UPDATE.
remove(session.getIdInternal(), _conn);
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(new BufferedOutputStream(bos));
((StandardSession) session).writeObjectData(oos);
oos.close();
oos = null;
byte[] obs = bos.toByteArray();
int size = obs.length;
bis = new ByteArrayInputStream(obs, 0, size);
in = new BufferedInputStream(bis, size);
if (preparedSaveSql == null) {
String saveSql = "INSERT INTO " + sessionTable + " ("
+ sessionIdCol + ", " + sessionAppCol + ", "
+ sessionDataCol + ", " + sessionValidCol
+ ", " + sessionMaxInactiveCol + ", "
+ sessionLastAccessedCol
+ ") VALUES (?, ?, ?, ?, ?, ?)";
preparedSaveSql = _conn.prepareStatement(saveSql);
}
preparedSaveSql.setString(1, session.getIdInternal());
preparedSaveSql.setString(2, getName());
preparedSaveSql.setBinaryStream(3, in, size);
preparedSaveSql.setString(4, session.isValid() ? "1" : "0");
preparedSaveSql.setInt(5, session.getMaxInactiveInterval());
preparedSaveSql.setLong(6, session.getLastAccessedTime());
preparedSaveSql.execute();
// Break out after the finally block
numberOfTries = 0;
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".SQLException", e));
if (dbConnection != null)
close(dbConnection);
} catch (IOException e) {
// Ignore
} finally {
if (oos != null) {
oos.close();
}
if (bis != null) {
bis.close();
}
if (in != null) {
in.close();
}
release(_conn);
}
numberOfTries--;
}
}
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(sm.getString(getStoreName() + ".saving",
session.getIdInternal(), sessionTable));
}
}
// --------------------------------------------------------- Protected Methods
/**
* Check the connection associated with this store, if it's
* <code>null</code> or closed try to reopen it.
* Returns <code>null</code> if the connection could not be established.
*
* @return <code>Connection</code> if the connection succeeded
*/
protected Connection getConnection() {
Connection conn = null;
try {
conn = open();
if (conn == null || conn.isClosed()) {
manager.getContext().getLogger().info(sm.getString(getStoreName() + ".checkConnectionDBClosed"));
conn = open();
if (conn == null || conn.isClosed()) {
manager.getContext().getLogger().info(sm.getString(getStoreName() + ".checkConnectionDBReOpenFail"));
}
}
} catch (SQLException ex) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException",
ex.toString()));
}
return conn;
}
/**
* 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);
if (dataSourceName != null && dataSource == null) {
Context initCtx;
try {
initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
this.dataSource = (DataSource) envCtx.lookup(this.dataSourceName);
} catch (NamingException e) {
manager.getContext().getLogger().error(
sm.getString(getStoreName() + ".wrongDataSource",
this.dataSourceName), e);
}
}
if (dataSource != null) {
return dataSource.getConnection();
}
// Instantiate our database driver if necessary
if (driver == null) {
try {
Class<?> clazz = Class.forName(driverName);
driver = (Driver) clazz.newInstance();
} catch (ClassNotFoundException ex) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException",
ex.toString()));
} catch (InstantiationException ex) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException",
ex.toString()));
} catch (IllegalAccessException ex) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".checkConnectionClassNotFoundException",
ex.toString()));
}
}
// 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);
dbConnection.setAutoCommit(true);
return (dbConnection);
}
/**
* 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 {
preparedSizeSql.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
this.preparedSizeSql = null;
try {
preparedKeysSql.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
this.preparedKeysSql = null;
try {
preparedSaveSql.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
this.preparedSaveSql = null;
try {
preparedClearSql.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
try {
preparedRemoveSql.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
this.preparedRemoveSql = null;
try {
preparedLoadSql.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
this.preparedLoadSql = null;
// Commit if autoCommit is false
try {
if (!dbConnection.getAutoCommit()) {
dbConnection.commit();
}
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".commitSQLException"), e);
}
// Close this database connection, and log any errors
try {
dbConnection.close();
} catch (SQLException e) {
manager.getContext().getLogger().error(sm.getString(getStoreName() + ".close", e.toString())); // Just log it here
} finally {
this.dbConnection = null;
}
}
/**
* Release the connection, if it
* is associated with a connection pool.
*
* @param conn The connection to be released
*/
protected void release(Connection conn) {
if (dataSource != null) {
close(conn);
}
}
/**
* Start this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void startInternal() throws LifecycleException {
if (dataSourceName == null) {
// If not using a connection pool, open a connection to the database
this.dbConnection = getConnection();
}
super.startInternal();
}
/**
* Stop this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void stopInternal() throws LifecycleException {
super.stopInternal();
// Close and release everything associated with our db.
if (dbConnection != null) {
try {
dbConnection.commit();
} catch (SQLException e) {
// Ignore
}
close(dbConnection);
}
}
}
|
55,354
|
Bug 55354 JNDIRealm.getPrincipal(context,username,gssCredential) corrupts realm context
|
The getPrincipal(context,username,gssCredential) method in JNDIRealm is designed to allow delegated credentials to be applied to the directory server connection as part of SPNEGO authentication. This is done by manipulation of a number of the directory context's environment parameters. However, as currently implemented, these environment parameters are forcibly cleared after the getUser() call regardless of whether the values were even changed (i.e. if isUseDelegatedCredential() returned false). If the container realm is defined to use GSSAPI authentication, only the first SPNEGO authentication request will succeed. All subsequent requests will fail with this exception: javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0906DC, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db0 The exception is due to the Context.SECURITY_AUTHENTICATION being cleared by getPrincipal() - resulting in a attempted "simple" bind with no username/password (i.e. anonymous). A workaround is to ensure that the connectionName and connectionPassword parameters are specified in the realm definition - however, if one is using GSSAPI - this shouldn't be necessary and certainly defeats the purpose of using GSSAPI in the first place. The code should preserve pre-existing environment parameters in the context before changing them, then restore those values afterwards - rather than just clearing the settings completely.
|
resolved fixed
|
135e2c4
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-15T20:31:48Z
| 2013-08-05T08:06:40Z
|
java/org/apache/catalina/realm/JNDIRealm.java
|
/*
* 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.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
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.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.tomcat.util.codec.binary.Base64;
import org.ietf.jgss.GSSCredential;
/**
* <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, and/or "{2}" the value of an attribute from the
* user's directory entry (the attribute is specified by the
* <code>userRoleAttribute</code> property), 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 $Id$
*/
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 static final String DEREF_ALIASES = "java.naming.ldap.derefAliases";
/**
* 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;
/**
* The name of the attribute inside the users
* directory entry where the value will be
* taken to search for roles
* This attribute is not used during a nested search
*/
protected String userRoleAttribute = 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>roleBase</code>.
*/
protected MessageFormat roleBaseFormat = null;
/**
* 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. The "{1}"
* and "{2}" are described in the Configuration Reference.
*/
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;
/**
* When searching for user roles, should the search be performed as the user
* currently being authenticated? If false, {@link #connectionName} and
* {@link #connectionPassword} will be used if specified, else an anonymous
* connection will be used.
*/
protected boolean roleSearchAsUser = 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";
/**
* The sizeLimit (also known as the countLimit) to use when the realm is
* configured with {@link #userSearch}. Zero for no limit.
*/
protected long sizeLimit = 0;
/**
* The timeLimit (in milliseconds) to use when the realm is configured with
* {@link #userSearch}. Zero for no limit.
*/
protected int timeLimit = 0;
/**
* Should delegated credentials from the SPNEGO authenticator be used if
* available
*/
protected boolean useDelegatedCredential = true;
// ------------------------------------------------------------- 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 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;
if (roleBase == null)
roleBaseFormat = null;
else
roleBaseFormat = new MessageFormat(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);
}
public boolean isRoleSearchAsUser() {
return roleSearchAsUser;
}
public void setRoleSearchAsUser(boolean roleSearchAsUser) {
this.roleSearchAsUser = roleSearchAsUser;
}
/**
* 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;
}
public String getUserRoleAttribute() {
return userRoleAttribute;
}
public void setUserRoleAttribute(String userRoleAttribute) {
this.userRoleAttribute = userRoleAttribute;
}
/**
* 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;
}
/**
* 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;
}
public long getSizeLimit() {
return sizeLimit;
}
public void setSizeLimit(long sizeLimit) {
this.sizeLimit = sizeLimit;
}
public int getTimeLimit() {
return timeLimit;
}
public void setTimeLimit(int timeLimit) {
this.timeLimit = timeLimit;
}
public boolean isUseDelegatedCredential() {
return useDelegatedCredential;
}
public void setUseDelegatedCredential(boolean useDelegatedCredential) {
this.useDelegatedCredential = useDelegatedCredential;
}
// ---------------------------------------------------------- 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
*/
@Override
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();
// TODO: Use a single log message
while (it.hasNext()) {
containerLog.debug("Found role: " + it.next());
}
}
return (new GenericPrincipal(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();
// TODO: Use a single log message
while (it.hasNext()) {
containerLog.debug("Found role: " + it.next());
}
}
// Create and return a suitable Principal for this user
return (new GenericPrincipal(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, 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<>();
if (userPassword != null)
list.add(userPassword);
if (userRoleName != null)
list.add(userRoleName);
if (userRoleAttribute != null) {
list.add(userRoleAttribute);
}
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 {
// If no attributes are requested, no need to look for them
if (attrIds == null || attrIds.length == 0) {
return new User(username, dn, null, null,null);
}
// 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);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, 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, userRoleAttrValue);
}
/**
* 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 {
userCredentialsAdd(context, dn, credentials);
user = getUserByPattern(context, username, attrIds, dn);
} finally {
userCredentialsRemove(context);
}
}
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);
}
constraints.setCountLimit(sizeLimit);
constraints.setTimeLimit(timeLimit);
// 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);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, 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, userRoleAttrValue);
}
/**
* 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.getUserName()));
} else {
containerLog.trace(sm.getString("jndiRealm.authenticateFailure",
user.getUserName()));
}
}
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.getPassword();
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(StandardCharsets.ISO_8859_1));
byte[] encoded = Base64.encodeBase64(md.digest());
String digestedPassword =
new String(encoded, StandardCharsets.ISO_8859_1);
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(StandardCharsets.ISO_8859_1));
// Decode stored password.
byte[] decoded = Base64.decodeBase64(password);
// Split decoded password into hash and salt.
final int saltpos = 20;
byte[] hash = new byte[saltpos];
System.arraycopy(decoded, 0, hash, 0, saltpos);
md.update(decoded, saltpos, decoded.length - saltpos);
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.getDN();
if (dn == null)
return (false);
// Validate the credentials specified by the user
if (containerLog.isTraceEnabled()) {
containerLog.trace(" validating credentials by binding as the user");
}
userCredentialsAdd(context, dn, 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");
}
}
userCredentialsRemove(context);
return (validated);
}
/**
* Configure the context to use the provided credentials for
* authentication.
*
* @param context DirContext to configure
* @param dn Distinguished name of user
* @param credentials Credentials of user
*/
private void userCredentialsAdd(DirContext context, String dn,
String credentials) throws NamingException {
// Set up security environment to bind as the user
context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
}
/**
* Configure the context to use {@link #connectionName} and
* {@link #connectionPassword} if specified or an anonymous connection if
* those attributes are not specified.
*
* @param context DirContext to configure
*/
private void userCredentialsRemove(DirContext context)
throws NamingException {
// 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 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.getDN();
String username = user.getUserName();
String userRoleId = user.getUserRoleId();
if (dn == null || username == null)
return (null);
if (containerLog.isTraceEnabled())
containerLog.trace(" getRoles(" + dn + ")");
// Start with roles retrieved from the user entry
List<String> list = new ArrayList<>();
List<String> userRoles = user.getRoles();
if (userRoles != null) {
list.addAll(userRoles);
}
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, userRoleId });
SearchControls controls = new SearchControls();
if (roleSubtree)
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
else
controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
controls.setReturningAttributes(new String[] {roleName});
String base = null;
if (roleBaseFormat != null) {
NameParser np = context.getNameParser("");
Name name = np.parse(dn);
String nameParts[] = new String[name.size()];
for (int i = 0; i < name.size(); i++) {
nameParts[i] = name.get(i);
}
base = roleBaseFormat.format(nameParts);
}
// Perform the configured search and process the results
NamingEnumeration<SearchResult> results = null;
try {
if (roleSearchAsUser) {
userCredentialsAdd(context, dn, user.getPassword());
}
results = context.search(base, filter, controls);
} finally {
if (roleSearchAsUser) {
userCredentialsRemove(context);
}
}
if (results == null)
return (list); // Should never happen, but just in case ...
HashMap<String, String> groupMap = new HashMap<>();
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
Map<String, String> newGroups = new HashMap<>(groupMap);
while (!newGroups.isEmpty()) {
Map<String, String> newThisRound = new HashMap<>(); // Stores the groups we find in this iteration
for (Entry<String, String> group : newGroups.entrySet()) {
filter = roleFormat.format(new String[] { group.getKey(), group.getValue(), group.getValue() });
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.put(dname, name);
if (containerLog.isTraceEnabled()) {
containerLog.trace(" Found nested role " + dname + " -> " + name);
}
}
}
} catch (PartialResultException ex) {
if (!adCompat)
throw ex;
}
}
newGroups = newThisRound;
}
}
list.addAll(groupMap.values());
return list;
}
/**
* 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<>();
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.
*/
@Override
protected String getName() {
return (name);
}
/**
* Return the password associated with the given principal's user name.
*/
@Override
protected String getPassword(String username) {
return (null);
}
/**
* Return the Principal associated with the given user name.
*/
@Override
protected Principal getPrincipal(String username) {
return getPrincipal(username, null);
}
@Override
protected Principal getPrincipal(String username,
GSSCredential gssCredential) {
DirContext context = null;
Principal principal = null;
try {
// Ensure that we have a directory context available
context = open();
// Occasionally the directory context will timeout. Try one more
// time before giving up.
try {
// Authenticate the specified username if possible
principal = getPrincipal(context, username, gssCredential);
} 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, gssCredential);
} 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, gssCredential);
}
// 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, GSSCredential gssCredential)
throws NamingException {
User user = null;
List<String> roles = null;
try {
if (gssCredential != null && isUseDelegatedCredential()) {
// Set up context
context.addToEnvironment(
Context.SECURITY_AUTHENTICATION, "GSSAPI");
context.addToEnvironment(
"javax.security.sasl.server.authentication", "true");
context.addToEnvironment(
"javax.security.sasl.qop", "auth-conf");
// Note: Subject already set in SPNEGO authenticator so no need
// for Subject.doAs() here
}
user = getUser(context, username);
if (user != null) {
roles = getRoles(context, user);
}
} finally {
try {
context.removeFromEnvironment(
Context.SECURITY_AUTHENTICATION);
} catch (NamingException e) {
// Ignore
}
try {
context.removeFromEnvironment(
"javax.security.sasl.server.authentication");
} catch (NamingException e) {
// Ignore
}
try {
context.removeFromEnvironment(
"javax.security.sasl.qop");
} catch (NamingException e) {
// Ignore
}
}
if (user != null) {
return new GenericPrincipal(user.getUserName(), user.getPassword(),
roles, null, null, gssCredential);
}
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<>();
// 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 the beginning of active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected void startInternal() throws LifecycleException {
// Validate that we can open our connection
try {
open();
} catch (NamingException e) {
throw new LifecycleException(sm.getString("jndiRealm.open"), e);
}
super.startInternal();
}
/**
* Gracefully terminate the active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
super.stopInternal();
// 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<>();
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 );
}
}
}
// ------------------------------------------------------ Private Classes
/**
* A protected class representing a User
*/
protected static class User {
private final String username;
private final String dn;
private final String password;
private final List<String> roles;
private final String userRoleId;
public User(String username, String dn, String password,
List<String> roles, String userRoleId) {
this.username = username;
this.dn = dn;
this.password = password;
if (roles == null) {
this.roles = Collections.emptyList();
} else {
this.roles = Collections.unmodifiableList(roles);
}
this.userRoleId = userRoleId;
}
public String getUserName() {
return username;
}
public String getDN() {
return dn;
}
public String getPassword() {
return password;
}
public List<String> getRoles() {
return roles;
}
public String getUserRoleId() {
return userRoleId;
}
}
}
|
55,434
|
Bug 55434 The path /foo/a/a/bar causes IllegalArgumentException when WsServerContainer creates UriTemplate
|
WsFilter calls WsServerContainer.findMapping("/foo/a/a/bar"), which in turn calls new UriTemplate(path). If the path contains repeated segments, it causes the following code in the UriTemplate constructor to throw an exception: Segment old = this.segments.put(segment, new Segment(index, segment)); if (old != null) { throw new IllegalArgumentException( sm.getString("uriTemplate.duplicateName", segment)); } This would be valid if the duplicates were URI variable names but not when their plain path segments.
|
resolved fixed
|
98ee5b4
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-18T18:14:36Z
| 2013-08-16T21:53:20Z
|
java/org/apache/tomcat/websocket/server/UriTemplate.java
|
/*
* 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.websocket.server;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.websocket.DeploymentException;
import org.apache.tomcat.util.res.StringManager;
/**
* Extracts path parameters from URIs used to create web socket connections
* using the URI template defined for the associated Endpoint.
*/
public class UriTemplate {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private final String normalized;
private final Map<String,Segment> segments = new LinkedHashMap<>();
private final boolean hasParameters;
public UriTemplate(String path) throws DeploymentException {
if (path == null || path.length() ==0 || !path.startsWith("/")) {
throw new DeploymentException(
sm.getString("uriTemplate.invalidPath", path));
}
StringBuilder normalized = new StringBuilder(path.length());
String[] segments = path.split("/");
int paramCount = 0;
int segmentCount = 0;
for (int i = 0; i < segments.length; i++) {
String segment = segments[i];
if (segment.length() == 0) {
continue;
}
normalized.append('/');
int index = -1;
if (segment.startsWith("{") && segment.endsWith("}")) {
index = segmentCount;
segment = segment.substring(1, segment.length() - 1);
normalized.append('{');
normalized.append(paramCount++);
normalized.append('}');
} else {
if (segment.contains("{") || segment.contains("}")) {
throw new IllegalArgumentException(sm.getString(
"uriTemplate.invalidSegment", segment, path));
}
normalized.append(segment);
}
Segment old =
this.segments.put(segment, new Segment(index, segment));
if (old != null) {
throw new IllegalArgumentException(
sm.getString("uriTemplate.duplicateName", segment));
}
segmentCount++;
}
this.normalized = normalized.toString();
this.hasParameters = paramCount > 0;
}
public Map<String,String> match(UriTemplate candidate) {
Map<String,String> result = new HashMap<>();
// Should not happen but for safety
if (candidate.getSegmentCount() != getSegmentCount()) {
return null;
}
Iterator<Segment> candidateSegments =
candidate.getSegments().values().iterator();
Iterator<Segment> targetSegments = segments.values().iterator();
while (candidateSegments.hasNext()) {
Segment candidateSegment = candidateSegments.next();
Segment targetSegment = targetSegments.next();
if (targetSegment.getParameterIndex() == -1) {
// Not a parameter - values must match
if (!targetSegment.getValue().equals(
candidateSegment.getValue())) {
// Not a match. Stop here
return null;
}
} else {
// Parameter
result.put(targetSegment.getValue(),
candidateSegment.getValue());
}
}
return result;
}
public boolean hasParameters() {
return hasParameters;
}
public int getSegmentCount() {
return segments.size();
}
public String getNormalizedPath() {
return normalized;
}
private Map<String,Segment> getSegments() {
return segments;
}
private static class Segment {
private final int parameterIndex;
private final String value;
public Segment(int parameterIndex, String value) {
this.parameterIndex = parameterIndex;
this.value = value;
}
public int getParameterIndex() {
return parameterIndex;
}
public String getValue() {
return value;
}
}
}
|
55,434
|
Bug 55434 The path /foo/a/a/bar causes IllegalArgumentException when WsServerContainer creates UriTemplate
|
WsFilter calls WsServerContainer.findMapping("/foo/a/a/bar"), which in turn calls new UriTemplate(path). If the path contains repeated segments, it causes the following code in the UriTemplate constructor to throw an exception: Segment old = this.segments.put(segment, new Segment(index, segment)); if (old != null) { throw new IllegalArgumentException( sm.getString("uriTemplate.duplicateName", segment)); } This would be valid if the duplicates were URI variable names but not when their plain path segments.
|
resolved fixed
|
98ee5b4
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-18T18:14:36Z
| 2013-08-16T21:53:20Z
|
test/org/apache/tomcat/websocket/server/TestUriTemplate.java
|
/*
* 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.websocket.server;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class TestUriTemplate {
@Test
public void testBasic() throws Exception {
UriTemplate t = new UriTemplate("/{a}/{b}");
Map<String,String> result = t.match(new UriTemplate("/foo/bar"));
Assert.assertEquals(2, result.size());
Assert.assertTrue(result.containsKey("a"));
Assert.assertTrue(result.containsKey("b"));
Assert.assertEquals("foo", result.get("a"));
Assert.assertEquals("bar", result.get("b"));
}
@Test
public void testOneOfTwo() throws Exception {
UriTemplate t = new UriTemplate("/{a}/{b}");
Map<String,String> result = t.match(new UriTemplate("/foo"));
Assert.assertNull(result);
}
@Test(expected=java.lang.IllegalArgumentException.class)
public void testBasicPrefix() throws Exception {
@SuppressWarnings("unused")
UriTemplate t = new UriTemplate("/x{a}/y{b}");
}
@Test(expected=java.lang.IllegalArgumentException.class)
public void testPrefixOneOfTwo() throws Exception {
UriTemplate t = new UriTemplate("/x{a}/y{b}");
t.match(new UriTemplate("/xfoo"));
}
@Test(expected=java.lang.IllegalArgumentException.class)
public void testPrefixTwoOfTwo() throws Exception {
UriTemplate t = new UriTemplate("/x{a}/y{b}");
t.match(new UriTemplate("/ybar"));
}
@Test(expected=java.lang.IllegalArgumentException.class)
public void testQuote1() throws Exception {
UriTemplate t = new UriTemplate("/.{a}");
t.match(new UriTemplate("/yfoo"));
}
@Test(expected=java.lang.IllegalArgumentException.class)
public void testQuote2() throws Exception {
@SuppressWarnings("unused")
UriTemplate t = new UriTemplate("/.{a}");
}
@Test
public void testNoParams() throws Exception {
UriTemplate t = new UriTemplate("/foo/bar");
Map<String,String> result = t.match(new UriTemplate("/foo/bar"));
Assert.assertEquals(0, result.size());
}
@Test
public void testSpecExample1_01() throws Exception {
UriTemplate t = new UriTemplate("/a/b");
Map<String,String> result = t.match(new UriTemplate("/a/b"));
Assert.assertEquals(0, result.size());
}
@Test
public void testSpecExample1_02() throws Exception {
UriTemplate t = new UriTemplate("/a/b");
Map<String,String> result = t.match(new UriTemplate("/a"));
Assert.assertNull(result);
}
@Test
public void testSpecExample1_03() throws Exception {
UriTemplate t = new UriTemplate("/a/b");
Map<String,String> result = t.match(new UriTemplate("/a/bb"));
Assert.assertNull(result);
}
@Test
public void testSpecExample2_01() throws Exception {
UriTemplate t = new UriTemplate("/a/{var}");
Map<String,String> result = t.match(new UriTemplate("/a/b"));
Assert.assertEquals(1, result.size());
Assert.assertEquals("b", result.get("var"));
}
@Test
public void testSpecExample2_02() throws Exception {
UriTemplate t = new UriTemplate("/a/{var}");
Map<String,String> result = t.match(new UriTemplate("/a/apple"));
Assert.assertEquals(1, result.size());
Assert.assertEquals("apple", result.get("var"));
}
@Test
public void testSpecExample2_03() throws Exception {
UriTemplate t = new UriTemplate("/a/{var}");
Map<String,String> result = t.match(new UriTemplate("/a"));
Assert.assertNull(result);
}
@Test
public void testSpecExample2_04() throws Exception {
UriTemplate t = new UriTemplate("/a/{var}");
Map<String,String> result = t.match(new UriTemplate("/a/b/c"));
Assert.assertNull(result);
}
@Test(expected=java.lang.IllegalArgumentException.class)
public void testDuplicate() throws Exception {
@SuppressWarnings("unused")
UriTemplate t = new UriTemplate("/{var}/{var}");
}
}
|
55,438
|
Bug 55438 Non Blocking API's onAllDataRead being called twice
| null |
resolved fixed
|
7f6ea48
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-19T14:54:15Z
| 2013-08-16T21:53:20Z
|
java/org/apache/catalina/connector/InputBuffer.java
|
/*
* 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.connector;
import java.io.IOException;
import java.io.Reader;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import javax.servlet.ReadListener;
import org.apache.catalina.security.SecurityUtil;
import org.apache.coyote.ActionCode;
import org.apache.coyote.Request;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.res.StringManager;
/**
* The buffer used by Tomcat request. This is a derivative of the Tomcat 3.3
* OutputBuffer, adapted to handle input instead of output. This allows
* complete recycling of the facade objects (the ServletInputStream and the
* BufferedReader).
*
* @author Remy Maucherat
*/
public class InputBuffer extends Reader
implements ByteChunk.ByteInputChannel, CharChunk.CharInputChannel,
CharChunk.CharOutputChannel {
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
// -------------------------------------------------------------- Constants
public static final String DEFAULT_ENCODING =
org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING;
public static final int DEFAULT_BUFFER_SIZE = 8*1024;
// The buffer can be used for byte[] and char[] reading
// ( this is needed to support ServletInputStream and BufferedReader )
public final int INITIAL_STATE = 0;
public final int CHAR_STATE = 1;
public final int BYTE_STATE = 2;
// ----------------------------------------------------- Instance Variables
/**
* The byte buffer.
*/
private final ByteChunk bb;
/**
* The chunk buffer.
*/
private CharChunk cb;
/**
* State of the output buffer.
*/
private int state = 0;
/**
* Flag which indicates if the input buffer is closed.
*/
private boolean closed = false;
/**
* Encoding to use.
*/
private String enc;
/**
* Encoder is set.
*/
private boolean gotEnc = false;
/**
* List of encoders.
*/
protected final HashMap<String,B2CConverter> encoders = new HashMap<>();
/**
* Current byte to char converter.
*/
protected B2CConverter conv;
/**
* Associated Coyote request.
*/
private Request coyoteRequest;
/**
* Buffer position.
*/
private int markPos = -1;
/**
* Buffer size.
*/
private final int size;
// ----------------------------------------------------------- Constructors
/**
* Default constructor. Allocate the buffer with the default buffer size.
*/
public InputBuffer() {
this(DEFAULT_BUFFER_SIZE);
}
/**
* Alternate constructor which allows specifying the initial buffer size.
*
* @param size Buffer size to use
*/
public InputBuffer(int size) {
this.size = size;
bb = new ByteChunk(size);
bb.setLimit(size);
bb.setByteInputChannel(this);
cb = new CharChunk(size);
cb.setLimit(size);
cb.setOptimizedWrite(false);
cb.setCharInputChannel(this);
cb.setCharOutputChannel(this);
}
// ------------------------------------------------------------- Properties
/**
* Associated Coyote request.
*
* @param coyoteRequest Associated Coyote request
*/
public void setRequest(Request coyoteRequest) {
this.coyoteRequest = coyoteRequest;
}
// --------------------------------------------------------- Public Methods
/**
* Recycle the output buffer.
*/
public void recycle() {
state = INITIAL_STATE;
// If usage of mark made the buffer too big, reallocate it
if (cb.getChars().length > size) {
cb = new CharChunk(size);
cb.setLimit(size);
cb.setOptimizedWrite(false);
cb.setCharInputChannel(this);
cb.setCharOutputChannel(this);
} else {
cb.recycle();
}
markPos = -1;
bb.recycle();
closed = false;
if (conv != null) {
conv.recycle();
}
gotEnc = false;
enc = null;
}
/**
* Clear cached encoders (to save memory for Comet requests).
*/
public void clearEncoders() {
encoders.clear();
}
/**
* Close the input buffer.
*
* @throws IOException An underlying IOException occurred
*/
@Override
public void close()
throws IOException {
closed = true;
}
public int available() {
int available = 0;
if (state == BYTE_STATE) {
available = bb.getLength();
} else if (state == CHAR_STATE) {
available = cb.getLength();
}
if (available == 0) {
coyoteRequest.action(ActionCode.AVAILABLE, null);
available = (coyoteRequest.getAvailable() > 0) ? 1 : 0;
}
return available;
}
public void setReadListener(ReadListener listener) {
coyoteRequest.setReadListener(listener);
// The container is responsible for the first call to
// listener.onDataAvailable(). If isReady() returns true, the container
// needs to call listener.onDataAvailable() from a new thread. If
// isReady() returns false, the socket will be registered for read and
// the container will call listener.onDataAvailable() once data arrives.
// Must call isFinished() first as a call to isReady() if the request
// has been finished will register the socket for read interest and that
// is not required.
if (isFinished() || isReady()) {
coyoteRequest.action(ActionCode.DISPATCH_READ, null);
}
}
public boolean isFinished() {
return available() == 0;
}
public boolean isReady() {
if (coyoteRequest.getReadListener() == null) {
throw new IllegalStateException("not in non blocking mode.");
}
int available = available();
boolean result = available > 0;
if (!result) {
coyoteRequest.action(ActionCode.NB_READ_INTEREST, null);
}
return result;
}
// ------------------------------------------------- Bytes Handling Methods
/**
* Reads new bytes in the byte chunk.
*
* @param cbuf Byte buffer to be written to the response
* @param off Offset
* @param len Length
*
* @throws IOException An underlying IOException occurred
*/
@Override
public int realReadBytes(byte cbuf[], int off, int len)
throws IOException {
if (closed) {
return -1;
}
if (coyoteRequest == null) {
return -1;
}
if(state == INITIAL_STATE) {
state = BYTE_STATE;
}
int result = coyoteRequest.doRead(bb);
return result;
}
public int readByte()
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
return bb.substract();
}
public int read(byte[] b, int off, int len)
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
return bb.substract(b, off, len);
}
// ------------------------------------------------- Chars Handling Methods
/**
* Since the converter will use append, it is possible to get chars to
* be removed from the buffer for "writing". Since the chars have already
* been read before, they are ignored. If a mark was set, then the
* mark is lost.
*/
@Override
public void realWriteChars(char c[], int off, int len)
throws IOException {
markPos = -1;
cb.setOffset(0);
cb.setEnd(0);
}
public void setEncoding(String s) {
enc = s;
}
@Override
public int realReadChars(char cbuf[], int off, int len)
throws IOException {
if (!gotEnc) {
setConverter();
}
boolean eof = false;
if (bb.getLength() <= 0) {
int nRead = realReadBytes(bb.getBytes(), 0, bb.getBytes().length);
if (nRead < 0) {
eof = true;
}
}
if (markPos == -1) {
cb.setOffset(0);
cb.setEnd(0);
} else {
// Make sure there's enough space in the worst case
cb.makeSpace(bb.getLength());
if ((cb.getBuffer().length - cb.getEnd()) == 0) {
// We went over the limit
cb.setOffset(0);
cb.setEnd(0);
markPos = -1;
}
}
state = CHAR_STATE;
conv.convert(bb, cb, eof);
if (cb.getLength() == 0 && eof) {
return -1;
} else {
return cb.getLength();
}
}
@Override
public int read()
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
return cb.substract();
}
@Override
public int read(char[] cbuf)
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
return read(cbuf, 0, cbuf.length);
}
@Override
public int read(char[] cbuf, int off, int len)
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
return cb.substract(cbuf, off, len);
}
@Override
public long skip(long n)
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
if (n < 0) {
throw new IllegalArgumentException();
}
long nRead = 0;
while (nRead < n) {
if (cb.getLength() >= n) {
cb.setOffset(cb.getStart() + (int) n);
nRead = n;
} else {
nRead += cb.getLength();
cb.setOffset(cb.getEnd());
int toRead = 0;
if (cb.getChars().length < (n - nRead)) {
toRead = cb.getChars().length;
} else {
toRead = (int) (n - nRead);
}
int nb = realReadChars(cb.getChars(), 0, toRead);
if (nb < 0) {
break;
}
}
}
return nRead;
}
@Override
public boolean ready()
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
if (state == INITIAL_STATE) {
state = CHAR_STATE;
}
return (available() > 0);
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readAheadLimit)
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
if (cb.getLength() <= 0) {
cb.setOffset(0);
cb.setEnd(0);
} else {
if ((cb.getBuffer().length > (2 * size))
&& (cb.getLength()) < (cb.getStart())) {
System.arraycopy(cb.getBuffer(), cb.getStart(),
cb.getBuffer(), 0, cb.getLength());
cb.setEnd(cb.getLength());
cb.setOffset(0);
}
}
cb.setLimit(cb.getStart() + readAheadLimit + size);
markPos = cb.getStart();
}
@Override
public void reset()
throws IOException {
if (closed) {
throw new IOException(sm.getString("inputBuffer.streamClosed"));
}
if (state == CHAR_STATE) {
if (markPos < 0) {
cb.recycle();
markPos = -1;
throw new IOException();
} else {
cb.setOffset(markPos);
}
} else {
bb.recycle();
}
}
public void checkConverter()
throws IOException {
if (!gotEnc) {
setConverter();
}
}
protected void setConverter()
throws IOException {
if (coyoteRequest != null) {
enc = coyoteRequest.getCharacterEncoding();
}
gotEnc = true;
if (enc == null) {
enc = DEFAULT_ENCODING;
}
conv = encoders.get(enc);
if (conv == null) {
if (SecurityUtil.isPackageProtectionEnabled()){
try{
conv = AccessController.doPrivileged(
new PrivilegedExceptionAction<B2CConverter>(){
@Override
public B2CConverter run() throws IOException {
return new B2CConverter(enc);
}
}
);
}catch(PrivilegedActionException ex){
Exception e = ex.getException();
if (e instanceof IOException) {
throw (IOException)e;
}
}
} else {
conv = new B2CConverter(enc);
}
encoders.put(enc, conv);
}
}
}
|
55,438
|
Bug 55438 Non Blocking API's onAllDataRead being called twice
| null |
resolved fixed
|
7f6ea48
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-19T14:54:15Z
| 2013-08-16T21:53:20Z
|
java/org/apache/catalina/connector/Request.java
|
/*
* 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.connector;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.FilterChain;
import javax.servlet.MultipartConfigElement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletResponse;
import javax.servlet.SessionTrackingMode;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.Manager;
import org.apache.catalina.Realm;
import org.apache.catalina.Session;
import org.apache.catalina.TomcatPrincipal;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.ApplicationPart;
import org.apache.catalina.core.ApplicationSessionCookieConfig;
import org.apache.catalina.core.AsyncContextImpl;
import org.apache.catalina.mapper.MappingData;
import org.apache.catalina.util.ParameterMap;
import org.apache.catalina.util.StringParser;
import org.apache.coyote.ActionCode;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.Cookies;
import org.apache.tomcat.util.http.FastHttpDateFormat;
import org.apache.tomcat.util.http.Parameters;
import org.apache.tomcat.util.http.ServerCookie;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.apache.tomcat.util.res.StringManager;
/**
* Wrapper object for the Coyote request.
*
* @author Remy Maucherat
* @author Craig R. McClanahan
* @version $Id$
*/
public class Request
implements HttpServletRequest {
private static final Log log = LogFactory.getLog(Request.class);
// ----------------------------------------------------------- Constructors
public Request() {
formats[0].setTimeZone(GMT_ZONE);
formats[1].setTimeZone(GMT_ZONE);
formats[2].setTimeZone(GMT_ZONE);
}
// ------------------------------------------------------------- Properties
/**
* Coyote request.
*/
protected org.apache.coyote.Request coyoteRequest;
/**
* Set the Coyote request.
*
* @param coyoteRequest The Coyote request
*/
public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) {
this.coyoteRequest = coyoteRequest;
inputBuffer.setRequest(coyoteRequest);
}
/**
* Get the Coyote request.
*/
public org.apache.coyote.Request getCoyoteRequest() {
return (this.coyoteRequest);
}
// ----------------------------------------------------- Variables
protected static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* The set of cookies associated with this Request.
*/
protected Cookie[] cookies = null;
/**
* The set of SimpleDateFormat formats to use in getDateHeader().
*
* Notice that because SimpleDateFormat is not thread-safe, we can't
* declare formats[] as a static variable.
*/
protected final SimpleDateFormat formats[] = {
new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE, 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)
};
/**
* The default Locale if none are specified.
*/
protected static final Locale defaultLocale = Locale.getDefault();
/**
* The attributes associated with this Request, keyed by attribute name.
*/
protected final HashMap<String, Object> attributes = new HashMap<>();
/**
* Flag that indicates if SSL attributes have been parsed to improve
* performance for applications (usually frameworks) that make multiple
* calls to {@link Request#getAttributeNames()}.
*/
protected boolean sslAttributesParsed = false;
/**
* List of read only attributes for this Request.
*/
private final HashMap<String,Object> readOnlyAttributes = new HashMap<>();
/**
* The preferred Locales associated with this Request.
*/
protected final ArrayList<Locale> locales = new ArrayList<>();
/**
* Internal notes associated with this request by Catalina components
* and event listeners.
*/
private final transient HashMap<String, Object> notes = new HashMap<>();
/**
* Authentication type.
*/
protected String authType = null;
/**
* Associated event.
*/
protected CometEventImpl event = null;
/**
* Comet state
*/
protected boolean comet = false;
/**
* The current dispatcher type.
*/
protected DispatcherType internalDispatcherType = null;
/**
* The associated input buffer.
*/
protected final InputBuffer inputBuffer = new InputBuffer();
/**
* ServletInputStream.
*/
protected CoyoteInputStream inputStream =
new CoyoteInputStream(inputBuffer);
/**
* Reader.
*/
protected CoyoteReader reader = new CoyoteReader(inputBuffer);
/**
* Using stream flag.
*/
protected boolean usingInputStream = false;
/**
* Using writer flag.
*/
protected boolean usingReader = false;
/**
* User principal.
*/
protected Principal userPrincipal = null;
/**
* Request parameters parsed flag.
*/
protected boolean parametersParsed = false;
/**
* Cookies parsed flag.
*/
protected boolean cookiesParsed = false;
/**
* Secure flag.
*/
protected boolean secure = false;
/**
* The Subject associated with the current AccessControllerContext
*/
protected transient Subject subject = null;
/**
* Post data buffer.
*/
protected static final int CACHED_POST_LEN = 8192;
protected byte[] postData = null;
/**
* Hash map used in the getParametersMap method.
*/
protected ParameterMap<String, String[]> parameterMap = new ParameterMap<>();
/**
* The parts, if any, uploaded with this request.
*/
protected Collection<Part> parts = null;
/**
* The exception thrown, if any when parsing the parts.
*/
protected Exception partsParseException = null;
/**
* The currently active session for this request.
*/
protected Session session = null;
/**
* The current request dispatcher path.
*/
protected Object requestDispatcherPath = null;
/**
* Was the requested session ID received in a cookie?
*/
protected boolean requestedSessionCookie = false;
/**
* The requested session ID (if any) for this request.
*/
protected String requestedSessionId = null;
/**
* Was the requested session ID received in a URL?
*/
protected boolean requestedSessionURL = false;
/**
* Was the requested session ID obtained from the SSL session?
*/
protected boolean requestedSessionSSL = false;
/**
* Parse locales.
*/
protected boolean localesParsed = false;
/**
* The string parser we will use for parsing request lines.
*/
private final StringParser parser = new StringParser();
/**
* Local port
*/
protected int localPort = -1;
/**
* Remote address.
*/
protected String remoteAddr = null;
/**
* Remote host.
*/
protected String remoteHost = null;
/**
* Remote port
*/
protected int remotePort = -1;
/**
* Local address
*/
protected String localAddr = null;
/**
* Local address
*/
protected String localName = null;
/**
* AsyncContext
*/
protected volatile AsyncContextImpl asyncContext = null;
protected Boolean asyncSupported = null;
/**
* Path parameters
*/
protected final Map<String,String> pathParameters = new HashMap<>();
// --------------------------------------------------------- Public Methods
protected void addPathParameter(String name, String value) {
pathParameters.put(name, value);
}
protected String getPathParameter(String name) {
return pathParameters.get(name);
}
public void setAsyncSupported(boolean asyncSupported) {
this.asyncSupported = Boolean.valueOf(asyncSupported);
}
/**
* Release all object references, and initialize instance variables, in
* preparation for reuse of this object.
*/
public void recycle() {
context = null;
wrapper = null;
internalDispatcherType = null;
requestDispatcherPath = null;
comet = false;
if (event != null) {
event.clear();
event = null;
}
authType = null;
inputBuffer.recycle();
usingInputStream = false;
usingReader = false;
userPrincipal = null;
subject = null;
parametersParsed = false;
if (parts != null) {
for (Part part: parts) {
try {
part.delete();
} catch (IOException ignored) {
// ApplicationPart.delete() never throws an IOEx
}
}
parts = null;
}
partsParseException = null;
cookiesParsed = false;
locales.clear();
localesParsed = false;
secure = false;
remoteAddr = null;
remoteHost = null;
remotePort = -1;
localPort = -1;
localAddr = null;
localName = null;
attributes.clear();
sslAttributesParsed = false;
notes.clear();
cookies = null;
if (session != null) {
try {
session.endAccess();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t);
}
}
session = null;
requestedSessionCookie = false;
requestedSessionId = null;
requestedSessionURL = false;
if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
parameterMap = new ParameterMap<>();
} else {
parameterMap.setLocked(false);
parameterMap.clear();
}
mappingData.recycle();
if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
if (facade != null) {
facade.clear();
facade = null;
}
if (inputStream != null) {
inputStream.clear();
inputStream = null;
}
if (reader != null) {
reader.clear();
reader = null;
}
}
asyncSupported = null;
if (asyncContext!=null) {
asyncContext.recycle();
}
asyncContext = null;
pathParameters.clear();
}
/**
* Clear cached encoders (to save memory for Comet requests).
*/
public void clearEncoders() {
inputBuffer.clearEncoders();
}
/**
* Clear cached encoders (to save memory for Comet requests).
*/
public boolean read()
throws IOException {
return (inputBuffer.realReadBytes(null, 0, 0) > 0);
}
// -------------------------------------------------------- Request Methods
/**
* Associated Catalina connector.
*/
protected Connector connector;
/**
* Return the Connector through which this Request was received.
*/
public Connector getConnector() {
return this.connector;
}
/**
* Set the Connector through which this Request was received.
*
* @param connector The new connector
*/
public void setConnector(Connector connector) {
this.connector = connector;
}
/**
* Associated context.
*/
protected Context context = null;
/**
* Return the Context within which this Request is being processed.
*/
public Context getContext() {
return this.context;
}
/**
* Set the Context within which this Request is being processed. This
* must be called as soon as the appropriate Context is identified, because
* it identifies the value to be returned by <code>getContextPath()</code>,
* and thus enables parsing of the request URI.
*
* @param context The newly associated Context
*/
public void setContext(Context context) {
this.context = context;
}
/**
* Filter chain associated with the request.
*/
protected FilterChain filterChain = null;
/**
* Get filter chain associated with the request.
*/
public FilterChain getFilterChain() {
return this.filterChain;
}
/**
* Set filter chain associated with the request.
*
* @param filterChain new filter chain
*/
public void setFilterChain(FilterChain filterChain) {
this.filterChain = filterChain;
}
/**
* Return the Host within which this Request is being processed.
*/
public Host getHost() {
return mappingData.host;
}
/**
* Mapping data.
*/
protected final MappingData mappingData = new MappingData();
/**
* Return mapping data.
*/
public MappingData getMappingData() {
return mappingData;
}
/**
* The facade associated with this request.
*/
protected RequestFacade facade = null;
/**
* Return the <code>ServletRequest</code> for which this object
* is the facade. This method must be implemented by a subclass.
*/
public HttpServletRequest getRequest() {
if (facade == null) {
facade = new RequestFacade(this);
}
return facade;
}
/**
* The response with which this request is associated.
*/
protected org.apache.catalina.connector.Response response = null;
/**
* Return the Response with which this Request is associated.
*/
public org.apache.catalina.connector.Response getResponse() {
return this.response;
}
/**
* Set the Response with which this Request is associated.
*
* @param response The new associated response
*/
public void setResponse(org.apache.catalina.connector.Response response) {
this.response = response;
}
/**
* Return the input stream associated with this Request.
*/
public InputStream getStream() {
if (inputStream == null) {
inputStream = new CoyoteInputStream(inputBuffer);
}
return inputStream;
}
/**
* URI byte to char converter.
*/
protected B2CConverter URIConverter = null;
/**
* Return the URI converter.
*/
protected B2CConverter getURIConverter() {
return URIConverter;
}
/**
* Set the URI converter.
*
* @param URIConverter the new URI converter
*/
protected void setURIConverter(B2CConverter URIConverter) {
this.URIConverter = URIConverter;
}
/**
* Associated wrapper.
*/
protected Wrapper wrapper = null;
/**
* Return the Wrapper within which this Request is being processed.
*/
public Wrapper getWrapper() {
return this.wrapper;
}
/**
* Set the Wrapper within which this Request is being processed. This
* must be called as soon as the appropriate Wrapper is identified, and
* before the Request is ultimately passed to an application servlet.
* @param wrapper The newly associated Wrapper
*/
public void setWrapper(Wrapper wrapper) {
this.wrapper = wrapper;
}
// ------------------------------------------------- Request Public Methods
/**
* Create and return a ServletInputStream to read the content
* associated with this Request.
*
* @exception IOException if an input/output error occurs
*/
public ServletInputStream createInputStream()
throws IOException {
if (inputStream == null) {
inputStream = new CoyoteInputStream(inputBuffer);
}
return inputStream;
}
/**
* Perform whatever actions are required to flush and close the input
* stream or reader, in a single operation.
*
* @exception IOException if an input/output error occurs
*/
public void finishRequest() throws IOException {
// Optionally disable swallowing of additional request data.
Context context = getContext();
if (context != null &&
response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE &&
!context.getSwallowAbortedUploads()) {
coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null);
}
}
/**
* Return the object bound with the specified name to the internal notes
* for this request, or <code>null</code> if no such binding exists.
*
* @param name Name of the note to be returned
*/
public Object getNote(String name) {
return notes.get(name);
}
/**
* Remove any object bound to the specified name in the internal notes
* for this request.
*
* @param name Name of the note to be removed
*/
public void removeNote(String name) {
notes.remove(name);
}
/**
* Set the port number of the server to process this request.
*
* @param port The server port
*/
public void setLocalPort(int port) {
localPort = port;
}
/**
* Bind an object to a specified name in the internal notes associated
* with this request, replacing any existing binding for this name.
*
* @param name Name to which the object should be bound
* @param value Object to be bound to the specified name
*/
public void setNote(String name, Object value) {
notes.put(name, value);
}
/**
* Set the IP address of the remote client associated with this Request.
*
* @param remoteAddr The remote IP address
*/
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
/**
* Set the fully qualified name of the remote client associated with this
* Request.
*
* @param remoteHost The remote host name
*/
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
/**
* Set the value to be returned by <code>isSecure()</code>
* for this Request.
*
* @param secure The new isSecure value
*/
public void setSecure(boolean secure) {
this.secure = secure;
}
/**
* Set the port number of the server to process this request.
*
* @param port The server port
*/
public void setServerPort(int port) {
coyoteRequest.setServerPort(port);
}
// ------------------------------------------------- ServletRequest Methods
/**
* Return the specified request attribute if it exists; otherwise, return
* <code>null</code>.
*
* @param name Name of the request attribute to return
*/
@Override
public Object getAttribute(String name) {
// Special attributes
SpecialAttributeAdapter adapter = specialAttributes.get(name);
if (adapter != null) {
return adapter.get(this, name);
}
Object attr=attributes.get(name);
if(attr!=null) {
return(attr);
}
attr = coyoteRequest.getAttribute(name);
if(attr != null) {
return attr;
}
if( isSSLAttribute(name) ) {
coyoteRequest.action(ActionCode.REQ_SSL_ATTRIBUTE,
coyoteRequest);
attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR);
if( attr != null) {
attributes.put(Globals.CERTIFICATES_ATTR, attr);
}
attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR);
if(attr != null) {
attributes.put(Globals.CIPHER_SUITE_ATTR, attr);
}
attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR);
if(attr != null) {
attributes.put(Globals.KEY_SIZE_ATTR, attr);
}
attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR);
if(attr != null) {
attributes.put(Globals.SSL_SESSION_ID_ATTR, attr);
}
attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_MGR_ATTR);
if(attr != null) {
attributes.put(Globals.SSL_SESSION_MGR_ATTR, attr);
}
attr = attributes.get(name);
sslAttributesParsed = true;
}
return attr;
}
@Override
public long getContentLengthLong() {
return coyoteRequest.getContentLengthLong();
}
/**
* Test if a given name is one of the special Servlet-spec SSL attributes.
*/
static boolean isSSLAttribute(String name) {
return Globals.CERTIFICATES_ATTR.equals(name) ||
Globals.CIPHER_SUITE_ATTR.equals(name) ||
Globals.KEY_SIZE_ATTR.equals(name) ||
Globals.SSL_SESSION_ID_ATTR.equals(name) ||
Globals.SSL_SESSION_MGR_ATTR.equals(name);
}
/**
* Return the names of all request attributes for this Request, or an
* empty <code>Enumeration</code> if there are none. Note that the attribute
* names returned will only be those for the attributes set via
* {@link #setAttribute(String, Object)}. Tomcat internal attributes will
* not be included although they are accessible via
* {@link #getAttribute(String)}. The Tomcat internal attributes include:
* <ul>
* <li>{@link Globals#DISPATCHER_TYPE_ATTR}</li>
* <li>{@link Globals#DISPATCHER_REQUEST_PATH_ATTR}</li>
* <li>{@link Globals#ASYNC_SUPPORTED_ATTR}</li>
* <li>{@link Globals#CERTIFICATES_ATTR} (SSL connections only)</li>
* <li>{@link Globals#CIPHER_SUITE_ATTR} (SSL connections only)</li>
* <li>{@link Globals#KEY_SIZE_ATTR} (SSL connections only)</li>
* <li>{@link Globals#SSL_SESSION_ID_ATTR} (SSL connections only)</li>
* <li>{@link Globals#SSL_SESSION_MGR_ATTR} (SSL connections only)</li>
* <li>{@link Globals#PARAMETER_PARSE_FAILED_ATTR}</li>
* </ul>
* The underlying connector may also expose request attributes. These all
* have names starting with "org.apache.tomcat" and include:
* <ul>
* <li>{@link Globals#SENDFILE_SUPPORTED_ATTR}</li>
* <li>{@link Globals#COMET_SUPPORTED_ATTR}</li>
* <li>{@link Globals#COMET_TIMEOUT_SUPPORTED_ATTR}</li>
* </ul>
* Connector implementations may return some, all or none of these
* attributes and may also support additional attributes.
*/
@Override
public Enumeration<String> getAttributeNames() {
if (isSecure() && !sslAttributesParsed) {
getAttribute(Globals.CERTIFICATES_ATTR);
}
// Take a copy to prevent ConncurrentModificationExceptions if used to
// remove attributes
Set<String> names = new HashSet<>();
names.addAll(attributes.keySet());
return Collections.enumeration(names);
}
/**
* Return the character encoding for this Request.
*/
@Override
public String getCharacterEncoding() {
return coyoteRequest.getCharacterEncoding();
}
/**
* Return the content length for this Request.
*/
@Override
public int getContentLength() {
return coyoteRequest.getContentLength();
}
/**
* Return the content type for this Request.
*/
@Override
public String getContentType() {
return coyoteRequest.getContentType();
}
/**
* Set the content type for this Request.
*/
public void setContentType(String contentType) {
coyoteRequest.setContentType(contentType);
}
/**
* Return the servlet input stream for this Request. The default
* implementation returns a servlet input stream created by
* <code>createInputStream()</code>.
*
* @exception IllegalStateException if <code>getReader()</code> has
* already been called for this request
* @exception IOException if an input/output error occurs
*/
@Override
public ServletInputStream getInputStream() throws IOException {
if (usingReader) {
throw new IllegalStateException
(sm.getString("coyoteRequest.getInputStream.ise"));
}
usingInputStream = true;
if (inputStream == null) {
inputStream = new CoyoteInputStream(inputBuffer);
}
return inputStream;
}
/**
* Return the preferred Locale that the client will accept content in,
* based on the value for the first <code>Accept-Language</code> header
* that was encountered. If the request did not specify a preferred
* language, the server's default Locale is returned.
*/
@Override
public Locale getLocale() {
if (!localesParsed) {
parseLocales();
}
if (locales.size() > 0) {
return locales.get(0);
}
return defaultLocale;
}
/**
* Return the set of preferred Locales that the client will accept
* content in, based on the values for any <code>Accept-Language</code>
* headers that were encountered. If the request did not specify a
* preferred language, the server's default Locale is returned.
*/
@Override
public Enumeration<Locale> getLocales() {
if (!localesParsed) {
parseLocales();
}
if (locales.size() > 0) {
return Collections.enumeration(locales);
}
ArrayList<Locale> results = new ArrayList<>();
results.add(defaultLocale);
return Collections.enumeration(results);
}
/**
* Return the value of the specified request parameter, if any; otherwise,
* return <code>null</code>. If there is more than one value defined,
* return only the first one.
*
* @param name Name of the desired request parameter
*/
@Override
public String getParameter(String name) {
if (!parametersParsed) {
parseParameters();
}
return coyoteRequest.getParameters().getParameter(name);
}
/**
* Returns a <code>Map</code> of the parameters of this request.
* Request parameters are extra information sent with the request.
* For HTTP servlets, parameters are contained in the query string
* or posted form data.
*
* @return A <code>Map</code> containing parameter names as keys
* and parameter values as map values.
*/
@Override
public Map<String, String[]> getParameterMap() {
if (parameterMap.isLocked()) {
return parameterMap;
}
Enumeration<String> enumeration = getParameterNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
String[] values = getParameterValues(name);
parameterMap.put(name, values);
}
parameterMap.setLocked(true);
return parameterMap;
}
/**
* Return the names of all defined request parameters for this request.
*/
@Override
public Enumeration<String> getParameterNames() {
if (!parametersParsed) {
parseParameters();
}
return coyoteRequest.getParameters().getParameterNames();
}
/**
* Return the defined values for the specified request parameter, if any;
* otherwise, return <code>null</code>.
*
* @param name Name of the desired request parameter
*/
@Override
public String[] getParameterValues(String name) {
if (!parametersParsed) {
parseParameters();
}
return coyoteRequest.getParameters().getParameterValues(name);
}
/**
* Return the protocol and version used to make this Request.
*/
@Override
public String getProtocol() {
return coyoteRequest.protocol().toString();
}
/**
* Read the Reader wrapping the input stream for this Request. The
* default implementation wraps a <code>BufferedReader</code> around the
* servlet input stream returned by <code>createInputStream()</code>.
*
* @exception IllegalStateException if <code>getInputStream()</code>
* has already been called for this request
* @exception IOException if an input/output error occurs
*/
@Override
public BufferedReader getReader() throws IOException {
if (usingInputStream) {
throw new IllegalStateException
(sm.getString("coyoteRequest.getReader.ise"));
}
usingReader = true;
inputBuffer.checkConverter();
if (reader == null) {
reader = new CoyoteReader(inputBuffer);
}
return reader;
}
/**
* Return the real path of the specified virtual path.
*
* @param path Path to be translated
*
* @deprecated As of version 2.1 of the Java Servlet API, use
* <code>ServletContext.getRealPath()</code>.
*/
@Override
@Deprecated
public String getRealPath(String path) {
if (context == null) {
return null;
}
ServletContext servletContext = context.getServletContext();
if (servletContext == null) {
return null;
}
try {
return (servletContext.getRealPath(path));
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* Return the remote IP address making this Request.
*/
@Override
public String getRemoteAddr() {
if (remoteAddr == null) {
coyoteRequest.action
(ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest);
remoteAddr = coyoteRequest.remoteAddr().toString();
}
return remoteAddr;
}
/**
* Return the remote host name making this Request.
*/
@Override
public String getRemoteHost() {
if (remoteHost == null) {
if (!connector.getEnableLookups()) {
remoteHost = getRemoteAddr();
} else {
coyoteRequest.action
(ActionCode.REQ_HOST_ATTRIBUTE, coyoteRequest);
remoteHost = coyoteRequest.remoteHost().toString();
}
}
return remoteHost;
}
/**
* Returns the Internet Protocol (IP) source port of the client
* or last proxy that sent the request.
*/
@Override
public int getRemotePort(){
if (remotePort == -1) {
coyoteRequest.action
(ActionCode.REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest);
remotePort = coyoteRequest.getRemotePort();
}
return remotePort;
}
/**
* Returns the host name of the Internet Protocol (IP) interface on
* which the request was received.
*/
@Override
public String getLocalName(){
if (localName == null) {
coyoteRequest.action
(ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest);
localName = coyoteRequest.localName().toString();
}
return localName;
}
/**
* Returns the Internet Protocol (IP) address of the interface on
* which the request was received.
*/
@Override
public String getLocalAddr(){
if (localAddr == null) {
coyoteRequest.action
(ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest);
localAddr = coyoteRequest.localAddr().toString();
}
return localAddr;
}
/**
* Returns the Internet Protocol (IP) port number of the interface
* on which the request was received.
*/
@Override
public int getLocalPort(){
if (localPort == -1){
coyoteRequest.action
(ActionCode.REQ_LOCALPORT_ATTRIBUTE, coyoteRequest);
localPort = coyoteRequest.getLocalPort();
}
return localPort;
}
/**
* Return a RequestDispatcher that wraps the resource at the specified
* path, which may be interpreted as relative to the current request path.
*
* @param path Path of the resource to be wrapped
*/
@Override
public RequestDispatcher getRequestDispatcher(String path) {
if (context == null) {
return null;
}
// If the path is already context-relative, just pass it through
if (path == null) {
return null;
} else if (path.startsWith("/")) {
return (context.getServletContext().getRequestDispatcher(path));
}
// Convert a request-relative path to a context-relative one
String servletPath = (String) getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
if (servletPath == null) {
servletPath = getServletPath();
}
// Add the path info, if there is any
String pathInfo = getPathInfo();
String requestPath = null;
if (pathInfo == null) {
requestPath = servletPath;
} else {
requestPath = servletPath + pathInfo;
}
int pos = requestPath.lastIndexOf('/');
String relative = null;
if (pos >= 0) {
relative = requestPath.substring(0, pos + 1) + path;
} else {
relative = requestPath + path;
}
return context.getServletContext().getRequestDispatcher(relative);
}
/**
* Return the scheme used to make this Request.
*/
@Override
public String getScheme() {
return coyoteRequest.scheme().toString();
}
/**
* Return the server name responding to this Request.
*/
@Override
public String getServerName() {
return coyoteRequest.serverName().toString();
}
/**
* Return the server port responding to this Request.
*/
@Override
public int getServerPort() {
return coyoteRequest.getServerPort();
}
/**
* Was this request received on a secure connection?
*/
@Override
public boolean isSecure() {
return secure;
}
/**
* Remove the specified request attribute if it exists.
*
* @param name Name of the request attribute to remove
*/
@Override
public void removeAttribute(String name) {
// Remove the specified attribute
// Check for read only attribute
// requests are per thread so synchronization unnecessary
if (readOnlyAttributes.containsKey(name)) {
return;
}
// Pass special attributes to the native layer
if (name.startsWith("org.apache.tomcat.")) {
coyoteRequest.getAttributes().remove(name);
}
boolean found = attributes.containsKey(name);
if (found) {
Object value = attributes.get(name);
attributes.remove(name);
// Notify interested application event listeners
notifyAttributeRemoved(name, value);
} else {
return;
}
}
/**
* Set the specified request attribute to the specified value.
*
* @param name Name of the request attribute to set
* @param value The associated value
*/
@Override
public void setAttribute(String name, Object value) {
// Name cannot be null
if (name == null) {
throw new IllegalArgumentException
(sm.getString("coyoteRequest.setAttribute.namenull"));
}
// Null value is the same as removeAttribute()
if (value == null) {
removeAttribute(name);
return;
}
// Special attributes
SpecialAttributeAdapter adapter = specialAttributes.get(name);
if (adapter != null) {
adapter.set(this, name, value);
return;
}
// Add or replace the specified attribute
// Check for read only attribute
// requests are per thread so synchronization unnecessary
if (readOnlyAttributes.containsKey(name)) {
return;
}
// Do the security check before any updates are made
if (Globals.IS_SECURITY_ENABLED &&
name.equals(Globals.SENDFILE_FILENAME_ATTR)) {
// Use the canonical file name to avoid any possible symlink and
// relative path issues
String canonicalPath;
try {
canonicalPath = new File(value.toString()).getCanonicalPath();
} catch (IOException e) {
throw new SecurityException(sm.getString(
"coyoteRequest.sendfileNotCanonical", value), e);
}
// Sendfile is performed in Tomcat's security context so need to
// check if the web app is permitted to access the file while still
// in the web app's security context
System.getSecurityManager().checkRead(canonicalPath);
// Update the value so the canonical path is used
value = canonicalPath;
}
Object oldValue = attributes.put(name, value);
// Pass special attributes to the native layer
if (name.startsWith("org.apache.tomcat.")) {
coyoteRequest.setAttribute(name, value);
}
// Notify interested application event listeners
notifyAttributeAssigned(name, value, oldValue);
}
/**
* Notify interested listeners that attribute has been assigned a value.
*/
private void notifyAttributeAssigned(String name, Object value,
Object oldValue) {
Object listeners[] = context.getApplicationEventListeners();
if ((listeners == null) || (listeners.length == 0)) {
return;
}
boolean replaced = (oldValue != null);
ServletRequestAttributeEvent event = null;
if (replaced) {
event = new ServletRequestAttributeEvent(
context.getServletContext(), getRequest(), name, oldValue);
} else {
event = new ServletRequestAttributeEvent(
context.getServletContext(), getRequest(), name, value);
}
for (int i = 0; i < listeners.length; i++) {
if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
continue;
}
ServletRequestAttributeListener listener =
(ServletRequestAttributeListener) listeners[i];
try {
if (replaced) {
listener.attributeReplaced(event);
} else {
listener.attributeAdded(event);
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
// Error valve will pick this exception up and display it to user
attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
}
}
}
/**
* Notify interested listeners that attribute has been removed.
*/
private void notifyAttributeRemoved(String name, Object value) {
Object listeners[] = context.getApplicationEventListeners();
if ((listeners == null) || (listeners.length == 0)) {
return;
}
ServletRequestAttributeEvent event =
new ServletRequestAttributeEvent(context.getServletContext(),
getRequest(), name, value);
for (int i = 0; i < listeners.length; i++) {
if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
continue;
}
ServletRequestAttributeListener listener =
(ServletRequestAttributeListener) listeners[i];
try {
listener.attributeRemoved(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
// Error valve will pick this exception up and display it to user
attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
}
}
}
/**
* Overrides the name of the character encoding used in the body of
* this request. This method must be called prior to reading request
* parameters or reading input using <code>getReader()</code>.
*
* @param enc The character encoding to be used
*
* @exception UnsupportedEncodingException if the specified encoding
* is not supported
*
* @since Servlet 2.3
*/
@Override
public void setCharacterEncoding(String enc)
throws UnsupportedEncodingException {
if (usingReader) {
return;
}
// Ensure that the specified encoding is valid
byte buffer[] = new byte[1];
buffer[0] = (byte) 'a';
// Confirm that the encoding name is valid
B2CConverter.getCharset(enc);
// Save the validated encoding
coyoteRequest.setCharacterEncoding(enc);
}
@Override
public ServletContext getServletContext() {
return context.getServletContext();
}
@Override
public AsyncContext startAsync() {
return startAsync(getRequest(),response.getResponse());
}
@Override
public AsyncContext startAsync(ServletRequest request,
ServletResponse response) {
if (!isAsyncSupported()) {
throw new IllegalStateException("Not supported.");
}
if (asyncContext == null) {
asyncContext = new AsyncContextImpl(this);
}
asyncContext.setStarted(getContext(), request, response,
request==getRequest() && response==getResponse().getResponse());
asyncContext.setTimeout(getConnector().getAsyncTimeout());
return asyncContext;
}
@Override
public boolean isAsyncStarted() {
if (asyncContext == null) {
return false;
}
return asyncContext.isStarted();
}
public boolean isAsyncDispatching() {
if (asyncContext == null) {
return false;
}
AtomicBoolean result = new AtomicBoolean(false);
coyoteRequest.action(ActionCode.ASYNC_IS_DISPATCHING, result);
return result.get();
}
public boolean isAsync() {
if (asyncContext == null) {
return false;
}
AtomicBoolean result = new AtomicBoolean(false);
coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC, result);
return result.get();
}
@Override
public boolean isAsyncSupported() {
if (this.asyncSupported == null) {
return true;
}
return asyncSupported.booleanValue();
}
@Override
public AsyncContext getAsyncContext() {
return this.asyncContext;
}
@Override
public DispatcherType getDispatcherType() {
if (internalDispatcherType == null) {
return DispatcherType.REQUEST;
}
return this.internalDispatcherType;
}
// ---------------------------------------------------- HttpRequest Methods
/**
* Add a Cookie to the set of Cookies associated with this Request.
*
* @param cookie The new cookie
*/
public void addCookie(Cookie cookie) {
if (!cookiesParsed) {
parseCookies();
}
int size = 0;
if (cookies != null) {
size = cookies.length;
}
Cookie[] newCookies = new Cookie[size + 1];
for (int i = 0; i < size; i++) {
newCookies[i] = cookies[i];
}
newCookies[size] = cookie;
cookies = newCookies;
}
/**
* Add a Locale to the set of preferred Locales for this Request. The
* first added Locale will be the first one returned by getLocales().
*
* @param locale The new preferred Locale
*/
public void addLocale(Locale locale) {
locales.add(locale);
}
/**
* Clear the collection of Cookies associated with this Request.
*/
public void clearCookies() {
cookiesParsed = true;
cookies = null;
}
/**
* Clear the collection of Locales associated with this Request.
*/
public void clearLocales() {
locales.clear();
}
/**
* Set the authentication type used for this request, if any; otherwise
* set the type to <code>null</code>. Typical values are "BASIC",
* "DIGEST", or "SSL".
*
* @param type The authentication type used
*/
public void setAuthType(String type) {
this.authType = type;
}
/**
* Set the path information for this Request. This will normally be called
* when the associated Context is mapping the Request to a particular
* Wrapper.
*
* @param path The path information
*/
public void setPathInfo(String path) {
mappingData.pathInfo.setString(path);
}
/**
* Set a flag indicating whether or not the requested session ID for this
* request came in through a cookie. This is normally called by the
* HTTP Connector, when it parses the request headers.
*
* @param flag The new flag
*/
public void setRequestedSessionCookie(boolean flag) {
this.requestedSessionCookie = flag;
}
/**
* Set the requested session ID for this request. This is normally called
* by the HTTP Connector, when it parses the request headers.
*
* @param id The new session id
*/
public void setRequestedSessionId(String id) {
this.requestedSessionId = id;
}
/**
* Set a flag indicating whether or not the requested session ID for this
* request came in through a URL. This is normally called by the
* HTTP Connector, when it parses the request headers.
*
* @param flag The new flag
*/
public void setRequestedSessionURL(boolean flag) {
this.requestedSessionURL = flag;
}
/**
* Set a flag indicating whether or not the requested session ID for this
* request came in through SSL. This is normally called by the
* HTTP Connector, when it parses the request headers.
*
* @param flag The new flag
*/
public void setRequestedSessionSSL(boolean flag) {
this.requestedSessionSSL = flag;
}
/**
* Get the decoded request URI.
*
* @return the URL decoded request URI
*/
public String getDecodedRequestURI() {
return coyoteRequest.decodedURI().toString();
}
/**
* Get the decoded request URI.
*
* @return the URL decoded request URI
*/
public MessageBytes getDecodedRequestURIMB() {
return coyoteRequest.decodedURI();
}
/**
* Set the Principal who has been authenticated for this Request. This
* value is also used to calculate the value to be returned by the
* <code>getRemoteUser()</code> method.
*
* @param principal The user Principal
*/
public void setUserPrincipal(Principal principal) {
if (Globals.IS_SECURITY_ENABLED){
HttpSession session = getSession(false);
if ( (subject != null) &&
(!subject.getPrincipals().contains(principal)) ){
subject.getPrincipals().add(principal);
} else if (session != null &&
session.getAttribute(Globals.SUBJECT_ATTR) == null) {
subject = new Subject();
subject.getPrincipals().add(principal);
}
if (session != null){
session.setAttribute(Globals.SUBJECT_ATTR, subject);
}
}
this.userPrincipal = principal;
}
// --------------------------------------------- HttpServletRequest Methods
/**
* {@inheritDoc}
*
* @since Servlet 3.1
*/
@SuppressWarnings("unchecked")
@Override
public <T extends HttpUpgradeHandler> T upgrade(
Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException {
T handler;
try {
handler = (T) context.getInstanceManager().newInstance(httpUpgradeHandlerClass);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NamingException e) {
throw new ServletException(e);
}
coyoteRequest.action(ActionCode.UPGRADE, handler);
// Output required by RFC2616. Protocol specific headers should have
// already been set.
response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
return handler;
}
/**
* Return the authentication type used for this Request.
*/
@Override
public String getAuthType() {
return authType;
}
/**
* Return the portion of the request URI used to select the Context
* of the Request.
*/
@Override
public String getContextPath() {
return mappingData.contextPath.toString();
}
/**
* Return the set of Cookies received with this Request.
*/
@Override
public Cookie[] getCookies() {
if (!cookiesParsed) {
parseCookies();
}
return cookies;
}
/**
* Return the value of the specified date header, if any; otherwise
* return -1.
*
* @param name Name of the requested date header
*
* @exception IllegalArgumentException if the specified header value
* cannot be converted to a date
*/
@Override
public long getDateHeader(String name) {
String value = getHeader(name);
if (value == null) {
return (-1L);
}
// Attempt to convert the date header in a variety of formats
long result = FastHttpDateFormat.parseDate(value, formats);
if (result != (-1L)) {
return result;
}
throw new IllegalArgumentException(value);
}
/**
* Return the first value of the specified header, if any; otherwise,
* return <code>null</code>
*
* @param name Name of the requested header
*/
@Override
public String getHeader(String name) {
return coyoteRequest.getHeader(name);
}
/**
* Return all of the values of the specified header, if any; otherwise,
* return an empty enumeration.
*
* @param name Name of the requested header
*/
@Override
public Enumeration<String> getHeaders(String name) {
return coyoteRequest.getMimeHeaders().values(name);
}
/**
* Return the names of all headers received with this request.
*/
@Override
public Enumeration<String> getHeaderNames() {
return coyoteRequest.getMimeHeaders().names();
}
/**
* Return the value of the specified header as an integer, or -1 if there
* is no such header for this request.
*
* @param name Name of the requested header
*
* @exception IllegalArgumentException if the specified header value
* cannot be converted to an integer
*/
@Override
public int getIntHeader(String name) {
String value = getHeader(name);
if (value == null) {
return (-1);
}
return Integer.parseInt(value);
}
/**
* Return the HTTP request method used in this Request.
*/
@Override
public String getMethod() {
return coyoteRequest.method().toString();
}
/**
* Return the path information associated with this Request.
*/
@Override
public String getPathInfo() {
return mappingData.pathInfo.toString();
}
/**
* Return the extra path information for this request, translated
* to a real path.
*/
@Override
public String getPathTranslated() {
if (context == null) {
return null;
}
if (getPathInfo() == null) {
return null;
}
return context.getServletContext().getRealPath(getPathInfo());
}
/**
* Return the query string associated with this request.
*/
@Override
public String getQueryString() {
return coyoteRequest.queryString().toString();
}
/**
* Return the name of the remote user that has been authenticated
* for this Request.
*/
@Override
public String getRemoteUser() {
if (userPrincipal == null) {
return null;
}
return userPrincipal.getName();
}
/**
* Get the request path.
*
* @return the request path
*/
public MessageBytes getRequestPathMB() {
return mappingData.requestPath;
}
/**
* Return the session identifier included in this request, if any.
*/
@Override
public String getRequestedSessionId() {
return requestedSessionId;
}
/**
* Return the request URI for this request.
*/
@Override
public String getRequestURI() {
return coyoteRequest.requestURI().toString();
}
/**
* Reconstructs the URL the client used to make the request.
* The returned URL contains a protocol, server name, port
* number, and server path, but it does not include query
* string parameters.
* <p>
* Because this method returns a <code>StringBuffer</code>,
* not a <code>String</code>, you can modify the URL easily,
* for example, to append query parameters.
* <p>
* This method is useful for creating redirect messages and
* for reporting errors.
*
* @return A <code>StringBuffer</code> object containing the
* reconstructed URL
*/
@Override
public StringBuffer getRequestURL() {
StringBuffer url = new StringBuffer();
String scheme = getScheme();
int port = getServerPort();
if (port < 0)
{
port = 80; // Work around java.net.URL bug
}
url.append(scheme);
url.append("://");
url.append(getServerName());
if ((scheme.equals("http") && (port != 80))
|| (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
url.append(getRequestURI());
return url;
}
/**
* Return the portion of the request URI used to select the servlet
* that will process this request.
*/
@Override
public String getServletPath() {
return (mappingData.wrapperPath.toString());
}
/**
* Return the session associated with this Request, creating one
* if necessary.
*/
@Override
public HttpSession getSession() {
Session session = doGetSession(true);
if (session == null) {
return null;
}
return session.getSession();
}
/**
* Return the session associated with this Request, creating one
* if necessary and requested.
*
* @param create Create a new session if one does not exist
*/
@Override
public HttpSession getSession(boolean create) {
Session session = doGetSession(create);
if (session == null) {
return null;
}
return session.getSession();
}
/**
* Return <code>true</code> if the session identifier included in this
* request came from a cookie.
*/
@Override
public boolean isRequestedSessionIdFromCookie() {
if (requestedSessionId == null) {
return false;
}
return requestedSessionCookie;
}
/**
* Return <code>true</code> if the session identifier included in this
* request came from the request URI.
*/
@Override
public boolean isRequestedSessionIdFromURL() {
if (requestedSessionId == null) {
return false;
}
return requestedSessionURL;
}
/**
* Return <code>true</code> if the session identifier included in this
* request came from the request URI.
*
* @deprecated As of Version 2.1 of the Java Servlet API, use
* <code>isRequestedSessionIdFromURL()</code> instead.
*/
@Override
@Deprecated
public boolean isRequestedSessionIdFromUrl() {
return (isRequestedSessionIdFromURL());
}
/**
* Return <code>true</code> if the session identifier included in this
* request identifies a valid session.
*/
@Override
public boolean isRequestedSessionIdValid() {
if (requestedSessionId == null) {
return false;
}
if (context == null) {
return false;
}
Manager manager = context.getManager();
if (manager == null) {
return false;
}
Session session = null;
try {
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
// Can't find the session
}
if ((session == null) || !session.isValid()) {
// Check for parallel deployment contexts
if (getMappingData().contexts == null) {
return false;
} else {
for (int i = (getMappingData().contexts.length); i > 0; i--) {
Context ctxt = getMappingData().contexts[i - 1];
try {
if (ctxt.getManager().findSession(requestedSessionId) !=
null) {
return true;
}
} catch (IOException e) {
// Ignore
}
}
return false;
}
}
return true;
}
/**
* Return <code>true</code> if the authenticated user principal
* possesses the specified role name.
*
* @param role Role name to be validated
*/
@Override
public boolean isUserInRole(String role) {
// Have we got an authenticated principal at all?
if (userPrincipal == null) {
return false;
}
// Identify the Realm we will use for checking role assignments
if (context == null) {
return false;
}
// If the role is "*" then the return value must be false
// Servlet 31, section 13.3
if ("*".equals(role)) {
return false;
}
// If the role is "**" then, unless the application defines a role with
// that name, only check if the user is authenticated
if ("**".equals(role) && !context.findSecurityRole("**")) {
return userPrincipal != null;
}
Realm realm = context.getRealm();
if (realm == null) {
return false;
}
// Check for a role defined directly as a <security-role>
return (realm.hasRole(wrapper, userPrincipal, role));
}
/**
* Return the principal that has been authenticated for this Request.
*/
public Principal getPrincipal() {
return userPrincipal;
}
/**
* Return the principal that has been authenticated for this Request.
*/
@Override
public Principal getUserPrincipal() {
if (userPrincipal instanceof TomcatPrincipal) {
return ((TomcatPrincipal) userPrincipal).getUserPrincipal();
}
return userPrincipal;
}
/**
* Return the session associated with this Request, creating one
* if necessary.
*/
public Session getSessionInternal() {
return doGetSession(true);
}
/**
* Change the ID of the session that this request is associated with. There
* are several things that may trigger an ID change. These include moving
* between nodes in a cluster and session fixation prevention during the
* authentication process.
*
* @param newSessionId The session to change the session ID for
*/
public void changeSessionId(String newSessionId) {
// This should only ever be called if there was an old session ID but
// double check to be sure
if (requestedSessionId != null && requestedSessionId.length() > 0) {
requestedSessionId = newSessionId;
}
if (context != null && !context.getServletContext()
.getEffectiveSessionTrackingModes().contains(
SessionTrackingMode.COOKIE)) {
return;
}
if (response != null) {
Cookie newCookie =
ApplicationSessionCookieConfig.createSessionCookie(context,
newSessionId, secure);
response.addSessionCookieInternal(newCookie);
}
}
/**
* Changes the session ID of the session associated with this request.
*
* @return the old session ID before it was changed
* @see javax.servlet.http.HttpSessionIdListener
* @since Servlet 3.1
*/
@Override
public String changeSessionId() {
Session session = this.getSessionInternal(false);
if (session == null) {
throw new IllegalStateException(
sm.getString("coyoteRequest.changeSessionId"));
}
Manager manager = this.getContext().getManager();
manager.changeSessionId(session);
String newSessionId = session.getId();
this.changeSessionId(newSessionId);
return newSessionId;
}
/**
* Return the session associated with this Request, creating one
* if necessary and requested.
*
* @param create Create a new session if one does not exist
*/
public Session getSessionInternal(boolean create) {
return doGetSession(create);
}
/**
* Get the event associated with the request.
* @return the event
*/
public CometEventImpl getEvent() {
if (event == null) {
event = new CometEventImpl(this, response);
}
return event;
}
/**
* Return true if the current request is handling Comet traffic.
*/
public boolean isComet() {
return comet;
}
/**
* Set comet state.
*/
public void setComet(boolean comet) {
this.comet = comet;
}
/**
* return true if we have parsed parameters
*/
public boolean isParametersParsed() {
return parametersParsed;
}
/**
* Return true if bytes are available.
*/
public boolean getAvailable() {
return (inputBuffer.available() > 0);
}
/**
* Return true if an attempt has been made to read the request body and all
* of the request body has been read
*/
public boolean isFinished() {
AtomicBoolean result = new AtomicBoolean(false);
coyoteRequest.action(ActionCode.REQUEST_BODY_FULLY_READ, result);
return result.get();
}
/**
* Disable swallowing of remaining input if configured
*/
protected void checkSwallowInput() {
Context context = getContext();
if (context != null && !context.getSwallowAbortedUploads()) {
coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null);
}
}
public void cometClose() {
coyoteRequest.action(ActionCode.COMET_CLOSE,getEvent());
setComet(false);
}
public void setCometTimeout(long timeout) {
coyoteRequest.action(ActionCode.COMET_SETTIMEOUT, Long.valueOf(timeout));
}
/**
* @throws IOException If an I/O error occurs
* @throws IllegalStateException If the response has been committed
* @throws ServletException If the caller is responsible for handling the
* error and the container has NOT set the HTTP response code etc.
*/
@Override
public boolean authenticate(HttpServletResponse response)
throws IOException, ServletException {
if (response.isCommitted()) {
throw new IllegalStateException(
sm.getString("coyoteRequest.authenticate.ise"));
}
return context.getAuthenticator().authenticate(this, response);
}
/**
* {@inheritDoc}
*/
@Override
public void login(String username, String password)
throws ServletException {
if (getAuthType() != null || getRemoteUser() != null ||
getUserPrincipal() != null) {
throw new ServletException(
sm.getString("coyoteRequest.alreadyAuthenticated"));
}
if (context.getAuthenticator() == null) {
throw new ServletException("no authenticator");
}
context.getAuthenticator().login(username, password, this);
}
/**
* {@inheritDoc}
*/
@Override
public void logout() throws ServletException {
context.getAuthenticator().logout(this);
}
/**
* {@inheritDoc}
*/
@Override
public Collection<Part> getParts() throws IOException, IllegalStateException,
ServletException {
parseParts();
if (partsParseException != null) {
if (partsParseException instanceof IOException) {
throw (IOException) partsParseException;
} else if (partsParseException instanceof IllegalStateException) {
throw (IllegalStateException) partsParseException;
} else if (partsParseException instanceof ServletException) {
throw (ServletException) partsParseException;
}
}
return parts;
}
private void parseParts() {
// Return immediately if the parts have already been parsed
if (parts != null || partsParseException != null) {
return;
}
MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
if (mce == null) {
if(getContext().getAllowCasualMultipartParsing()) {
mce = new MultipartConfigElement(null,
connector.getMaxPostSize(),
connector.getMaxPostSize(),
connector.getMaxPostSize());
} else {
parts = Collections.emptyList();
return;
}
}
Parameters parameters = coyoteRequest.getParameters();
parameters.setLimit(getConnector().getMaxParameterCount());
boolean success = false;
try {
File location;
String locationStr = mce.getLocation();
if (locationStr == null || locationStr.length() == 0) {
location = ((File) context.getServletContext().getAttribute(
ServletContext.TEMPDIR));
} else {
// If relative, it is relative to TEMPDIR
location = new File(locationStr);
if (!location.isAbsolute()) {
location = new File(
(File) context.getServletContext().getAttribute(
ServletContext.TEMPDIR),
locationStr).getAbsoluteFile();
}
}
if (!location.isDirectory()) {
partsParseException = new IOException(
sm.getString("coyoteRequest.uploadLocationInvalid",
location));
return;
}
// Create a new file upload handler
DiskFileItemFactory factory = new DiskFileItemFactory();
try {
factory.setRepository(location.getCanonicalFile());
} catch (IOException ioe) {
partsParseException = ioe;
return;
}
factory.setSizeThreshold(mce.getFileSizeThreshold());
ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(factory);
upload.setFileSizeMax(mce.getMaxFileSize());
upload.setSizeMax(mce.getMaxRequestSize());
parts = new ArrayList<>();
try {
List<FileItem> items =
upload.parseRequest(new ServletRequestContext(this));
int maxPostSize = getConnector().getMaxPostSize();
int postSize = 0;
String enc = getCharacterEncoding();
Charset charset = null;
if (enc != null) {
try {
charset = B2CConverter.getCharset(enc);
} catch (UnsupportedEncodingException e) {
// Ignore
}
}
for (FileItem item : items) {
ApplicationPart part = new ApplicationPart(item, location);
parts.add(part);
if (part.getSubmittedFileName() == null) {
String name = part.getName();
String value = null;
try {
String encoding = parameters.getEncoding();
if (encoding == null) {
if (enc == null) {
encoding = Parameters.DEFAULT_ENCODING;
} else {
encoding = enc;
}
}
value = part.getString(encoding);
} catch (UnsupportedEncodingException uee) {
try {
value = part.getString(Parameters.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
// Should not be possible
}
}
if (maxPostSize > 0) {
// Have to calculate equivalent size. Not completely
// accurate but close enough.
if (charset == null) {
// Name length
postSize += name.getBytes().length;
} else {
postSize += name.getBytes(charset).length;
}
if (value != null) {
// Equals sign
postSize++;
// Value length
postSize += part.getSize();
}
// Value separator
postSize++;
if (postSize > maxPostSize) {
throw new IllegalStateException(sm.getString(
"coyoteRequest.maxPostSizeExceeded"));
}
}
parameters.addParameter(name, value);
}
}
success = true;
} catch (InvalidContentTypeException e) {
partsParseException = new ServletException(e);
} catch (FileUploadBase.SizeException e) {
checkSwallowInput();
partsParseException = new IllegalStateException(e);
} catch (FileUploadException e) {
partsParseException = new IOException(e);
} catch (IllegalStateException e) {
checkSwallowInput();
partsParseException = e;
}
} finally {
if (partsParseException != null || !success) {
parameters.setParseFailed(true);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Part getPart(String name) throws IOException, IllegalStateException,
ServletException {
Collection<Part> c = getParts();
Iterator<Part> iterator = c.iterator();
while (iterator.hasNext()) {
Part part = iterator.next();
if (name.equals(part.getName())) {
return part;
}
}
return null;
}
// ------------------------------------------------------ Protected Methods
protected Session doGetSession(boolean create) {
// There cannot be a session if no context has been assigned yet
if (context == null) {
return (null);
}
// Return the current session if it exists and is valid
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
return (session);
}
// Return the requested session if it exists and is valid
Manager manager = null;
if (context != null) {
manager = context.getManager();
}
if (manager == null)
{
return (null); // Sessions are not supported
}
if (requestedSessionId != null) {
try {
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null;
}
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
session.access();
return (session);
}
}
// Create a new session if requested and the response is not committed
if (!create) {
return (null);
}
if ((context != null) && (response != null) &&
context.getServletContext().getEffectiveSessionTrackingModes().
contains(SessionTrackingMode.COOKIE) &&
response.getResponse().isCommitted()) {
throw new IllegalStateException
(sm.getString("coyoteRequest.sessionCreateCommitted"));
}
// Attempt to reuse session id if one was submitted in a cookie
// Do not reuse the session id if it is from a URL, to prevent possible
// phishing attacks
// Use the SSL session ID if one is present.
if (("/".equals(context.getSessionCookiePath())
&& isRequestedSessionIdFromCookie()) || requestedSessionSSL ) {
session = manager.createSession(getRequestedSessionId());
} else {
session = manager.createSession(null);
}
// Creating a new session cookie based on that session
if ((session != null) && (getContext() != null)
&& getContext().getServletContext().
getEffectiveSessionTrackingModes().contains(
SessionTrackingMode.COOKIE)) {
Cookie cookie =
ApplicationSessionCookieConfig.createSessionCookie(
context, session.getIdInternal(), isSecure());
response.addSessionCookieInternal(cookie);
}
if (session == null) {
return null;
}
session.access();
return session;
}
protected String unescape(String s) {
if (s==null) {
return null;
}
if (s.indexOf('\\') == -1) {
return s;
}
StringBuilder buf = new StringBuilder();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c!='\\') {
buf.append(c);
} else {
if (++i >= s.length())
{
throw new IllegalArgumentException();//invalid escape, hence invalid cookie
}
c = s.charAt(i);
buf.append(c);
}
}
return buf.toString();
}
/**
* Parse cookies.
*/
protected void parseCookies() {
cookiesParsed = true;
Cookies serverCookies = coyoteRequest.getCookies();
int count = serverCookies.getCookieCount();
if (count <= 0) {
return;
}
cookies = new Cookie[count];
int idx=0;
for (int i = 0; i < count; i++) {
ServerCookie scookie = serverCookies.getCookie(i);
try {
/*
we must unescape the '\\' escape character
*/
Cookie cookie = new Cookie(scookie.getName().toString(),null);
int version = scookie.getVersion();
cookie.setVersion(version);
cookie.setValue(unescape(scookie.getValue().toString()));
cookie.setPath(unescape(scookie.getPath().toString()));
String domain = scookie.getDomain().toString();
if (domain!=null)
{
cookie.setDomain(unescape(domain));//avoid NPE
}
String comment = scookie.getComment().toString();
cookie.setComment(version==1?unescape(comment):null);
cookies[idx++] = cookie;
} catch(IllegalArgumentException e) {
// Ignore bad cookie
}
}
if( idx < count ) {
Cookie [] ncookies = new Cookie[idx];
System.arraycopy(cookies, 0, ncookies, 0, idx);
cookies = ncookies;
}
}
/**
* Parse request parameters.
*/
protected void parseParameters() {
parametersParsed = true;
Parameters parameters = coyoteRequest.getParameters();
boolean success = false;
try {
// Set this every time in case limit has been changed via JMX
parameters.setLimit(getConnector().getMaxParameterCount());
// getCharacterEncoding() may have been overridden to search for
// hidden form field containing request encoding
String enc = getCharacterEncoding();
boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();
if (enc != null) {
parameters.setEncoding(enc);
if (useBodyEncodingForURI) {
parameters.setQueryStringEncoding(enc);
}
} else {
parameters.setEncoding
(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);
if (useBodyEncodingForURI) {
parameters.setQueryStringEncoding
(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);
}
}
parameters.handleQueryParameters();
if (usingInputStream || usingReader) {
success = true;
return;
}
if( !getConnector().isParseBodyMethod(getMethod()) ) {
success = true;
return;
}
String contentType = getContentType();
if (contentType == null) {
contentType = "";
}
int semicolon = contentType.indexOf(';');
if (semicolon >= 0) {
contentType = contentType.substring(0, semicolon).trim();
} else {
contentType = contentType.trim();
}
if ("multipart/form-data".equals(contentType)) {
parseParts();
success = true;
return;
}
if (!("application/x-www-form-urlencoded".equals(contentType))) {
success = true;
return;
}
int len = getContentLength();
if (len > 0) {
int maxPostSize = connector.getMaxPostSize();
if ((maxPostSize > 0) && (len > maxPostSize)) {
if (context.getLogger().isDebugEnabled()) {
context.getLogger().debug(
sm.getString("coyoteRequest.postTooLarge"));
}
checkSwallowInput();
return;
}
byte[] formData = null;
if (len < CACHED_POST_LEN) {
if (postData == null) {
postData = new byte[CACHED_POST_LEN];
}
formData = postData;
} else {
formData = new byte[len];
}
try {
if (readPostBody(formData, len) != len) {
return;
}
} catch (IOException e) {
// Client disconnect
if (context.getLogger().isDebugEnabled()) {
context.getLogger().debug(
sm.getString("coyoteRequest.parseParameters"), e);
}
return;
}
parameters.processParameters(formData, 0, len);
} else if ("chunked".equalsIgnoreCase(
coyoteRequest.getHeader("transfer-encoding"))) {
byte[] formData = null;
try {
formData = readChunkedPostBody();
} catch (IOException e) {
// Client disconnect or chunkedPostTooLarge error
if (context.getLogger().isDebugEnabled()) {
context.getLogger().debug(
sm.getString("coyoteRequest.parseParameters"), e);
}
return;
}
if (formData != null) {
parameters.processParameters(formData, 0, formData.length);
}
}
success = true;
} finally {
if (!success) {
parameters.setParseFailed(true);
}
}
}
/**
* Read post body in an array.
*/
protected int readPostBody(byte body[], int len)
throws IOException {
int offset = 0;
do {
int inputLen = getStream().read(body, offset, len - offset);
if (inputLen <= 0) {
return offset;
}
offset += inputLen;
} while ((len - offset) > 0);
return len;
}
/**
* Read chunked post body.
*/
protected byte[] readChunkedPostBody() throws IOException {
ByteChunk body = new ByteChunk();
byte[] buffer = new byte[CACHED_POST_LEN];
int len = 0;
while (len > -1) {
len = getStream().read(buffer, 0, CACHED_POST_LEN);
if (connector.getMaxPostSize() > 0 &&
(body.getLength() + len) > connector.getMaxPostSize()) {
// Too much data
checkSwallowInput();
throw new IOException(
sm.getString("coyoteRequest.chunkedPostTooLarge"));
}
if (len > 0) {
body.append(buffer, 0, len);
}
}
if (body.getLength() == 0) {
return null;
}
if (body.getLength() < body.getBuffer().length) {
int length = body.getLength();
byte[] result = new byte[length];
System.arraycopy(body.getBuffer(), 0, result, 0, length);
return result;
}
return body.getBuffer();
}
/**
* Parse request locales.
*/
protected void parseLocales() {
localesParsed = true;
Enumeration<String> values = getHeaders("accept-language");
while (values.hasMoreElements()) {
String value = values.nextElement();
parseLocalesHeader(value);
}
}
/**
* Parse accept-language header value.
*/
protected void parseLocalesHeader(String value) {
// Store the accumulated languages that have been requested in
// a local collection, sorted by the quality value (so we can
// add Locales in descending order). The values will be ArrayLists
// containing the corresponding Locales to be added
TreeMap<Double, ArrayList<Locale>> locales = new TreeMap<>();
// Preprocess the value to remove all whitespace
int white = value.indexOf(' ');
if (white < 0) {
white = value.indexOf('\t');
}
if (white >= 0) {
StringBuilder sb = new StringBuilder();
int len = value.length();
for (int i = 0; i < len; i++) {
char ch = value.charAt(i);
if ((ch != ' ') && (ch != '\t')) {
sb.append(ch);
}
}
parser.setString(sb.toString());
} else {
parser.setString(value);
}
// Process each comma-delimited language specification
int length = parser.getLength();
while (true) {
// Extract the next comma-delimited entry
int start = parser.getIndex();
if (start >= length) {
break;
}
int end = parser.findChar(',');
String entry = parser.extract(start, end).trim();
parser.advance(); // For the following entry
// Extract the quality factor for this entry
double quality = 1.0;
int semi = entry.indexOf(";q=");
if (semi >= 0) {
try {
String strQuality = entry.substring(semi + 3);
if (strQuality.length() <= 5) {
quality = Double.parseDouble(strQuality);
} else {
quality = 0.0;
}
} catch (NumberFormatException e) {
quality = 0.0;
}
entry = entry.substring(0, semi);
}
// Skip entries we are not going to keep track of
if (quality < 0.00005)
{
continue; // Zero (or effectively zero) quality factors
}
if ("*".equals(entry))
{
continue; // FIXME - "*" entries are not handled
}
// Extract the language and country for this entry
String language = null;
String country = null;
String variant = null;
int dash = entry.indexOf('-');
if (dash < 0) {
language = entry;
country = "";
variant = "";
} else {
language = entry.substring(0, dash);
country = entry.substring(dash + 1);
int vDash = country.indexOf('-');
if (vDash > 0) {
String cTemp = country.substring(0, vDash);
variant = country.substring(vDash + 1);
country = cTemp;
} else {
variant = "";
}
}
if (!isAlpha(language) || !isAlpha(country) || !isAlpha(variant)) {
continue;
}
// Add a new Locale to the list of Locales for this quality level
Locale locale = new Locale(language, country, variant);
Double key = new Double(-quality); // Reverse the order
ArrayList<Locale> values = locales.get(key);
if (values == null) {
values = new ArrayList<>();
locales.put(key, values);
}
values.add(locale);
}
// Process the quality values in highest->lowest order (due to
// negating the Double value when creating the key)
for (ArrayList<Locale> list : locales.values()) {
for (Locale locale : list) {
addLocale(locale);
}
}
}
protected static final boolean isAlpha(String value) {
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
return false;
}
}
return true;
}
// ----------------------------------------------------- Special attributes handling
private static interface SpecialAttributeAdapter {
Object get(Request request, String name);
void set(Request request, String name, Object value);
// None of special attributes support removal
// void remove(Request request, String name);
}
private static final Map<String, SpecialAttributeAdapter> specialAttributes
= new HashMap<>();
static {
specialAttributes.put(Globals.DISPATCHER_TYPE_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
return (request.internalDispatcherType == null) ? DispatcherType.REQUEST
: request.internalDispatcherType;
}
@Override
public void set(Request request, String name, Object value) {
request.internalDispatcherType = (DispatcherType) value;
}
});
specialAttributes.put(Globals.DISPATCHER_REQUEST_PATH_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
return (request.requestDispatcherPath == null) ? request
.getRequestPathMB().toString()
: request.requestDispatcherPath.toString();
}
@Override
public void set(Request request, String name, Object value) {
request.requestDispatcherPath = value;
}
});
specialAttributes.put(Globals.ASYNC_SUPPORTED_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
return request.asyncSupported;
}
@Override
public void set(Request request, String name, Object value) {
Boolean oldValue = request.asyncSupported;
request.asyncSupported = (Boolean)value;
request.notifyAttributeAssigned(name, value, oldValue);
}
});
specialAttributes.put(Globals.GSS_CREDENTIAL_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
if (request.userPrincipal instanceof TomcatPrincipal) {
return ((TomcatPrincipal) request.userPrincipal)
.getGssCredential();
}
return null;
}
@Override
public void set(Request request, String name, Object value) {
// NO-OP
}
});
specialAttributes.put(Globals.PARAMETER_PARSE_FAILED_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
if (request.getCoyoteRequest().getParameters()
.isParseFailed()) {
return Boolean.TRUE;
}
return null;
}
@Override
public void set(Request request, String name, Object value) {
// NO-OP
}
});
specialAttributes.put(Globals.COMET_SUPPORTED_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
return Boolean.valueOf(
request.getConnector().getProtocolHandler(
).isCometSupported());
}
@Override
public void set(Request request, String name, Object value) {
// NO-OP
}
});
specialAttributes.put(Globals.COMET_TIMEOUT_SUPPORTED_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
return Boolean.valueOf(
request.getConnector().getProtocolHandler(
).isCometTimeoutSupported());
}
@Override
public void set(Request request, String name, Object value) {
// NO-OP
}
});
specialAttributes.put(Globals.SENDFILE_SUPPORTED_ATTR,
new SpecialAttributeAdapter() {
@Override
public Object get(Request request, String name) {
return Boolean.valueOf(
request.getConnector().getProtocolHandler(
).isSendfileSupported());
}
@Override
public void set(Request request, String name, Object value) {
// NO-OP
}
});
}
}
|
55,438
|
Bug 55438 Non Blocking API's onAllDataRead being called twice
| null |
resolved fixed
|
7f6ea48
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-19T14:54:15Z
| 2013-08-16T21:53:20Z
|
java/org/apache/coyote/Request.java
|
/*
* 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.coyote;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.ReadListener;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.buf.UDecoder;
import org.apache.tomcat.util.http.Cookies;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.Parameters;
import org.apache.tomcat.util.res.StringManager;
/**
* This is a low-level, efficient representation of a server request. Most
* fields are GC-free, expensive operations are delayed until the user code
* needs the information.
*
* Processing is delegated to modules, using a hook mechanism.
*
* This class is not intended for user code - it is used internally by tomcat
* for processing the request in the most efficient way. Users ( servlets ) can
* access the information using a facade, which provides the high-level view
* of the request.
*
* Tomcat defines a number of attributes:
* <ul>
* <li>"org.apache.tomcat.request" - allows access to the low-level
* request object in trusted applications
* </ul>
*
* @author James Duncan Davidson [duncan@eng.sun.com]
* @author James Todd [gonzo@eng.sun.com]
* @author Jason Hunter [jch@eng.sun.com]
* @author Harish Prabandham
* @author Alex Cruikshank [alex@epitonic.com]
* @author Hans Bergsten [hans@gefionsoftware.com]
* @author Costin Manolache
* @author Remy Maucherat
*/
public final class Request {
private static final StringManager sm =
StringManager.getManager(Constants.Package);
// ----------------------------------------------------------- Constructors
public Request() {
parameters.setQuery(queryMB);
parameters.setURLDecoder(urlDecoder);
}
// ----------------------------------------------------- Instance Variables
private int serverPort = -1;
private final MessageBytes serverNameMB = MessageBytes.newInstance();
private int remotePort;
private int localPort;
private final MessageBytes schemeMB = MessageBytes.newInstance();
private final MessageBytes methodMB = MessageBytes.newInstance();
private final MessageBytes unparsedURIMB = MessageBytes.newInstance();
private final MessageBytes uriMB = MessageBytes.newInstance();
private final MessageBytes decodedUriMB = MessageBytes.newInstance();
private final MessageBytes queryMB = MessageBytes.newInstance();
private final MessageBytes protoMB = MessageBytes.newInstance();
// remote address/host
private final MessageBytes remoteAddrMB = MessageBytes.newInstance();
private final MessageBytes localNameMB = MessageBytes.newInstance();
private final MessageBytes remoteHostMB = MessageBytes.newInstance();
private final MessageBytes localAddrMB = MessageBytes.newInstance();
private final MimeHeaders headers = new MimeHeaders();
private final MessageBytes instanceId = MessageBytes.newInstance();
/**
* Notes.
*/
private final Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Associated input buffer.
*/
private InputBuffer inputBuffer = null;
/**
* URL decoder.
*/
private final UDecoder urlDecoder = new UDecoder();
/**
* HTTP specific fields. (remove them ?)
*/
private long contentLength = -1;
private MessageBytes contentTypeMB = null;
private String charEncoding = null;
private final Cookies cookies = new Cookies(headers);
private final Parameters parameters = new Parameters();
private final MessageBytes remoteUser=MessageBytes.newInstance();
private final MessageBytes authType=MessageBytes.newInstance();
private final HashMap<String,Object> attributes=new HashMap<>();
private Response response;
private ActionHook hook;
private int bytesRead=0;
// Time of the request - useful to avoid repeated calls to System.currentTime
private long startTime = -1;
private int available = 0;
private final RequestInfo reqProcessorMX=new RequestInfo(this);
protected volatile ReadListener listener;
public ReadListener getReadListener() {
return listener;
}
public void setReadListener(ReadListener listener) {
if (listener == null) {
throw new NullPointerException(
sm.getString("request.nullReadListener"));
}
if (getReadListener() != null) {
throw new IllegalStateException(
sm.getString("request.readListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
// for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
throw new IllegalStateException(
sm.getString("request.notAsync"));
}
this.listener = listener;
}
// ------------------------------------------------------------- Properties
/**
* Get the instance id (or JVM route). Currently Ajp is sending it with each
* request. In future this should be fixed, and sent only once ( or
* 'negotiated' at config time so both tomcat and apache share the same name.
*
* @return the instance id
*/
public MessageBytes instanceId() {
return instanceId;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public UDecoder getURLDecoder() {
return urlDecoder;
}
// -------------------- Request data --------------------
public MessageBytes scheme() {
return schemeMB;
}
public MessageBytes method() {
return methodMB;
}
public MessageBytes unparsedURI() {
return unparsedURIMB;
}
public MessageBytes requestURI() {
return uriMB;
}
public MessageBytes decodedURI() {
return decodedUriMB;
}
public MessageBytes queryString() {
return queryMB;
}
public MessageBytes protocol() {
return protoMB;
}
/**
* Return the buffer holding the server name, if
* any. Use isNull() to check if there is no value
* set.
* This is the "virtual host", derived from the
* Host: header.
*/
public MessageBytes serverName() {
return serverNameMB;
}
public int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort ) {
this.serverPort=serverPort;
}
public MessageBytes remoteAddr() {
return remoteAddrMB;
}
public MessageBytes remoteHost() {
return remoteHostMB;
}
public MessageBytes localName() {
return localNameMB;
}
public MessageBytes localAddr() {
return localAddrMB;
}
public int getRemotePort(){
return remotePort;
}
public void setRemotePort(int port){
this.remotePort = port;
}
public int getLocalPort(){
return localPort;
}
public void setLocalPort(int port){
this.localPort = port;
}
// -------------------- encoding/type --------------------
/**
* Get the character encoding used for this request.
*/
public String getCharacterEncoding() {
if (charEncoding != null) {
return charEncoding;
}
charEncoding = getCharsetFromContentType(getContentType());
return charEncoding;
}
public void setCharacterEncoding(String enc) {
this.charEncoding = enc;
}
public void setContentLength(int len) {
this.contentLength = len;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
if( contentLength > -1 ) {
return contentLength;
}
MessageBytes clB = headers.getUniqueValue("content-length");
contentLength = (clB == null || clB.isNull()) ? -1 : clB.getLong();
return contentLength;
}
public String getContentType() {
contentType();
if ((contentTypeMB == null) || contentTypeMB.isNull()) {
return null;
}
return contentTypeMB.toString();
}
public void setContentType(String type) {
contentTypeMB.setString(type);
}
public MessageBytes contentType() {
if (contentTypeMB == null) {
contentTypeMB = headers.getValue("content-type");
}
return contentTypeMB;
}
public void setContentType(MessageBytes mb) {
contentTypeMB=mb;
}
public String getHeader(String name) {
return headers.getHeader(name);
}
// -------------------- Associated response --------------------
public Response getResponse() {
return response;
}
public void setResponse( Response response ) {
this.response=response;
response.setRequest( this );
}
public void action(ActionCode actionCode, Object param) {
if( hook==null && response!=null ) {
hook=response.getHook();
}
if (hook != null) {
if( param==null ) {
hook.action(actionCode, this);
} else {
hook.action(actionCode, param);
}
}
}
// -------------------- Cookies --------------------
public Cookies getCookies() {
return cookies;
}
// -------------------- Parameters --------------------
public Parameters getParameters() {
return parameters;
}
// -------------------- Other attributes --------------------
// We can use notes for most - need to discuss what is of general interest
public void setAttribute( String name, Object o ) {
attributes.put( name, o );
}
public HashMap<String,Object> getAttributes() {
return attributes;
}
public Object getAttribute(String name ) {
return attributes.get(name);
}
public MessageBytes getRemoteUser() {
return remoteUser;
}
public MessageBytes getAuthType() {
return authType;
}
public int getAvailable() {
return available;
}
public void setAvailable(int available) {
this.available = available;
}
// -------------------- Input Buffer --------------------
public InputBuffer getInputBuffer() {
return inputBuffer;
}
public void setInputBuffer(InputBuffer inputBuffer) {
this.inputBuffer = inputBuffer;
}
/**
* Read data from the input buffer and put it into a byte chunk.
*
* The buffer is owned by the protocol implementation - it will be reused on the next read.
* The Adapter must either process the data in place or copy it to a separate buffer if it needs
* to hold it. In most cases this is done during byte->char conversions or via InputStream. Unlike
* InputStream, this interface allows the app to process data in place, without copy.
*
*/
public int doRead(ByteChunk chunk)
throws IOException {
int n = inputBuffer.doRead(chunk, this);
if (n > 0) {
bytesRead+=n;
}
return n;
}
// -------------------- debug --------------------
@Override
public String toString() {
return "R( " + requestURI().toString() + ")";
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
// -------------------- Per-Request "notes" --------------------
/**
* Used to store private data. Thread data could be used instead - but
* if you have the req, getting/setting a note is just a array access, may
* be faster than ThreadLocal for very frequent operations.
*
* Example use:
* Jk:
* HandlerRequest.HOSTBUFFER = 10 CharChunk, buffer for Host decoding
* WorkerEnv: SSL_CERT_NOTE=16 - MessageBytes containing the cert
*
* Catalina CoyoteAdapter:
* ADAPTER_NOTES = 1 - stores the HttpServletRequest object ( req/res)
*
* To avoid conflicts, note in the range 0 - 8 are reserved for the
* servlet container ( catalina connector, etc ), and values in 9 - 16
* for connector use.
*
* 17-31 range is not allocated or used.
*/
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Recycling --------------------
public void recycle() {
bytesRead=0;
contentLength = -1;
contentTypeMB = null;
charEncoding = null;
headers.recycle();
serverNameMB.recycle();
serverPort=-1;
localNameMB.recycle();
localPort = -1;
remotePort = -1;
available = 0;
cookies.recycle();
parameters.recycle();
unparsedURIMB.recycle();
uriMB.recycle();
decodedUriMB.recycle();
queryMB.recycle();
methodMB.recycle();
protoMB.recycle();
schemeMB.recycle();
instanceId.recycle();
remoteUser.recycle();
authType.recycle();
attributes.clear();
listener = null;
startTime = -1;
}
// -------------------- Info --------------------
public void updateCounters() {
reqProcessorMX.updateCounters();
}
public RequestInfo getRequestProcessor() {
return reqProcessorMX;
}
public int getBytesRead() {
return bytesRead;
}
public boolean isProcessing() {
return reqProcessorMX.getStage()==org.apache.coyote.Constants.STAGE_SERVICE;
}
/**
* Parse the character encoding from the specified content type header.
* If the content type is null, or there is no explicit character encoding,
* <code>null</code> is returned.
*
* @param contentType a content type header
*/
private static String getCharsetFromContentType(String contentType) {
if (contentType == null) {
return (null);
}
int start = contentType.indexOf("charset=");
if (start < 0) {
return (null);
}
String encoding = contentType.substring(start + 8);
int end = encoding.indexOf(';');
if (end >= 0) {
encoding = encoding.substring(0, end);
}
encoding = encoding.trim();
if ((encoding.length() > 2) && (encoding.startsWith("\""))
&& (encoding.endsWith("\""))) {
encoding = encoding.substring(1, encoding.length() - 1);
}
return (encoding.trim());
}
}
|
55,438
|
Bug 55438 Non Blocking API's onAllDataRead being called twice
| null |
resolved fixed
|
7f6ea48
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-19T14:54:15Z
| 2013-08-16T21:53:20Z
|
test/org/apache/catalina/nonblocking/TestNonBlockingAPI.java
|
/*
* 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.nonblocking;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.SocketFactory;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.BytesStreamer;
import org.apache.catalina.startup.TesterServlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.catalina.valves.TesterAccessLogValve;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.ByteChunk;
public class TestNonBlockingAPI extends TomcatBaseTest {
private static final Log log = LogFactory.getLog(TestNonBlockingAPI.class);
private static final int CHUNK_SIZE = 1024 * 1024;
private static final int WRITE_SIZE = CHUNK_SIZE * 5;
private static final byte[] DATA = new byte[WRITE_SIZE];
private static final int WRITE_PAUSE_MS = 500;
static {
// Use this sequence for padding to make it easier to spot errors
byte[] padding = new byte[] {'z', 'y', 'x', 'w', 'v', 'u', 't', 's',
'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k'};
int blockSize = padding.length;
for (int i = 0; i < WRITE_SIZE / blockSize; i++) {
String hex = String.format("%01X", Integer.valueOf(i));
int hexSize = hex.length();
int padSize = blockSize - hexSize;
System.arraycopy(padding, 0, DATA, i * blockSize, padSize);
System.arraycopy(
hex.getBytes(), 0, DATA, i * blockSize + padSize, hexSize);
}
}
@Test
public void testNonBlockingRead() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
StandardContext ctx = (StandardContext) tomcat.addContext("",
System.getProperty("java.io.tmpdir"));
NBReadServlet servlet = new NBReadServlet();
String servletName = NBReadServlet.class.getName();
Tomcat.addServlet(ctx, servletName, servlet);
ctx.addServletMapping("/", servletName);
tomcat.start();
Map<String, List<String>> resHeaders = new HashMap<>();
int rc = postUrl(true, new DataWriter(500), "http://localhost:" +
getPort() + "/", new ByteChunk(), resHeaders, null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
}
@Test
public void testNonBlockingWrite() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
StandardContext ctx = (StandardContext) tomcat.addContext("",
System.getProperty("java.io.tmpdir"));
NBWriteServlet servlet = new NBWriteServlet();
String servletName = NBWriteServlet.class.getName();
Tomcat.addServlet(ctx, servletName, servlet);
ctx.addServletMapping("/", servletName);
tomcat.getConnector().setProperty("socket.txBufSize", "1024");
tomcat.start();
SocketFactory factory = SocketFactory.getDefault();
Socket s = factory.createSocket("localhost", getPort());
ByteChunk result = new ByteChunk();
OutputStream os = s.getOutputStream();
os.write(("GET / HTTP/1.1\r\n" +
"Host: localhost:" + getPort() + "\r\n" +
"Connection: close\r\n" +
"\r\n").getBytes(StandardCharsets.ISO_8859_1));
os.flush();
InputStream is = s.getInputStream();
byte[] buffer = new byte[8192];
int read = 0;
int readSinceLastPause = 0;
while (read != -1) {
read = is.read(buffer);
if (read > 0) {
result.append(buffer, 0, read);
}
readSinceLastPause += read;
if (readSinceLastPause > WRITE_SIZE / 16) {
readSinceLastPause = 0;
Thread.sleep(500);
}
}
os.close();
is.close();
s.close();
// Validate the result.
// Response line
String resultString = result.toString();
log.info("Client read " + resultString.length() + " bytes");
int lineStart = 0;
int lineEnd = resultString.indexOf('\n', 0);
String line = resultString.substring(lineStart, lineEnd + 1);
Assert.assertEquals("HTTP/1.1 200 OK\r\n", line);
// Check headers - looking to see if response is chunked (it should be)
boolean chunked = false;
while (line.length() > 2) {
lineStart = lineEnd + 1;
lineEnd = resultString.indexOf('\n', lineStart);
line = resultString.substring(lineStart, lineEnd + 1);
if (line.startsWith("Transfer-Encoding:")) {
Assert.assertEquals("Transfer-Encoding: chunked\r\n", line);
chunked = true;
}
}
Assert.assertTrue(chunked);
// Now check body size
int totalBodyRead = 0;
int chunkSize = -1;
while (chunkSize != 0) {
// Chunk size in hex
lineStart = lineEnd + 1;
lineEnd = resultString.indexOf('\n', lineStart);
line = resultString.substring(lineStart, lineEnd + 1);
Assert.assertTrue(line.endsWith("\r\n"));
line = line.substring(0, line.length() - 2);
log.info("[" + line + "]");
chunkSize = Integer.parseInt(line, 16);
// Read the chunk
lineStart = lineEnd + 1;
lineEnd = resultString.indexOf('\n', lineStart);
log.info("Start : " + lineStart + ", End: " + lineEnd);
if (lineEnd > lineStart) {
line = resultString.substring(lineStart, lineEnd + 1);
} else {
line = resultString.substring(lineStart);
}
if (line.length() > 40) {
log.info(line.substring(0, 32));
} else {
log.info(line);
}
if (chunkSize + 2 != line.length()) {
log.error("Chunk wrong length. Was " + line.length() +
" Expected " + (chunkSize + 2));
byte[] resultBytes = resultString.getBytes();
// Find error
boolean found = false;
for (int i = totalBodyRead; i < (totalBodyRead + line.length()); i++) {
if (DATA[i] != resultBytes[lineStart + i - totalBodyRead]) {
int dataStart = i - 16;
if (dataStart < 0) {
dataStart = 0;
}
int dataEnd = i + 16;
if (dataEnd > DATA.length) {
dataEnd = DATA.length;
}
int resultStart = lineStart + i - totalBodyRead - 16;
if (resultStart < 0) {
resultStart = 0;
}
int resultEnd = lineStart + i - totalBodyRead + 16;
if (resultEnd > resultString.length()) {
resultEnd = resultString.length();
}
log.error("Mis-match tx: " + new String(
DATA, dataStart, dataEnd - dataStart));
log.error("Mis-match rx: " +
resultString.substring(resultStart, resultEnd));
found = true;
break;
}
}
if (!found) {
log.error("No mismatch. Data truncated");
}
}
Assert.assertTrue(line.endsWith("\r\n"));
Assert.assertEquals(chunkSize + 2, line.length());
totalBodyRead += chunkSize;
}
Assert.assertEquals(WRITE_SIZE, totalBodyRead);
}
@Test
public void testNonBlockingWriteError() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
StandardContext ctx = (StandardContext) tomcat.addContext(
"", System.getProperty("java.io.tmpdir"));
TesterAccessLogValve alv = new TesterAccessLogValve();
ctx.getPipeline().addValve(alv);
NBWriteServlet servlet = new NBWriteServlet();
String servletName = NBWriteServlet.class.getName();
Tomcat.addServlet(ctx, servletName, servlet);
ctx.addServletMapping("/", servletName);
tomcat.getConnector().setProperty("socket.txBufSize", "1024");
tomcat.start();
SocketFactory factory = SocketFactory.getDefault();
Socket s = factory.createSocket("localhost", getPort());
ByteChunk result = new ByteChunk();
OutputStream os = s.getOutputStream();
os.write(("GET / HTTP/1.1\r\n" +
"Host: localhost:" + getPort() + "\r\n" +
"Connection: close\r\n" +
"\r\n").getBytes(StandardCharsets.ISO_8859_1));
os.flush();
InputStream is = s.getInputStream();
byte[] buffer = new byte[8192];
int read = 0;
int readSinceLastPause = 0;
int readTotal = 0;
while (read != -1 && readTotal < WRITE_SIZE / 2) {
long start = System.currentTimeMillis();
read = is.read(buffer);
long end = System.currentTimeMillis();
log.info("Client read [" + read + "] bytes in [" + (end - start) +
"] ms");
if (read > 0) {
result.append(buffer, 0, read);
}
readSinceLastPause += read;
readTotal += read;
if (readSinceLastPause > WRITE_SIZE / 16) {
readSinceLastPause = 0;
Thread.sleep(WRITE_PAUSE_MS);
}
}
os.close();
is.close();
s.close();
String resultString = result.toString();
log.info("Client read " + resultString.length() + " bytes");
int lineStart = 0;
int lineEnd = resultString.indexOf('\n', 0);
String line = resultString.substring(lineStart, lineEnd + 1);
Assert.assertEquals("HTTP/1.1 200 OK\r\n", line);
try {
//allow the listeners to finish up
Thread.sleep(1000);
} catch (Exception e) {
}
Assert.assertTrue("Error listener should have been invoked.",
servlet.wlistener.onErrorInvoked);
// TODO Figure out why non-blocking writes with the NIO connector appear
// to be slower on Linux
alv.validateAccessLog(1, 500, WRITE_PAUSE_MS * 7,
WRITE_PAUSE_MS * 7 + 30 * 1000);
}
public static class DataWriter implements BytesStreamer {
final int max = 5;
int count = 0;
long delay = 0;
byte[] b = "WANTMORE".getBytes();
byte[] f = "FINISHED".getBytes();
public DataWriter(long delay) {
this.delay = delay;
}
@Override
public int getLength() {
return b.length * max;
}
@Override
public int available() {
if (count < max) {
return b.length;
} else {
return 0;
}
}
@Override
public byte[] next() {
if (count < max) {
if (count > 0)
try {
if (delay > 0)
Thread.sleep(delay);
} catch (Exception x) {
}
count++;
if (count < max)
return b;
else
return f;
} else {
return null;
}
}
}
@WebServlet(asyncSupported = true)
public class NBReadServlet extends TesterServlet {
private static final long serialVersionUID = 1L;
public volatile TestReadListener listener;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// step 1 - start async
AsyncContext actx = req.startAsync();
actx.setTimeout(Long.MAX_VALUE);
actx.addListener(new AsyncListener() {
@Override
public void onTimeout(AsyncEvent event) throws IOException {
log.info("onTimeout");
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
log.info("onStartAsync");
}
@Override
public void onError(AsyncEvent event) throws IOException {
log.info("AsyncListener.onError");
}
@Override
public void onComplete(AsyncEvent event) throws IOException {
log.info("onComplete");
}
});
// step 2 - notify on read
ServletInputStream in = req.getInputStream();
listener = new TestReadListener(actx, false);
in.setReadListener(listener);
}
}
@WebServlet(asyncSupported = true)
public class NBWriteServlet extends TesterServlet {
private static final long serialVersionUID = 1L;
public volatile TestWriteListener wlistener;
public volatile TestReadListener rlistener;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// step 1 - start async
AsyncContext actx = req.startAsync();
actx.setTimeout(Long.MAX_VALUE);
actx.addListener(new AsyncListener() {
@Override
public void onTimeout(AsyncEvent event) throws IOException {
log.info("onTimeout");
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
log.info("onStartAsync");
}
@Override
public void onError(AsyncEvent event) throws IOException {
log.info("AsyncListener.onError");
}
@Override
public void onComplete(AsyncEvent event) throws IOException {
log.info("onComplete");
}
});
// step 2 - notify on read
ServletInputStream in = req.getInputStream();
rlistener = new TestReadListener(actx, true);
in.setReadListener(rlistener);
ServletOutputStream out = resp.getOutputStream();
resp.setBufferSize(200 * 1024);
wlistener = new TestWriteListener(actx);
out.setWriteListener(wlistener);
}
}
private class TestReadListener implements ReadListener {
private final AsyncContext ctx;
private final StringBuilder body = new StringBuilder();
private final boolean usingNonBlockingWrite;
public TestReadListener(AsyncContext ctx,
boolean usingNonBlockingWrite) {
this.ctx = ctx;
this.usingNonBlockingWrite = usingNonBlockingWrite;
}
@Override
public void onDataAvailable() throws IOException {
ServletInputStream in = ctx.getRequest().getInputStream();
String s = "";
byte[] b = new byte[8192];
int read = 0;
do {
read = in.read(b);
if (read == -1) {
break;
}
s += new String(b, 0, read);
} while (in.isReady());
log.info(s);
body.append(s);
}
@Override
public void onAllDataRead() {
log.info("onAllDataRead");
// If non-blocking writes are being used, don't write here as it
// will inject unexpected data into the write output.
if (!usingNonBlockingWrite) {
String msg;
if (body.toString().endsWith("FINISHED")) {
msg = "OK";
} else {
msg = "FAILED";
}
try {
ctx.getResponse().getOutputStream().print(msg);
} catch (IOException ioe) {
// Ignore
}
ctx.complete();
}
}
@Override
public void onError(Throwable throwable) {
log.info("ReadListener.onError");
throwable.printStackTrace();
}
}
private class TestWriteListener implements WriteListener {
AsyncContext ctx;
int written = 0;
public volatile boolean onErrorInvoked = false;
public TestWriteListener(AsyncContext ctx) {
this.ctx = ctx;
}
@Override
public void onWritePossible() throws IOException {
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
int before = written;
while (written < WRITE_SIZE &&
ctx.getResponse().getOutputStream().isReady()) {
ctx.getResponse().getOutputStream().write(
DATA, written, CHUNK_SIZE);
written += CHUNK_SIZE;
}
if (written == WRITE_SIZE) {
// Clear the output buffer else data may be lost when
// calling complete
ctx.getResponse().flushBuffer();
}
log.info("Write took:" + (end - start) +
" ms. Bytes before=" + before + " after=" + written);
// only call complete if we have emptied the buffer
if (ctx.getResponse().getOutputStream().isReady() &&
written == WRITE_SIZE) {
// it is illegal to call complete
// if there is a write in progress
ctx.complete();
}
}
@Override
public void onError(Throwable throwable) {
log.info("WriteListener.onError");
throwable.printStackTrace();
onErrorInvoked = true;
}
}
public static int postUrlWithDisconnect(boolean stream, BytesStreamer streamer, String path,
Map<String, List<String>> reqHead, Map<String, List<String>> resHead) throws IOException {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setReadTimeout(1000000);
if (reqHead != null) {
for (Map.Entry<String, List<String>> entry : reqHead.entrySet()) {
StringBuilder valueList = new StringBuilder();
for (String value : entry.getValue()) {
if (valueList.length() > 0) {
valueList.append(',');
}
valueList.append(value);
}
connection.setRequestProperty(entry.getKey(), valueList.toString());
}
}
if (streamer != null && stream) {
if (streamer.getLength() > 0) {
connection.setFixedLengthStreamingMode(streamer.getLength());
} else {
connection.setChunkedStreamingMode(1024);
}
}
connection.connect();
// Write the request body
OutputStream os = null;
try {
os = connection.getOutputStream();
while (streamer != null && streamer.available() > 0) {
byte[] next = streamer.next();
os.write(next);
os.flush();
}
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ioe) {
// Ignore
}
}
}
int rc = connection.getResponseCode();
if (resHead != null) {
Map<String, List<String>> head = connection.getHeaderFields();
resHead.putAll(head);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (rc == HttpServletResponse.SC_OK) {
connection.getInputStream().close();
// Should never be null here but just to be safe
if (os != null) {
os.close();
}
connection.disconnect();
}
return rc;
}
}
|
55,442
|
Bug 55442 EL Constructor throws exception
|
In the EL 3.0 Spec, section 1.22.3 "Constructor Reference" states "A class name reference, followed by arguments in parenthesis, such as "Boolean(true)" denotes the invocation of the constructor of the class with the supplied arguments." This leads me to believe that the following test should work: @Test public void testImport03() { ELProcessor processor = new ELProcessor(); Object result = processor.getValue("Integer('1000')", Integer.class); Assert.assertEquals(Integer.valueOf(1000), result); } Unfortunately, this fails with the following error. javax.el.ELException: Function ':Integer' not found at org.apache.el.parser.AstFunction.getValue(AstFunction.java:136) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:188) at javax.el.ELProcessor.getValue(ELProcessor.java:45) at org.apache.el.parser.TestAstIdentifier.testImport03(TestAstIdentifier.java:53) ... Thanks
|
resolved fixed
|
ab70f07
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-20T08:38:29Z
| 2013-08-17T17:20:00Z
|
java/org/apache/el/parser/AstFunction.java
|
/*
* 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.
*/
/* Generated By:JJTree: Do not edit this line. AstFunction.java */
package org.apache.el.parser;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.el.ELException;
import javax.el.FunctionMapper;
import javax.el.LambdaExpression;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
import org.apache.el.lang.EvaluationContext;
import org.apache.el.util.MessageFactory;
/**
* @author Jacob Hookom [jacob@hookom.net]
* @version $Id$
*/
public final class AstFunction extends SimpleNode {
protected String localName = "";
protected String prefix = "";
public AstFunction(int id) {
super(id);
}
public String getLocalName() {
return localName;
}
public String getOutputName() {
if (this.prefix == null) {
return this.localName;
} else {
return this.prefix + ":" + this.localName;
}
}
public String getPrefix() {
return prefix;
}
@Override
public Class<?> getType(EvaluationContext ctx)
throws ELException {
FunctionMapper fnMapper = ctx.getFunctionMapper();
// quickly validate again for this request
if (fnMapper == null) {
throw new ELException(MessageFactory.get("error.fnMapper.null"));
}
Method m = fnMapper.resolveFunction(this.prefix, this.localName);
if (m == null) {
throw new ELException(MessageFactory.get("error.fnMapper.method",
this.getOutputName()));
}
return m.getReturnType();
}
@Override
public Object getValue(EvaluationContext ctx)
throws ELException {
FunctionMapper fnMapper = ctx.getFunctionMapper();
// quickly validate again for this request
if (fnMapper == null) {
throw new ELException(MessageFactory.get("error.fnMapper.null"));
}
Method m = fnMapper.resolveFunction(this.prefix, this.localName);
if (m == null && this.prefix.length() == 0) {
// TODO: Do we need to think about precedence of the various ways
// a lambda expression may be obtained from something that
// the parser thinks is a function?
Object obj = null;
if (ctx.isLambdaArgument(this.localName)) {
obj = ctx.getLambdaArgument(this.localName);
}
if (obj == null) {
VariableMapper varMapper = ctx.getVariableMapper();
if (varMapper != null) {
obj = varMapper.resolveVariable(this.localName);
if (obj instanceof ValueExpression) {
// See if this returns a LambdaEXpression
obj = ((ValueExpression) obj).getValue(ctx);
}
}
}
if (obj == null) {
obj = ctx.getELResolver().getValue(ctx, null, this.localName);
}
if (obj instanceof LambdaExpression) {
// Build arguments
int i = 0;
while (obj instanceof LambdaExpression &&
i < jjtGetNumChildren()) {
Node args = jjtGetChild(i);
obj = ((LambdaExpression) obj).invoke(
((AstMethodParameters) args).getParameters(ctx));
i++;
}
if (i < jjtGetNumChildren()) {
// Haven't consumed all the sets of parameters therefore
// there were too many sets of parameters
throw new ELException(MessageFactory.get(
"error.lambda.tooManyMethodParameterSets"));
}
return obj;
}
}
if (m == null) {
throw new ELException(MessageFactory.get("error.fnMapper.method",
this.getOutputName()));
}
// Not a lambda expression so must be a function. Check there is just a
// single set of method parameters
if (this.jjtGetNumChildren() != 1) {
throw new ELException(MessageFactory.get(
"error.funciton.tooManyMethodParameterSets",
getOutputName()));
}
Node parameters = jjtGetChild(0);
Class<?>[] paramTypes = m.getParameterTypes();
Object[] params = null;
Object result = null;
int numParams = parameters.jjtGetNumChildren();
if (numParams > 0) {
params = new Object[numParams];
try {
for (int i = 0; i < numParams; i++) {
params[i] = parameters.jjtGetChild(i).getValue(ctx);
params[i] = coerceToType(params[i], paramTypes[i]);
}
} catch (ELException ele) {
throw new ELException(MessageFactory.get("error.function", this
.getOutputName()), ele);
}
}
try {
result = m.invoke(null, params);
} catch (IllegalAccessException iae) {
throw new ELException(MessageFactory.get("error.function", this
.getOutputName()), iae);
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
if (cause instanceof ThreadDeath) {
throw (ThreadDeath) cause;
}
if (cause instanceof VirtualMachineError) {
throw (VirtualMachineError) cause;
}
throw new ELException(MessageFactory.get("error.function", this
.getOutputName()), cause);
}
return result;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
@Override
public String toString()
{
return ELParserTreeConstants.jjtNodeName[id] + "[" + this.getOutputName() + "]";
}
}
|
55,442
|
Bug 55442 EL Constructor throws exception
|
In the EL 3.0 Spec, section 1.22.3 "Constructor Reference" states "A class name reference, followed by arguments in parenthesis, such as "Boolean(true)" denotes the invocation of the constructor of the class with the supplied arguments." This leads me to believe that the following test should work: @Test public void testImport03() { ELProcessor processor = new ELProcessor(); Object result = processor.getValue("Integer('1000')", Integer.class); Assert.assertEquals(Integer.valueOf(1000), result); } Unfortunately, this fails with the following error. javax.el.ELException: Function ':Integer' not found at org.apache.el.parser.AstFunction.getValue(AstFunction.java:136) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:188) at javax.el.ELProcessor.getValue(ELProcessor.java:45) at org.apache.el.parser.TestAstIdentifier.testImport03(TestAstIdentifier.java:53) ... Thanks
|
resolved fixed
|
ab70f07
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-20T08:38:29Z
| 2013-08-17T17:20:00Z
|
test/org/apache/el/parser/TestAstFunction.java
| |
55,454
|
Bug 55454 NullPointerException caused by invalid contentType, e.g. trailing semicolon
|
possible related to 53353 When having an invalid contenttype like: <jsp:directive.page language="java" contentType="text/html;"/> (note the trailing ";") Tomcat throws a NullPointerException like this: java.lang.NullPointerException org.apache.tomcat.util.http.parser.HttpParser.parseMediaType(HttpParser.java:217) org.apache.tomcat.util.http.parser.MediaTypeCache.parse(MediaTypeCache.java:54) org.apache.catalina.connector.Response.setContentType(Response.java:805) org.apache.catalina.connector.ResponseFacade.setContentType(ResponseFacade.java:245) javax.servlet.ServletResponseWrapper.setContentType(ServletResponseWrapper.java:123) After removing the extra ";" or entering a charset like this: <jsp:directive.page language="java" contentType="text/html; charset=UTF-8"/> it works as expected. My desired behaviour would be: Don't crash with a NPE. Other Tomcat versions seem to handly this different.
|
resolved fixed
|
8b03dcf
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-20T15:02:23Z
| 2013-08-20T14:46:40Z
|
java/org/apache/tomcat/util/http/parser/HttpParser.java
|
/*
* 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.http.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* HTTP header value parser implementation. Parsing HTTP headers as per RFC2616
* is not always as simple as it first appears. For headers that only use tokens
* the simple approach will normally be sufficient. However, for the other
* headers, while simple code meets 99.9% of cases, there are often some edge
* cases that make things far more complicated.
*
* The purpose of this parser is to let the parser worry about the edge cases.
* It provides tolerant (where safe to do so) parsing of HTTP header values
* assuming that wrapped header lines have already been unwrapped. (The Tomcat
* header processing code does the unwrapping.)
*
* Provides parsing of the following HTTP header values as per RFC 2616:
* - Authorization for DIGEST authentication
* - MediaType (used for Content-Type header)
*
* Support for additional headers will be provided as required.
*/
public class HttpParser {
@SuppressWarnings("unused") // Unused due to buggy client implementations
private static final Integer FIELD_TYPE_TOKEN = Integer.valueOf(0);
private static final Integer FIELD_TYPE_QUOTED_STRING = Integer.valueOf(1);
private static final Integer FIELD_TYPE_TOKEN_OR_QUOTED_STRING = Integer.valueOf(2);
private static final Integer FIELD_TYPE_LHEX = Integer.valueOf(3);
private static final Integer FIELD_TYPE_QUOTED_TOKEN = Integer.valueOf(4);
private static final Map<String,Integer> fieldTypes = new HashMap<>();
// Arrays used by isToken(), isHex()
private static final boolean isToken[] = new boolean[128];
private static final boolean isHex[] = new boolean[128];
static {
// Digest field types.
// Note: These are more relaxed than RFC2617. This adheres to the
// recommendation of RFC2616 that servers are tolerant of buggy
// clients when they can be so without ambiguity.
fieldTypes.put("username", FIELD_TYPE_QUOTED_STRING);
fieldTypes.put("realm", FIELD_TYPE_QUOTED_STRING);
fieldTypes.put("nonce", FIELD_TYPE_QUOTED_STRING);
fieldTypes.put("digest-uri", FIELD_TYPE_QUOTED_STRING);
// RFC2617 says response is <">32LHEX<">. 32LHEX will also be accepted
fieldTypes.put("response", FIELD_TYPE_LHEX);
// RFC2617 says algorithm is token. <">token<"> will also be accepted
fieldTypes.put("algorithm", FIELD_TYPE_QUOTED_TOKEN);
fieldTypes.put("cnonce", FIELD_TYPE_QUOTED_STRING);
fieldTypes.put("opaque", FIELD_TYPE_QUOTED_STRING);
// RFC2617 says qop is token. <">token<"> will also be accepted
fieldTypes.put("qop", FIELD_TYPE_QUOTED_TOKEN);
// RFC2617 says nc is 8LHEX. <">8LHEX<"> will also be accepted
fieldTypes.put("nc", FIELD_TYPE_LHEX);
// Setup the flag arrays
for (int i = 0; i < 128; i++) {
if (i < 32) {
isToken[i] = false;
} else if (i == '(' || i == ')' || i == '<' || i == '>' || i == '@' ||
i == ',' || i == ';' || i == ':' || i == '\\' || i == '\"' ||
i == '/' || i == '[' || i == ']' || i == '?' || i == '=' ||
i == '{' || i == '}' || i == ' ' || i == '\t') {
isToken[i] = false;
} else {
isToken[i] = true;
}
if (i >= '0' && i <= '9' || i >= 'A' && i <= 'F' ||
i >= 'a' && i <= 'f') {
isHex[i] = true;
} else {
isHex[i] = false;
}
}
}
/**
* Parses an HTTP Authorization header for DIGEST authentication as per RFC
* 2617 section 3.2.2.
*
* @param input The header value to parse
*
* @return A map of directives and values as {@link String}s or
* <code>null</code> if a parsing error occurs. Although the
* values returned are {@link String}s they will have been
* validated to ensure that they conform to RFC 2617.
*
* @throws IllegalArgumentException If the header does not conform to RFC
* 2617
* @throws IOException If an error occurs while reading the input
*/
public static Map<String,String> parseAuthorizationDigest (
StringReader input) throws IllegalArgumentException, IOException {
Map<String,String> result = new HashMap<>();
if (skipConstant(input, "Digest") != SkipConstantResult.FOUND) {
return null;
}
// All field names are valid tokens
String field = readToken(input);
if (field == null) {
return null;
}
while (!field.equals("")) {
if (skipConstant(input, "=") != SkipConstantResult.FOUND) {
return null;
}
String value = null;
Integer type = fieldTypes.get(field.toLowerCase(Locale.ENGLISH));
if (type == null) {
// auth-param = token "=" ( token | quoted-string )
type = FIELD_TYPE_TOKEN_OR_QUOTED_STRING;
}
switch (type.intValue()) {
case 0:
// FIELD_TYPE_TOKEN
value = readToken(input);
break;
case 1:
// FIELD_TYPE_QUOTED_STRING
value = readQuotedString(input, false);
break;
case 2:
// FIELD_TYPE_TOKEN_OR_QUOTED_STRING
value = readTokenOrQuotedString(input, false);
break;
case 3:
// FIELD_TYPE_LHEX
value = readLhex(input);
break;
case 4:
// FIELD_TYPE_QUOTED_TOKEN
value = readQuotedToken(input);
break;
default:
// Error
throw new IllegalArgumentException(
"TODO i18n: Unsupported type");
}
if (value == null) {
return null;
}
result.put(field, value);
if (skipConstant(input, ",") == SkipConstantResult.NOT_FOUND) {
return null;
}
field = readToken(input);
if (field == null) {
return null;
}
}
return result;
}
public static MediaType parseMediaType(StringReader input)
throws IOException {
// Type (required)
String type = readToken(input);
if (type == null || type.length() == 0) {
return null;
}
if (skipConstant(input, "/") == SkipConstantResult.NOT_FOUND) {
return null;
}
// Subtype (required)
String subtype = readToken(input);
if (subtype == null || subtype.length() == 0) {
return null;
}
LinkedHashMap<String,String> parameters = new LinkedHashMap<>();
SkipConstantResult lookForSemiColon = skipConstant(input, ";");
if (lookForSemiColon == SkipConstantResult.NOT_FOUND) {
return null;
}
while (lookForSemiColon == SkipConstantResult.FOUND) {
String attribute = readToken(input);
if (skipConstant(input, "=") == SkipConstantResult.FOUND) {
String value = readTokenOrQuotedString(input, true);
parameters.put(attribute.toLowerCase(Locale.ENGLISH), value);
} else {
parameters.put(attribute.toLowerCase(Locale.ENGLISH), "");
}
lookForSemiColon = skipConstant(input, ";");
if (lookForSemiColon == SkipConstantResult.NOT_FOUND) {
return null;
}
}
return new MediaType(type, subtype, parameters);
}
public static String unquote(String input) {
if (input == null || input.length() < 2 || input.charAt(0) != '"') {
return input;
}
StringBuilder result = new StringBuilder();
for (int i = 1 ; i < (input.length() - 1); i++) {
char c = input.charAt(i);
if (input.charAt(i) == '\\') {
i++;
result.append(input.charAt(i));
} else {
result.append(c);
}
}
return result.toString();
}
private static boolean isToken(int c) {
// Fast for correct values, slower for incorrect ones
try {
return isToken[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
private static boolean isHex(int c) {
// Fast for correct values, slower for incorrect ones
try {
return isHex[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
// Skip any LWS and return the next char
private static int skipLws(StringReader input, boolean withReset)
throws IOException {
if (withReset) {
input.mark(1);
}
int c = input.read();
while (c == 32 || c == 9 || c == 10 || c == 13) {
if (withReset) {
input.mark(1);
}
c = input.read();
}
if (withReset) {
input.reset();
}
return c;
}
private static SkipConstantResult skipConstant(StringReader input,
String constant) throws IOException {
int len = constant.length();
int c = skipLws(input, false);
for (int i = 0; i < len; i++) {
if (i == 0 && c == -1) {
return SkipConstantResult.EOF;
}
if (c != constant.charAt(i)) {
input.skip(-(i + 1));
return SkipConstantResult.NOT_FOUND;
}
if (i != (len - 1)) {
c = input.read();
}
}
return SkipConstantResult.FOUND;
}
/**
* @return the token if one was found, the empty string if no data was
* available to read or <code>null</code> if data other than a
* token was found
*/
private static String readToken(StringReader input) throws IOException {
StringBuilder result = new StringBuilder();
int c = skipLws(input, false);
while (c != -1 && isToken(c)) {
result.append((char) c);
c = input.read();
}
// Skip back so non-token character is available for next read
input.skip(-1);
if (c != -1 && result.length() == 0) {
return null;
} else {
return result.toString();
}
}
/**
* @return the quoted string if one was found, null if data other than a
* quoted string was found or null if the end of data was reached
* before the quoted string was terminated
*/
private static String readQuotedString(StringReader input,
boolean returnQuoted) throws IOException {
int c = skipLws(input, false);
if (c != '"') {
return null;
}
StringBuilder result = new StringBuilder();
if (returnQuoted) {
result.append('\"');
}
c = input.read();
while (c != '"') {
if (c == -1) {
return null;
} else if (c == '\\') {
c = input.read();
if (returnQuoted) {
result.append('\\');
}
result.append(c);
} else {
result.append((char) c);
}
c = input.read();
}
if (returnQuoted) {
result.append('\"');
}
return result.toString();
}
private static String readTokenOrQuotedString(StringReader input,
boolean returnQuoted) throws IOException {
// Go back so first non-LWS character is available to be read again
int c = skipLws(input, true);
if (c == '"') {
return readQuotedString(input, returnQuoted);
} else {
return readToken(input);
}
}
/**
* Token can be read unambiguously with or without surrounding quotes so
* this parsing method for token permits optional surrounding double quotes.
* This is not defined in any RFC. It is a special case to handle data from
* buggy clients (known buggy clients for DIGEST auth include Microsoft IE 8
* & 9, Apple Safari for OSX and iOS) that add quotes to values that
* should be tokens.
*
* @return the token if one was found, null if data other than a token or
* quoted token was found or null if the end of data was reached
* before a quoted token was terminated
*/
private static String readQuotedToken(StringReader input)
throws IOException {
StringBuilder result = new StringBuilder();
boolean quoted = false;
int c = skipLws(input, false);
if (c == '"') {
quoted = true;
} else if (c == -1 || !isToken(c)) {
return null;
} else {
result.append((char) c);
}
c = input.read();
while (c != -1 && isToken(c)) {
result.append((char) c);
c = input.read();
}
if (quoted) {
if (c != '"') {
return null;
}
} else {
// Skip back so non-token character is available for next read
input.skip(-1);
}
if (c != -1 && result.length() == 0) {
return null;
} else {
return result.toString();
}
}
/**
* LHEX can be read unambiguously with or without surrounding quotes so this
* parsing method for LHEX permits optional surrounding double quotes. Some
* buggy clients (libwww-perl for DIGEST auth) are known to send quoted LHEX
* when the specification requires just LHEX.
*
* <p>
* LHEX are, literally, lower-case hexadecimal digits. This implementation
* allows for upper-case digits as well, converting the returned value to
* lower-case.
*
* @return the sequence of LHEX (minus any surrounding quotes) if any was
* found, or <code>null</code> if data other LHEX was found
*/
private static String readLhex(StringReader input)
throws IOException {
StringBuilder result = new StringBuilder();
boolean quoted = false;
int c = skipLws(input, false);
if (c == '"') {
quoted = true;
} else if (c == -1 || !isHex(c)) {
return null;
} else {
if ('A' <= c && c <= 'F') {
c -= ('A' - 'a');
}
result.append((char) c);
}
c = input.read();
while (c != -1 && isHex(c)) {
if ('A' <= c && c <= 'F') {
c -= ('A' - 'a');
}
result.append((char) c);
c = input.read();
}
if (quoted) {
if (c != '"') {
return null;
}
} else {
// Skip back so non-hex character is available for next read
input.skip(-1);
}
if (c != -1 && result.length() == 0) {
return null;
} else {
return result.toString();
}
}
private static enum SkipConstantResult {
FOUND,
NOT_FOUND,
EOF
}
}
|
55,454
|
Bug 55454 NullPointerException caused by invalid contentType, e.g. trailing semicolon
|
possible related to 53353 When having an invalid contenttype like: <jsp:directive.page language="java" contentType="text/html;"/> (note the trailing ";") Tomcat throws a NullPointerException like this: java.lang.NullPointerException org.apache.tomcat.util.http.parser.HttpParser.parseMediaType(HttpParser.java:217) org.apache.tomcat.util.http.parser.MediaTypeCache.parse(MediaTypeCache.java:54) org.apache.catalina.connector.Response.setContentType(Response.java:805) org.apache.catalina.connector.ResponseFacade.setContentType(ResponseFacade.java:245) javax.servlet.ServletResponseWrapper.setContentType(ServletResponseWrapper.java:123) After removing the extra ";" or entering a charset like this: <jsp:directive.page language="java" contentType="text/html; charset=UTF-8"/> it works as expected. My desired behaviour would be: Don't crash with a NPE. Other Tomcat versions seem to handly this different.
|
resolved fixed
|
8b03dcf
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-20T15:02:23Z
| 2013-08-20T14:46:40Z
|
test/org/apache/tomcat/util/http/parser/TestMediaType.java
|
/*
* 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.http.parser;
import java.io.IOException;
import java.io.StringReader;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link HttpParser} focusing on media-type as defined in
* section 3.7 of RFC 2616.
*/
public class TestMediaType {
// Include whitespace to ensure Parser handles it correctly (it should be
// skipped).
private static final String TYPE = " foo ";
private static final String SUBTYPE = " bar ";
private static final String TYPES = TYPE + "/" + SUBTYPE;
private static final Parameter PARAM_TOKEN =
new Parameter("a", "b");
private static final Parameter PARAM_QUOTED =
new Parameter("x", "\"y\"");
private static final Parameter PARAM_EMPTY_QUOTED =
new Parameter("z", "\"\"");
private static final Parameter PARAM_COMPLEX_QUOTED =
new Parameter("w", "\"foo'bar,a=b;x=y\"");
private static final String CHARSET = "UTF-8";
private static final String WS_CHARSET = " \tUTF-8";
private static final String CHARSET_WS = "UTF-8 \t";
// Since this is quoted, it should retain the space at the end
private static final String CHARSET_QUOTED = "\"" + CHARSET_WS + "\"";
private static final Parameter PARAM_CHARSET =
new Parameter("charset", CHARSET);
private static final Parameter PARAM_WS_CHARSET =
new Parameter("charset", WS_CHARSET);
private static final Parameter PARAM_CHARSET_WS =
new Parameter("charset", CHARSET_WS);
private static final Parameter PARAM_CHARSET_QUOTED =
new Parameter("charset", CHARSET_QUOTED);
private static final String[] LWS_VALUES = new String[] {
"", " ", "\t", "\r", "\n", "\r\n", " \r", " \n", " \r\n",
"\r ", "\n ", "\r\n ", " \r ", " \n ", " \r\n " };
@Test
public void testSimple() throws IOException {
doTest();
}
@Test
public void testSimpleWithToken() throws IOException {
doTest(PARAM_TOKEN);
}
@Test
public void testSimpleWithQuotedString() throws IOException {
doTest(PARAM_QUOTED);
}
@Test
public void testSimpleWithEmptyQuotedString() throws IOException {
doTest(PARAM_EMPTY_QUOTED);
}
@Test
public void testSimpleWithComplesQuotedString() throws IOException {
doTest(PARAM_COMPLEX_QUOTED);
}
@Test
public void testSimpleWithCharset() throws IOException {
doTest(PARAM_CHARSET);
}
@Test
public void testSimpleWithCharsetWhitespaceBefore() throws IOException {
doTest(PARAM_WS_CHARSET);
}
@Test
public void testSimpleWithCharsetWhitespaceAfter() throws IOException {
doTest(PARAM_CHARSET_WS);
}
@Test
public void testSimpleWithCharsetQuoted() throws IOException {
doTest(PARAM_CHARSET_QUOTED);
}
@Test
public void testSimpleWithAll() throws IOException {
doTest(PARAM_COMPLEX_QUOTED, PARAM_EMPTY_QUOTED, PARAM_QUOTED,
PARAM_TOKEN, PARAM_CHARSET);
}
@Test
public void testCharset() throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(TYPES);
sb.append(PARAM_CHARSET);
sb.append(PARAM_TOKEN);
StringReader sr = new StringReader(sb.toString());
MediaType m = HttpParser.parseMediaType(sr);
assertEquals("foo/bar; charset=UTF-8; a=b", m.toString());
assertEquals(CHARSET, m.getCharset());
assertEquals("foo/bar; a=b", m.toStringNoCharset());
}
@Test
public void testCharsetQuoted() throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(TYPES);
sb.append(PARAM_CHARSET_QUOTED);
StringReader sr = new StringReader(sb.toString());
MediaType m = HttpParser.parseMediaType(sr);
assertEquals(CHARSET_WS, m.getCharset());
assertEquals(TYPES.replaceAll(" ", ""),
m.toStringNoCharset());
}
@Test
public void testBug52811() throws IOException {
String input = "multipart/related;boundary=1_4F50BD36_CDF8C28;" +
"Start=\"<31671603.smil>\";" +
"Type=\"application/smil;charset=UTF-8\"";
StringReader sr = new StringReader(input);
MediaType m = HttpParser.parseMediaType(sr);
// Check the types
assertEquals("multipart", m.getType());
assertEquals("related", m.getSubtype());
// Check the parameters
assertTrue(m.getParameterCount() == 3);
assertEquals("1_4F50BD36_CDF8C28", m.getParameterValue("boundary"));
assertEquals("\"<31671603.smil>\"", m.getParameterValue("Start"));
assertEquals("\"application/smil;charset=UTF-8\"",
m.getParameterValue("Type"));
String expected = "multipart/related; boundary=1_4F50BD36_CDF8C28; " +
"start=\"<31671603.smil>\"; " +
"type=\"application/smil;charset=UTF-8\"";
assertEquals(expected, m.toString());
assertEquals(expected, m.toStringNoCharset());
assertNull(m.getCharset());
}
@Test
public void testBug53353() throws IOException {
String input = "text/html; UTF-8;charset=UTF-8";
StringReader sr = new StringReader(input);
MediaType m = HttpParser.parseMediaType(sr);
// Check the types
assertEquals("text", m.getType());
assertEquals("html", m.getSubtype());
// Check the parameters
assertTrue(m.getParameterCount() == 2);
assertEquals("", m.getParameterValue("UTF-8"));
assertEquals("UTF-8", m.getCharset());
// Note: Invalid input is filtered out
assertEquals("text/html; charset=UTF-8", m.toString());
assertEquals("UTF-8", m.getCharset());
}
private void doTest(Parameter... parameters) throws IOException {
for (String lws : LWS_VALUES) {
doTest(lws, parameters);
}
}
private void doTest(String lws, Parameter... parameters)
throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(TYPES);
for (Parameter p : parameters) {
sb.append(p.toString(lws));
}
StringReader sr = new StringReader(sb.toString());
MediaType m = HttpParser.parseMediaType(sr);
// Check all expected parameters are present
assertTrue(m.getParameterCount() == parameters.length);
// Check the types
assertEquals(TYPE.trim(), m.getType());
assertEquals(SUBTYPE.trim(), m.getSubtype());
// Check the parameters
for (int i = 0; i < parameters.length; i++) {
assertEquals(parameters[i].getValue().trim(),
m.getParameterValue(parameters[i].getName().trim()));
}
}
private static class Parameter {
private final String name;
private final String value;
public Parameter(String name,String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return toString("");
}
public String toString(String lws) {
StringBuilder sb = new StringBuilder();
sb.append(lws);
sb.append(";");
sb.append(lws);
sb.append(name);
sb.append(lws);
sb.append("=");
sb.append(lws);
sb.append(value);
sb.append(lws);
return sb.toString();
}
}
@Test
public void testCase() throws Exception {
StringReader sr = new StringReader("type/sub-type;a=1;B=2");
MediaType m = HttpParser.parseMediaType(sr);
Assert.assertEquals("1", m.getParameterValue("A"));
Assert.assertEquals("1", m.getParameterValue("a"));
Assert.assertEquals("2", m.getParameterValue("B"));
Assert.assertEquals("2", m.getParameterValue("b"));
}
}
|
55,469
|
Bug 55469 Missing HTML closing tags in Manager application
| null |
resolved fixed
|
9a22360
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-23T06:34:50Z
| 2013-08-23T01:06:40Z
|
java/org/apache/catalina/manager/HTMLManagerServlet.java
|
/*
* 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.manager;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.DistributedManager;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.manager.util.BaseSessionComparator;
import org.apache.catalina.manager.util.ReverseComparator;
import org.apache.catalina.manager.util.SessionUtils;
import org.apache.catalina.util.ContextName;
import org.apache.catalina.util.RequestUtil;
import org.apache.catalina.util.ServerInfo;
import org.apache.catalina.util.URLEncoder;
import org.apache.tomcat.util.res.StringManager;
/**
* Servlet that enables remote management of the web applications deployed
* within the same virtual host as this web application is. Normally, this
* functionality will be protected by a security constraint in the web
* application deployment descriptor. However, this requirement can be
* relaxed during testing.
* <p>
* The difference between the <code>ManagerServlet</code> and this
* Servlet is that this Servlet prints out a HTML interface which
* makes it easier to administrate.
* <p>
* However if you use a software that parses the output of
* <code>ManagerServlet</code> you won't be able to upgrade
* to this Servlet since the output are not in the
* same format ar from <code>ManagerServlet</code>
*
* @author Bip Thelin
* @author Malcolm Edgar
* @author Glenn L. Nielsen
* @version $Id$
* @see ManagerServlet
*/
public final class HTMLManagerServlet extends ManagerServlet {
private static final long serialVersionUID = 1L;
protected static final URLEncoder URL_ENCODER;
protected static final String APPLICATION_MESSAGE = "message";
protected static final String APPLICATION_ERROR = "error";
protected static final String sessionsListJspPath =
"/WEB-INF/jsp/sessionsList.jsp";
protected static final String sessionDetailJspPath =
"/WEB-INF/jsp/sessionDetail.jsp";
protected static final String connectorCiphersJspPath =
"/WEB-INF/jsp/connectorCiphers.jsp";
static {
URL_ENCODER = new URLEncoder();
// '/' should not be encoded in context paths
URL_ENCODER.addSafeCharacter('/');
}
private boolean showProxySessions = false;
// --------------------------------------------------------- Public Methods
/**
* Process a GET request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
StringManager smClient = StringManager.getManager(
Constants.Package, request.getLocales());
// Identify the request parameters that we need
// By obtaining the command from the pathInfo, per-command security can
// be configured in web.xml
String command = request.getPathInfo();
String path = request.getParameter("path");
ContextName cn = null;
if (path != null) {
cn = new ContextName(path, request.getParameter("version"));
}
// Prepare our output writer to generate the response message
response.setContentType("text/html; charset=" + Constants.CHARSET);
String message = "";
// Process the requested command
if (command == null || command.equals("/")) {
// No command == list
} else if (command.equals("/list")) {
// List always displayed - nothing to do here
} else if (command.equals("/sessions")) {
try {
doSessions(cn, request, response, smClient);
return;
} catch (Exception e) {
log("HTMLManagerServlet.sessions[" + cn + "]", e);
message = smClient.getString("managerServlet.exception",
e.toString());
}
} else if (command.equals("/sslConnectorCiphers")) {
sslConnectorCiphers(request, response);
} else if (command.equals("/upload") || command.equals("/deploy") ||
command.equals("/reload") || command.equals("/undeploy") ||
command.equals("/expire") || command.equals("/start") ||
command.equals("/stop")) {
message =
smClient.getString("managerServlet.postCommand", command);
} else {
message =
smClient.getString("managerServlet.unknownCommand", command);
}
list(request, response, message, smClient);
}
/**
* Process a POST request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
StringManager smClient = StringManager.getManager(
Constants.Package, request.getLocales());
// Identify the request parameters that we need
// By obtaining the command from the pathInfo, per-command security can
// be configured in web.xml
String command = request.getPathInfo();
String path = request.getParameter("path");
ContextName cn = null;
if (path != null) {
cn = new ContextName(path, request.getParameter("version"));
}
String deployPath = request.getParameter("deployPath");
ContextName deployCn = null;
if (deployPath != null) {
deployCn = new ContextName(deployPath,
request.getParameter("deployVersion"));
}
String deployConfig = request.getParameter("deployConfig");
String deployWar = request.getParameter("deployWar");
// Prepare our output writer to generate the response message
response.setContentType("text/html; charset=" + Constants.CHARSET);
String message = "";
if (command == null || command.length() == 0) {
// No command == list
// List always displayed -> do nothing
} else if (command.equals("/upload")) {
message = upload(request, smClient);
} else if (command.equals("/deploy")) {
message = deployInternal(deployConfig, deployCn, deployWar,
smClient);
} else if (command.equals("/reload")) {
message = reload(cn, smClient);
} else if (command.equals("/undeploy")) {
message = undeploy(cn, smClient);
} else if (command.equals("/expire")) {
message = expireSessions(cn, request, smClient);
} else if (command.equals("/start")) {
message = start(cn, smClient);
} else if (command.equals("/stop")) {
message = stop(cn, smClient);
} else if (command.equals("/findleaks")) {
message = findleaks(smClient);
} else {
// Try GET
doGet(request,response);
return;
}
list(request, response, message, smClient);
}
protected String upload(HttpServletRequest request, StringManager smClient)
throws IOException, ServletException {
String message = "";
Part warPart = null;
String filename = null;
Collection<Part> parts = request.getParts();
Iterator<Part> iter = parts.iterator();
try {
while (iter.hasNext()) {
Part part = iter.next();
if (part.getName().equals("deployWar") && warPart == null) {
warPart = part;
} else {
part.delete();
}
}
while (true) {
if (warPart == null) {
message = smClient.getString(
"htmlManagerServlet.deployUploadNoFile");
break;
}
filename = warPart.getSubmittedFileName();
if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
message = smClient.getString(
"htmlManagerServlet.deployUploadNotWar", filename);
break;
}
// Get the filename if uploaded name includes a path
if (filename.lastIndexOf('\\') >= 0) {
filename =
filename.substring(filename.lastIndexOf('\\') + 1);
}
if (filename.lastIndexOf('/') >= 0) {
filename =
filename.substring(filename.lastIndexOf('/') + 1);
}
// Identify the appBase of the owning Host of this Context
// (if any)
File file = new File(host.getAppBaseFile(), filename);
if (file.exists()) {
message = smClient.getString(
"htmlManagerServlet.deployUploadWarExists",
filename);
break;
}
ContextName cn = new ContextName(filename);
String name = cn.getName();
if ((host.findChild(name) != null) && !isDeployed(name)) {
message = smClient.getString(
"htmlManagerServlet.deployUploadInServerXml",
filename);
break;
}
if (!isServiced(name)) {
addServiced(name);
try {
warPart.write(file.getAbsolutePath());
// Perform new deployment
check(name);
} finally {
removeServiced(name);
}
}
break;
}
} catch(Exception e) {
message = smClient.getString
("htmlManagerServlet.deployUploadFail", e.getMessage());
log(message, e);
} finally {
if (warPart != null) {
warPart.delete();
}
warPart = null;
}
return message;
}
/**
* Deploy an application for the specified path from the specified
* web application archive.
*
* @param config URL of the context configuration file to be deployed
* @param cn Name of the application to be deployed
* @param war URL of the web application archive to be deployed
* @return message String
*/
protected String deployInternal(String config, ContextName cn, String war,
StringManager smClient) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.deploy(printWriter, config, cn, war, false, smClient);
return stringWriter.toString();
}
/**
* Render a HTML list of the currently active Contexts in our virtual host,
* and memory and server status information.
*
* @param request The request
* @param response The response
* @param message a message to display
*/
protected void list(HttpServletRequest request,
HttpServletResponse response,
String message,
StringManager smClient) throws IOException {
if (debug >= 1)
log("list: Listing contexts for virtual host '" +
host.getName() + "'");
PrintWriter writer = response.getWriter();
// HTML Header Section
writer.print(Constants.HTML_HEADER_SECTION);
// Body Header Section
Object[] args = new Object[2];
args[0] = request.getContextPath();
args[1] = smClient.getString("htmlManagerServlet.title");
writer.print(MessageFormat.format
(Constants.BODY_HEADER_SECTION, args));
// Message Section
args = new Object[3];
args[0] = smClient.getString("htmlManagerServlet.messageLabel");
if (message == null || message.length() == 0) {
args[1] = "OK";
} else {
args[1] = RequestUtil.filter(message);
}
writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args));
// Manager Section
args = new Object[9];
args[0] = smClient.getString("htmlManagerServlet.manager");
args[1] = response.encodeURL(request.getContextPath() + "/html/list");
args[2] = smClient.getString("htmlManagerServlet.list");
args[3] = response.encodeURL
(request.getContextPath() + "/" +
smClient.getString("htmlManagerServlet.helpHtmlManagerFile"));
args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager");
args[5] = response.encodeURL
(request.getContextPath() + "/" +
smClient.getString("htmlManagerServlet.helpManagerFile"));
args[6] = smClient.getString("htmlManagerServlet.helpManager");
args[7] = response.encodeURL
(request.getContextPath() + "/status");
args[8] = smClient.getString("statusServlet.title");
writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args));
// Apps Header Section
args = new Object[7];
args[0] = smClient.getString("htmlManagerServlet.appsTitle");
args[1] = smClient.getString("htmlManagerServlet.appsPath");
args[2] = smClient.getString("htmlManagerServlet.appsVersion");
args[3] = smClient.getString("htmlManagerServlet.appsName");
args[4] = smClient.getString("htmlManagerServlet.appsAvailable");
args[5] = smClient.getString("htmlManagerServlet.appsSessions");
args[6] = smClient.getString("htmlManagerServlet.appsTasks");
writer.print(MessageFormat.format(APPS_HEADER_SECTION, args));
// Apps Row Section
// Create sorted map of deployed applications by context name.
Container children[] = host.findChildren();
String contextNames[] = new String[children.length];
for (int i = 0; i < children.length; i++)
contextNames[i] = children[i].getName();
Arrays.sort(contextNames);
String appsStart = smClient.getString("htmlManagerServlet.appsStart");
String appsStop = smClient.getString("htmlManagerServlet.appsStop");
String appsReload = smClient.getString("htmlManagerServlet.appsReload");
String appsUndeploy =
smClient.getString("htmlManagerServlet.appsUndeploy");
String appsExpire = smClient.getString("htmlManagerServlet.appsExpire");
String noVersion = "<i>" +
smClient.getString("htmlManagerServlet.noVersion") + "</i>";
boolean isHighlighted = true;
boolean isDeployed = true;
String highlightColor = null;
for (String contextName : contextNames) {
Context ctxt = (Context) host.findChild(contextName);
if (ctxt != null) {
// Bugzilla 34818, alternating row colors
isHighlighted = !isHighlighted;
if(isHighlighted) {
highlightColor = "#C3F3C3";
} else {
highlightColor = "#FFFFFF";
}
String contextPath = ctxt.getPath();
String displayPath = contextPath;
if (displayPath.equals("")) {
displayPath = "/";
}
StringBuilder tmp = new StringBuilder();
tmp.append("path=");
tmp.append(URL_ENCODER.encode(displayPath));
if (ctxt.getWebappVersion().length() > 0) {
tmp.append("&version=");
tmp.append(URL_ENCODER.encode(ctxt.getWebappVersion()));
}
String pathVersion = tmp.toString();
try {
isDeployed = isDeployed(contextName);
} catch (Exception e) {
// Assume false on failure for safety
isDeployed = false;
}
args = new Object[7];
args[0] = "<a href=\"" + URL_ENCODER.encode(contextPath + "/")
+ "\">" + RequestUtil.filter(displayPath) + "</a>";
if ("".equals(ctxt.getWebappVersion())) {
args[1] = noVersion;
} else {
args[1] = RequestUtil.filter(ctxt.getWebappVersion());
}
if (ctxt.getDisplayName() == null) {
args[2] = " ";
} else {
args[2] = RequestUtil.filter(ctxt.getDisplayName());
}
args[3] = Boolean.valueOf(ctxt.getState().isAvailable());
args[4] = RequestUtil.filter(response.encodeURL(request.getContextPath() +
"/html/sessions?" + pathVersion));
Manager manager = ctxt.getManager();
if (manager instanceof DistributedManager && showProxySessions) {
args[5] = Integer.valueOf(
((DistributedManager)manager).getActiveSessionsFull());
} else if (ctxt.getManager() != null){
args[5] = Integer.valueOf(manager.getActiveSessions());
} else {
args[5] = Integer.valueOf(0);
}
args[6] = highlightColor;
writer.print
(MessageFormat.format(APPS_ROW_DETAILS_SECTION, args));
args = new Object[14];
args[0] = RequestUtil.filter(response.encodeURL(request
.getContextPath() + "/html/start?" + pathVersion));
args[1] = appsStart;
args[2] = RequestUtil.filter(response.encodeURL(request
.getContextPath() + "/html/stop?" + pathVersion));
args[3] = appsStop;
args[4] = RequestUtil.filter(response.encodeURL(request
.getContextPath() + "/html/reload?" + pathVersion));
args[5] = appsReload;
args[6] = RequestUtil.filter(response.encodeURL(request
.getContextPath() + "/html/undeploy?" + pathVersion));
args[7] = appsUndeploy;
args[8] = RequestUtil.filter(response.encodeURL(request
.getContextPath() + "/html/expire?" + pathVersion));
args[9] = appsExpire;
args[10] = smClient.getString(
"htmlManagerServlet.expire.explain");
if (manager == null) {
args[11] = smClient.getString(
"htmlManagerServlet.noManager");
} else {
args[11] = Integer.valueOf(
ctxt.getManager().getMaxInactiveInterval()/60);
}
args[12] = smClient.getString("htmlManagerServlet.expire.unit");
args[13] = highlightColor;
if (ctxt.getName().equals(this.context.getName())) {
writer.print(MessageFormat.format(
MANAGER_APP_ROW_BUTTON_SECTION, args));
} else if (ctxt.getState().isAvailable() && isDeployed) {
writer.print(MessageFormat.format(
STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args));
} else if (ctxt.getState().isAvailable() && !isDeployed) {
writer.print(MessageFormat.format(
STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args));
} else if (!ctxt.getState().isAvailable() && isDeployed) {
writer.print(MessageFormat.format(
STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args));
} else {
writer.print(MessageFormat.format(
STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args));
}
}
}
// Deploy Section
args = new Object[7];
args[0] = smClient.getString("htmlManagerServlet.deployTitle");
args[1] = smClient.getString("htmlManagerServlet.deployServer");
args[2] = response.encodeURL(request.getContextPath() + "/html/deploy");
args[3] = smClient.getString("htmlManagerServlet.deployPath");
args[4] = smClient.getString("htmlManagerServlet.deployConfig");
args[5] = smClient.getString("htmlManagerServlet.deployWar");
args[6] = smClient.getString("htmlManagerServlet.deployButton");
writer.print(MessageFormat.format(DEPLOY_SECTION, args));
args = new Object[4];
args[0] = smClient.getString("htmlManagerServlet.deployUpload");
args[1] = response.encodeURL(request.getContextPath() + "/html/upload");
args[2] = smClient.getString("htmlManagerServlet.deployUploadFile");
args[3] = smClient.getString("htmlManagerServlet.deployButton");
writer.print(MessageFormat.format(UPLOAD_SECTION, args));
// Diagnostics section
args = new Object[9];
args[0] = smClient.getString("htmlManagerServlet.diagnosticsTitle");
args[1] = smClient.getString("htmlManagerServlet.diagnosticsLeak");
args[2] = response.encodeURL(
request.getContextPath() + "/html/findleaks");
args[3] = smClient.getString("htmlManagerServlet.diagnosticsLeakWarning");
args[4] = smClient.getString("htmlManagerServlet.diagnosticsLeakButton");
args[5] = smClient.getString("htmlManagerServlet.diagnosticsSsl");
args[6] = response.encodeURL(
request.getContextPath() + "/html/sslConnectorCiphers");
args[7] = smClient.getString("htmlManagerServlet.diagnosticsSslConnectorCipherButton");
args[8] = smClient.getString("htmlManagerServlet.diagnosticsSslConnectorCipherText");
writer.print(MessageFormat.format(DIAGNOSTICS_SECTION, args));
// Server Header Section
args = new Object[9];
args[0] = smClient.getString("htmlManagerServlet.serverTitle");
args[1] = smClient.getString("htmlManagerServlet.serverVersion");
args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion");
args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor");
args[4] = smClient.getString("htmlManagerServlet.serverOSName");
args[5] = smClient.getString("htmlManagerServlet.serverOSVersion");
args[6] = smClient.getString("htmlManagerServlet.serverOSArch");
args[7] = sm.getString("htmlManagerServlet.serverHostname");
args[8] = sm.getString("htmlManagerServlet.serverIPAddress");
writer.print(MessageFormat.format
(Constants.SERVER_HEADER_SECTION, args));
// Server Row Section
args = new Object[8];
args[0] = ServerInfo.getServerInfo();
args[1] = System.getProperty("java.runtime.version");
args[2] = System.getProperty("java.vm.vendor");
args[3] = System.getProperty("os.name");
args[4] = System.getProperty("os.version");
args[5] = System.getProperty("os.arch");
try {
InetAddress address = InetAddress.getLocalHost();
args[6] = address.getHostName();
args[7] = address.getHostAddress();
} catch (UnknownHostException e) {
args[6] = "-";
args[7] = "-";
}
writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args));
// HTML Tail Section
writer.print(Constants.HTML_TAIL_SECTION);
// Finish up the response
writer.flush();
writer.close();
}
/**
* Reload the web application at the specified context path.
*
* @see ManagerServlet#reload(PrintWriter, ContextName, StringManager)
*
* @param cn Name of the application to be restarted
* @param smClient StringManager for the client's locale
* @return message String
*/
protected String reload(ContextName cn, StringManager smClient) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.reload(printWriter, cn, smClient);
return stringWriter.toString();
}
/**
* Undeploy the web application at the specified context path.
*
* @see ManagerServlet#undeploy(PrintWriter, ContextName, StringManager)
*
* @param cn Name of the application to be undeployed
* @param smClient StringManager for the client's locale
* @return message String
*/
protected String undeploy(ContextName cn, StringManager smClient) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.undeploy(printWriter, cn, smClient);
return stringWriter.toString();
}
/**
* Display session information and invoke list.
*
* @see ManagerServlet#sessions(PrintWriter, ContextName, int,
* StringManager)
*
* @param cn Name of the application to list session information
* @param idle Expire all sessions with idle time ≥ idle for this context
* @param smClient StringManager for the client's locale
* @return message String
*/
protected String sessions(ContextName cn, int idle, StringManager smClient) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.sessions(printWriter, cn, idle, smClient);
return stringWriter.toString();
}
/**
* Start the web application at the specified context path.
*
* @see ManagerServlet#start(PrintWriter, ContextName, StringManager)
*
* @param cn Name of the application to be started
* @param smClient StringManager for the client's locale
* @return message String
*/
protected String start(ContextName cn, StringManager smClient) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.start(printWriter, cn, smClient);
return stringWriter.toString();
}
/**
* Stop the web application at the specified context path.
*
* @see ManagerServlet#stop(PrintWriter, ContextName, StringManager)
*
* @param cn Name of the application to be stopped
* @param smClient StringManager for the client's locale
* @return message String
*/
protected String stop(ContextName cn, StringManager smClient) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.stop(printWriter, cn, smClient);
return stringWriter.toString();
}
/**
* Find potential memory leaks caused by web application reload.
*
* @see ManagerServlet#findleaks(boolean, PrintWriter, StringManager)
*
* @param smClient StringManager for the client's locale
*
* @return message String
*/
protected String findleaks(StringManager smClient) {
StringBuilder msg = new StringBuilder();
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
super.findleaks(false, printWriter, smClient);
String writerText = stringWriter.toString();
if (writerText.length() > 0) {
if (!writerText.startsWith("FAIL -")) {
msg.append(smClient.getString(
"htmlManagerServlet.findleaksList"));
}
msg.append(writerText);
} else {
msg.append(smClient.getString("htmlManagerServlet.findleaksNone"));
}
return msg.toString();
}
protected void sslConnectorCiphers(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("cipherList", getConnectorCiphers());
getServletContext().getRequestDispatcher(
connectorCiphersJspPath).forward(request, response);
}
/**
* @see javax.servlet.Servlet#getServletInfo()
*/
@Override
public String getServletInfo() {
return "HTMLManagerServlet, Copyright (c) 1999-2013, The Apache Software Foundation";
}
/**
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
super.init();
// Set our properties from the initialization parameters
String value = null;
value = getServletConfig().getInitParameter("showProxySessions");
showProxySessions = Boolean.parseBoolean(value);
}
// ------------------------------------------------ Sessions administration
/**
*
* Extract the expiration request parameter
*
* @param cn Name of the application from which to expire sessions
* @param req
* @param smClient StringManager for the client's locale
*/
protected String expireSessions(ContextName cn, HttpServletRequest req,
StringManager smClient) {
int idle = -1;
String idleParam = req.getParameter("idle");
if (idleParam != null) {
try {
idle = Integer.parseInt(idleParam);
} catch (NumberFormatException e) {
log("Could not parse idle parameter to an int: " + idleParam);
}
}
return sessions(cn, idle, smClient);
}
/**
*
* @param req
* @param resp
* @param smClient StringManager for the client's locale
* @throws ServletException
* @throws IOException
*/
protected void doSessions(ContextName cn, HttpServletRequest req,
HttpServletResponse resp, StringManager smClient)
throws ServletException, IOException {
req.setAttribute("path", cn.getPath());
req.setAttribute("version", cn.getVersion());
String action = req.getParameter("action");
if (debug >= 1) {
log("sessions: Session action '" + action +
"' for web application '" + cn.getDisplayName() + "'");
}
if ("sessionDetail".equals(action)) {
String sessionId = req.getParameter("sessionId");
displaySessionDetailPage(req, resp, cn, sessionId, smClient);
return;
} else if ("invalidateSessions".equals(action)) {
String[] sessionIds = req.getParameterValues("sessionIds");
int i = invalidateSessions(cn, sessionIds, smClient);
req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated.");
} else if ("removeSessionAttribute".equals(action)) {
String sessionId = req.getParameter("sessionId");
String name = req.getParameter("attributeName");
boolean removed =
removeSessionAttribute(cn, sessionId, name, smClient);
String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'";
req.setAttribute(APPLICATION_MESSAGE, outMessage);
displaySessionDetailPage(req, resp, cn, sessionId, smClient);
return;
} // else
displaySessionsListPage(cn, req, resp, smClient);
}
protected List<Session> getSessionsForName(ContextName cn,
StringManager smClient) {
if ((cn == null) || !(cn.getPath().startsWith("/") ||
cn.getPath().equals(""))) {
String path = null;
if (cn != null) {
path = cn.getPath();
}
throw new IllegalArgumentException(smClient.getString(
"managerServlet.invalidPath",
RequestUtil.filter(path)));
}
Context ctxt = (Context) host.findChild(cn.getName());
if (null == ctxt) {
throw new IllegalArgumentException(smClient.getString(
"managerServlet.noContext",
RequestUtil.filter(cn.getDisplayName())));
}
Manager manager = ctxt.getManager();
List<Session> sessions = new ArrayList<>();
sessions.addAll(Arrays.asList(manager.findSessions()));
if (manager instanceof DistributedManager && showProxySessions) {
// Add dummy proxy sessions
Set<String> sessionIds =
((DistributedManager) manager).getSessionIdsFull();
// Remove active (primary and backup) session IDs from full list
for (Session session : sessions) {
sessionIds.remove(session.getId());
}
// Left with just proxy sessions - add them
for (String sessionId : sessionIds) {
sessions.add(new DummyProxySession(sessionId));
}
}
return sessions;
}
protected Session getSessionForNameAndId(ContextName cn, String id,
StringManager smClient) {
List<Session> sessions = getSessionsForName(cn, smClient);
if (sessions == null || sessions.isEmpty()) return null;
for(Session session : sessions) {
if (session.getId().equals(id)) {
return session;
}
}
return null;
}
/**
*
* @param cn Name of the application for which the sessions will be listed
* @param req
* @param resp
* @param smClient StringManager for the client's locale
* @throws ServletException
* @throws IOException
*/
protected void displaySessionsListPage(ContextName cn,
HttpServletRequest req, HttpServletResponse resp,
StringManager smClient)
throws ServletException, IOException {
List<Session> sessions = getSessionsForName(cn, smClient);
String sortBy = req.getParameter("sort");
String orderBy = null;
if (null != sortBy && !"".equals(sortBy.trim())) {
Comparator<Session> comparator = getComparator(sortBy);
if (comparator != null) {
orderBy = req.getParameter("order");
if ("DESC".equalsIgnoreCase(orderBy)) {
comparator = new ReverseComparator(comparator);
orderBy = "ASC";
} else {
orderBy = "DESC";
}
try {
Collections.sort(sessions, comparator);
} catch (IllegalStateException ise) {
// at least 1 of the sessions is invalidated
req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated");
}
} else {
log("WARNING: unknown sort order: " + sortBy);
}
}
// keep sort order
req.setAttribute("sort", sortBy);
req.setAttribute("order", orderBy);
req.setAttribute("activeSessions", sessions);
//strong>NOTE</strong> - This header will be overridden
// automatically if a <code>RequestDispatcher.forward()</code> call is
// ultimately invoked.
resp.setHeader("Pragma", "No-cache"); // HTTP 1.0
resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1
resp.setDateHeader("Expires", 0); // 0 means now
getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp);
}
/**
*
* @param req
* @param resp
* @param smClient StringManager for the client's locale
* @throws ServletException
* @throws IOException
*/
protected void displaySessionDetailPage(HttpServletRequest req,
HttpServletResponse resp, ContextName cn, String sessionId,
StringManager smClient) throws ServletException, IOException {
Session session = getSessionForNameAndId(cn, sessionId, smClient);
//strong>NOTE</strong> - This header will be overridden
// automatically if a <code>RequestDispatcher.forward()</code> call is
// ultimately invoked.
resp.setHeader("Pragma", "No-cache"); // HTTP 1.0
resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1
resp.setDateHeader("Expires", 0); // 0 means now
req.setAttribute("currentSession", session);
getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp);
}
/**
* Invalidate HttpSessions
* @param cn Name of the application for which sessions are to be
* invalidated
* @param sessionIds
* @param smClient StringManager for the client's locale
* @return number of invalidated sessions
* @throws IOException
*/
protected int invalidateSessions(ContextName cn, String[] sessionIds,
StringManager smClient) throws IOException {
if (null == sessionIds) {
return 0;
}
int nbAffectedSessions = 0;
for (int i = 0; i < sessionIds.length; ++i) {
String sessionId = sessionIds[i];
HttpSession session =
getSessionForNameAndId(cn, sessionId, smClient).getSession();
if (null == session) {
// Shouldn't happen, but let's play nice...
if (debug >= 1) {
log("WARNING: can't invalidate null session " + sessionId);
}
continue;
}
try {
session.invalidate();
++nbAffectedSessions;
if (debug >= 1) {
log("Invalidating session id " + sessionId);
}
} catch (IllegalStateException ise) {
if (debug >= 1) {
log("Can't invalidate already invalidated session id " + sessionId);
}
}
}
return nbAffectedSessions;
}
/**
* Removes an attribute from an HttpSession
* @param cn Name of the application hosting the session from which the
* attribute is to be removed
* @param sessionId
* @param attributeName
* @param smClient StringManager for the client's locale
* @return true if there was an attribute removed, false otherwise
* @throws IOException
*/
protected boolean removeSessionAttribute(ContextName cn, String sessionId,
String attributeName, StringManager smClient) throws IOException {
HttpSession session =
getSessionForNameAndId(cn, sessionId, smClient).getSession();
if (null == session) {
// Shouldn't happen, but let's play nice...
if (debug >= 1) {
log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId);
}
return false;
}
boolean wasPresent = (null != session.getAttribute(attributeName));
try {
session.removeAttribute(attributeName);
} catch (IllegalStateException ise) {
if (debug >= 1) {
log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId);
}
}
return wasPresent;
}
protected Comparator<Session> getComparator(String sortBy) {
Comparator<Session> comparator = null;
if ("CreationTime".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Date>() {
@Override
public Comparable<Date> getComparableObject(Session session) {
return new Date(session.getCreationTime());
}
};
} else if ("id".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<String>() {
@Override
public Comparable<String> getComparableObject(Session session) {
return session.getId();
}
};
} else if ("LastAccessedTime".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Date>() {
@Override
public Comparable<Date> getComparableObject(Session session) {
return new Date(session.getLastAccessedTime());
}
};
} else if ("MaxInactiveInterval".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Integer>() {
@Override
public Comparable<Integer> getComparableObject(Session session) {
return Integer.valueOf(session.getMaxInactiveInterval());
}
};
} else if ("new".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Boolean>() {
@Override
public Comparable<Boolean> getComparableObject(Session session) {
return Boolean.valueOf(session.getSession().isNew());
}
};
} else if ("locale".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<String>() {
@Override
public Comparable<String> getComparableObject(Session session) {
return JspHelper.guessDisplayLocaleFromSession(session);
}
};
} else if ("user".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<String>() {
@Override
public Comparable<String> getComparableObject(Session session) {
return JspHelper.guessDisplayUserFromSession(session);
}
};
} else if ("UsedTime".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Date>() {
@Override
public Comparable<Date> getComparableObject(Session session) {
return new Date(SessionUtils.getUsedTimeForSession(session));
}
};
} else if ("InactiveTime".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Date>() {
@Override
public Comparable<Date> getComparableObject(Session session) {
return new Date(SessionUtils.getInactiveTimeForSession(session));
}
};
} else if ("TTL".equalsIgnoreCase(sortBy)) {
comparator = new BaseSessionComparator<Date>() {
@Override
public Comparable<Date> getComparableObject(Session session) {
return new Date(SessionUtils.getTTLForSession(session));
}
};
}
//TODO: complete this to TTL, etc.
return comparator;
}
// ------------------------------------------------------ Private Constants
// These HTML sections are broken in relatively small sections, because of
// limited number of substitutions MessageFormat can process
// (maximum of 10).
private static final String APPS_HEADER_SECTION =
"<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td colspan=\"6\" class=\"title\">{0}</td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td class=\"header-left\"><small>{1}</small></td>\n" +
" <td class=\"header-left\"><small>{2}</small></td>\n" +
" <td class=\"header-center\"><small>{3}</small></td>\n" +
" <td class=\"header-center\"><small>{4}</small></td>\n" +
" <td class=\"header-left\"><small>{5}</small></td>\n" +
" <td class=\"header-left\"><small>{6}</small></td>\n" +
"</tr>\n";
private static final String APPS_ROW_DETAILS_SECTION =
"<tr>\n" +
" <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{0}</small></td>\n" +
" <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{1}</small></td>\n" +
" <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{2}</small></td>\n" +
" <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\"><small>{3}</small></td>\n" +
" <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\">" +
"<small><a href=\"{4}\">{5}</a></small></td>\n";
private static final String MANAGER_APP_ROW_BUTTON_SECTION =
" <td class=\"row-left\" bgcolor=\"{13}\">\n" +
" <small>\n" +
" {1} \n" +
" {3} \n" +
" {5} \n" +
" {7} \n" +
" </small>\n" +
" </td>\n" +
"</tr><tr>\n" +
" <td class=\"row-left\" bgcolor=\"{13}\">\n" +
" <form method=\"POST\" action=\"{8}\">\n" +
" <small>\n" +
" <input type=\"submit\" value=\"{9}\"> {10} <input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\"> {12} \n" +
" </small>\n" +
" </form>\n" +
" </td>\n" +
"</tr>\n";
private static final String STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION =
" <td class=\"row-left\" bgcolor=\"{13}\">\n" +
" <small>{1}</small> \n" +
" <form class=\"inline\" method=\"POST\" action=\"{2}\">" +
" <small><input type=\"submit\" value=\"{3}\"></small>" +
" </form>\n" +
" <form class=\"inline\" method=\"POST\" action=\"{4}\">" +
" <small><input type=\"submit\" value=\"{5}\"></small>" +
" </form>\n" +
" <form class=\"inline\" method=\"POST\" action=\"{6}\">" +
" <small><input type=\"submit\" value=\"{7}\"></small>" +
" </form>\n" +
" </td>\n" +
" </tr><tr>\n" +
" <td class=\"row-left\" bgcolor=\"{13}\">\n" +
" <form method=\"POST\" action=\"{8}\">\n" +
" <small>\n" +
" <input type=\"submit\" value=\"{9}\"> {10} <input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\"> {12} \n" +
" </small>\n" +
" </form>\n" +
" </td>\n" +
"</tr>\n";
private static final String STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION =
" <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" +
" <form class=\"inline\" method=\"POST\" action=\"{0}\">" +
" <small><input type=\"submit\" value=\"{1}\"></small>" +
" </form>\n" +
" <small>{3}</small> \n" +
" <small>{5}</small> \n" +
" <form class=\"inline\" method=\"POST\" action=\"{6}\">" +
" <small><input type=\"submit\" value=\"{7}\"></small>" +
" </form>\n" +
" </td>\n" +
"</tr>\n<tr></tr>\n";
private static final String STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION =
" <td class=\"row-left\" bgcolor=\"{13}\">\n" +
" <small>{1}</small> \n" +
" <form class=\"inline\" method=\"POST\" action=\"{2}\">" +
" <small><input type=\"submit\" value=\"{3}\"></small>" +
" </form>\n" +
" <form class=\"inline\" method=\"POST\" action=\"{4}\">" +
" <small><input type=\"submit\" value=\"{5}\"></small>" +
" </form>\n" +
" <small>{7}</small> \n" +
" </td>\n" +
" </tr><tr>\n" +
" <td class=\"row-left\" bgcolor=\"{13}\">\n" +
" <form method=\"POST\" action=\"{8}\">\n" +
" <small>\n" +
" <input type=\"submit\" value=\"{9}\"> {10} <input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\"> {12} \n" +
" </small>\n" +
" </form>\n" +
" </td>\n" +
"</tr>\n";
private static final String STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION =
" <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" +
" <form class=\"inline\" method=\"POST\" action=\"{0}\">" +
" <small><input type=\"submit\" value=\"{1}\"></small>" +
" </form>\n" +
" <small>{3}</small> \n" +
" <small>{5}</small> \n" +
" <small>{7}</small> \n" +
" </td>\n" +
"</tr>\n<tr></tr>\n";
private static final String DEPLOY_SECTION =
"</table>\n" +
"<br>\n" +
"<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td colspan=\"2\" class=\"title\">{0}</td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\">\n" +
"<form method=\"post\" action=\"{2}\">\n" +
"<table cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td class=\"row-right\">\n" +
" <small>{3}</small>\n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"text\" name=\"deployPath\" size=\"20\">\n" +
" </td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td class=\"row-right\">\n" +
" <small>{4}</small>\n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"text\" name=\"deployConfig\" size=\"20\">\n" +
" </td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td class=\"row-right\">\n" +
" <small>{5}</small>\n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"text\" name=\"deployWar\" size=\"40\">\n" +
" </td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td class=\"row-right\">\n" +
" \n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"submit\" value=\"{6}\">\n" +
" </td>\n" +
"</tr>\n" +
"</table>\n" +
"</form>\n" +
"</td>\n" +
"</tr>\n";
private static final String UPLOAD_SECTION =
"<tr>\n" +
" <td colspan=\"2\" class=\"header-left\"><small>{0}</small></td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\">\n" +
"<form method=\"post\" action=\"{1}\" " +
"enctype=\"multipart/form-data\">\n" +
"<table cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td class=\"row-right\">\n" +
" <small>{2}</small>\n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"file\" name=\"deployWar\" size=\"40\">\n" +
" </td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td class=\"row-right\">\n" +
" \n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"submit\" value=\"{3}\">\n" +
" </td>\n" +
"</tr>\n" +
"</table>\n" +
"</form>\n" +
"</table>\n" +
"<br>\n" +
"\n";
private static final String DIAGNOSTICS_SECTION =
"<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td colspan=\"2\" class=\"title\">{0}</td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\">\n" +
"<form method=\"post\" action=\"{2}\">\n" +
"<table cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"submit\" value=\"{4}\">\n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <small>{3}</small>\n" +
" </td>\n" +
"</tr>\n" +
"</table>\n" +
"</form>\n" +
"</td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\" class=\"header-left\"><small>{5}</small></td>\n" +
"</tr>\n" +
"<tr>\n" +
" <td colspan=\"2\">\n" +
"<form method=\"post\" action=\"{6}\">\n" +
"<table cellspacing=\"0\" cellpadding=\"3\">\n" +
"<tr>\n" +
" <td class=\"row-left\">\n" +
" <input type=\"submit\" value=\"{7}\">\n" +
" </td>\n" +
" <td class=\"row-left\">\n" +
" <small>{8}</small>\n" +
" </td>\n" +
"</tr>\n" +
"</table>\n" +
"</form>\n" +
"</td>\n" +
"</tr>\n" +
"</table>\n" +
"<br>";
}
|
51,526
|
Bug 51526 Process web application context config with embedded Tomcat.addWebApp(...)
|
It would be nice if org.apache.catalina.startup.Tomcat.addWebApp(...) would process the web application's META-INF/context.xml if found. The current implementation skips META-INF/context.xml loading, and does not appear to offer any hook to enable it--the StandardContext is instantiated and initialized with a null configFile in the single call to addWebApp(...).
|
resolved fixed
|
058f044
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-27T19:22:47Z
| 2011-07-19T01:46:40Z
|
java/org/apache/catalina/startup/Tomcat.java
|
/*
* 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.startup;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Realm;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.Wrapper;
import org.apache.catalina.authenticator.NonLoginAuthenticator;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.NamingContextListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.core.StandardService;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.realm.RealmBase;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
// TODO: lazy init for the temp dir - only when a JSP is compiled or
// get temp dir is called we need to create it. This will avoid the
// need for the baseDir
// TODO: allow contexts without a base dir - i.e.
// only programmatic. This would disable the default servlet.
/**
* Minimal tomcat starter for embedding/unit tests.
*
* Tomcat supports multiple styles of configuration and
* startup - the most common and stable is server.xml-based,
* implemented in org.apache.catalina.startup.Bootstrap.
*
* This class is for use in apps that embed tomcat.
* Requirements:
*
* - all tomcat classes and possibly servlets are in the classpath.
* ( for example all is in one big jar, or in eclipse CP, or in any other
* combination )
*
* - we need one temporary directory for work files
*
* - no config file is required. This class provides methods to
* use if you have a webapp with a web.xml file, but it is
* optional - you can use your own servlets.
*
* There are a variety of 'add' methods to configure servlets and webapps. These
* methods, by default, create a simple in-memory security realm and apply it.
* If you need more complex security processing, you can define a subclass of
* this class.
*
* This class provides a set of convenience methods for configuring webapp
* contexts, all overloads of the method <code>addWebapp</code>. These methods
* create a webapp context, configure it, and then add it to a {@link Host}.
* They do not use a global default web.xml; rather, they add a lifecycle
* listener that adds the standard DefaultServlet, JSP processing, and welcome
* files.
*
* In complex cases, you may prefer to use the ordinary Tomcat API to create
* webapp contexts; for example, you might need to install a custom Loader
* before the call to {@link Host#addChild(Container)}. To replicate the basic
* behavior of the <code>addWebapp</code> methods, you may want to call two
* methods of this class: {@link #noDefaultWebXmlPath()} and
* {@link #getDefaultWebXmlListener()}.
*
* {@link #getDefaultWebXmlListener()} returns a {@link LifecycleListener} that
* adds the standard DefaultServlet, JSP processing, and welcome files. If you
* add this listener, you must prevent Tomcat from applying any standard global
* web.xml with ...
*
* {@link #noDefaultWebXmlPath()} returns a dummy pathname to configure to
* prevent {@link ContextConfig} from trying to apply a global web.xml file.
*
* This class provides a main() and few simple CLI arguments,
* see setters for doc. It can be used for simple tests and
* demo.
*
* @see <a href="http://svn.apache.org/repos/asf/tomcat/trunk/test/org/apache/catalina/startup/TestTomcat.java">TestTomcat</a>
* @author Costin Manolache
*/
public class Tomcat {
// Single engine, service, server, connector - few cases need more,
// they can use server.xml
protected Server server;
protected Service service;
protected Engine engine;
protected Connector connector; // for more - customize the classes
// To make it a bit easier to config for the common case
// ( one host, one context ).
protected Host host;
// TODO: it's easy to add support for more hosts - but is it
// really needed ?
// TODO: allow use of in-memory connector
protected int port = 8080;
protected String hostname = "localhost";
protected String basedir;
private final Map<String, String> userPass = new HashMap<>();
private final Map<String, List<String>> userRoles = new HashMap<>();
private final Map<String, Principal> userPrincipals = new HashMap<>();
public Tomcat() {
// NOOP
}
/**
* Tomcat needs a directory for temp files. This should be the
* first method called.
*
* By default, if this method is not called, we use:
* - system properties - catalina.base, catalina.home
* - $PWD/tomcat.$PORT
* (/tmp doesn't seem a good choice for security).
*
* TODO: disable work dir if not needed ( no jsp, etc ).
*/
public void setBaseDir(String basedir) {
this.basedir = basedir;
}
/**
* Set the port for the default connector. Must
* be called before start().
*/
public void setPort(int port) {
this.port = port;
}
/**
* The the hostname of the default host, default is
* 'localhost'.
*/
public void setHostname(String s) {
hostname = s;
}
/**
* This is equivalent to adding a web application to Tomcat's webapps
* directory. The equivalent of the default web.xml will be applied to the
* web application and any WEB-INF/web.xml packaged with the application
* will be processed normally. Normal web fragment and
* {@link javax.servlet.ServletContainerInitializer} processing will be
* applied.
*
* @throws ServletException
*/
public Context addWebapp(String contextPath, String baseDir)
throws ServletException {
return addWebapp(getHost(), contextPath, baseDir);
}
/**
* Add a context - programmatic mode, no default web.xml used. This means
* that there is no JSP support (no JSP servlet), no default servlet and
* no web socket support unless explicitly enabled via the programmatic
* interface. There is also no
* {@link javax.servlet.ServletContainerInitializer} processing and no
* annotation processing. If a
* {@link javax.servlet.ServletContainerInitializer} is added
* programmatically, there will still be no scanning for
* {@link javax.servlet.annotation.HandlesTypes} matches.
*
* API calls equivalent with web.xml:
*
* context-param
* ctx.addParameter("name", "value");
*
*
* error-page
* ErrorPage ep = new ErrorPage();
* ep.setErrorCode(500);
* ep.setLocation("/error.html");
* ctx.addErrorPage(ep);
*
* ctx.addMimeMapping("ext", "type");
*
* Note: If you reload the Context, all your configuration will be lost. If
* you need reload support, consider using a LifecycleListener to provide
* your configuration.
*
* TODO: add the rest
*
* @param contextPath "" for root context.
* @param baseDir base dir for the context, for static files. Must exist,
* relative to the server home
*/
public Context addContext(String contextPath,
String baseDir) {
return addContext(getHost(), contextPath, baseDir);
}
/**
* Equivalent with
* <servlet><servlet-name><servlet-class>.
*
* In general it is better/faster to use the method that takes a
* Servlet as param - this one can be used if the servlet is not
* commonly used, and want to avoid loading all deps.
* ( for example: jsp servlet )
*
* You can customize the returned servlet, ex:
*
* wrapper.addInitParameter("name", "value");
*
* @param contextPath Context to add Servlet to
* @param servletName Servlet name (used in mappings)
* @param servletClass The class to be used for the Servlet
* @return The wrapper for the servlet
*/
public Wrapper addServlet(String contextPath,
String servletName,
String servletClass) {
Container ctx = getHost().findChild(contextPath);
return addServlet((Context) ctx, servletName, servletClass);
}
/**
* Static version of {@link #addServlet(String, String, String)}
* @param ctx Context to add Servlet to
* @param servletName Servlet name (used in mappings)
* @param servletClass The class to be used for the Servlet
* @return The wrapper for the servlet
*/
public static Wrapper addServlet(Context ctx,
String servletName,
String servletClass) {
// will do class for name and set init params
Wrapper sw = ctx.createWrapper();
sw.setServletClass(servletClass);
sw.setName(servletName);
ctx.addChild(sw);
return sw;
}
/**
* Add an existing Servlet to the context with no class.forName or
* initialisation.
* @param contextPath Context to add Servlet to
* @param servletName Servlet name (used in mappings)
* @param servlet The Servlet to add
* @return The wrapper for the servlet
*/
public Wrapper addServlet(String contextPath,
String servletName,
Servlet servlet) {
Container ctx = getHost().findChild(contextPath);
return addServlet((Context) ctx, servletName, servlet);
}
/**
* Static version of {@link #addServlet(String, String, Servlet)}.
* @param ctx Context to add Servlet to
* @param servletName Servlet name (used in mappings)
* @param servlet The Servlet to add
* @return The wrapper for the servlet
*/
public static Wrapper addServlet(Context ctx,
String servletName,
Servlet servlet) {
// will do class for name and set init params
Wrapper sw = new ExistingStandardWrapper(servlet);
sw.setName(servletName);
ctx.addChild(sw);
return sw;
}
/**
* Initialise the server.
*
* @throws LifecycleException
*/
public void init() throws LifecycleException {
getServer();
getConnector();
server.init();
}
/**
* Start the server.
*
* @throws LifecycleException
*/
public void start() throws LifecycleException {
getServer();
getConnector();
server.start();
}
/**
* Stop the server.
*
* @throws LifecycleException
*/
public void stop() throws LifecycleException {
getServer();
server.stop();
}
/**
* Destroy the server. This object cannot be used once this method has been
* called.
*/
public void destroy() throws LifecycleException {
getServer();
server.destroy();
// Could null out objects here
}
/**
* Add a user for the in-memory realm. All created apps use this
* by default, can be replaced using setRealm().
*
*/
public void addUser(String user, String pass) {
userPass.put(user, pass);
}
/**
* @see #addUser(String, String)
*/
public void addRole(String user, String role) {
List<String> roles = userRoles.get(user);
if (roles == null) {
roles = new ArrayList<>();
userRoles.put(user, roles);
}
roles.add(role);
}
// ------- Extra customization -------
// You can tune individual tomcat objects, using internal APIs
/**
* Get the default http connector. You can set more
* parameters - the port is already initialized.
*
* Alternatively, you can construct a Connector and set any params,
* then call addConnector(Connector)
*
* @return A connector object that can be customized
*/
public Connector getConnector() {
getServer();
if (connector != null) {
return connector;
}
// This will load Apr connector if available,
// default to nio. I'm having strange problems with apr
// XXX: jfclere weird... Don't add the AprLifecycleListener then.
// and for the use case the speed benefit wouldn't matter.
connector = new Connector("HTTP/1.1");
// connector = new Connector("org.apache.coyote.http11.Http11Protocol");
connector.setPort(port);
service.addConnector( connector );
return connector;
}
public void setConnector(Connector connector) {
this.connector = connector;
}
/**
* Get the service object. Can be used to add more
* connectors and few other global settings.
*/
public Service getService() {
getServer();
return service;
}
/**
* Sets the current host - all future webapps will
* be added to this host. When tomcat starts, the
* host will be the default host.
*
* @param host
*/
public void setHost(Host host) {
this.host = host;
}
public Host getHost() {
if (host == null) {
host = new StandardHost();
host.setName(hostname);
getEngine().addChild( host );
}
return host;
}
/**
* Access to the engine, for further customization.
*/
public Engine getEngine() {
if(engine == null ) {
getServer();
engine = new StandardEngine();
engine.setName( "Tomcat" );
engine.setDefaultHost(hostname);
engine.setRealm(createDefaultRealm());
service.setContainer(engine);
}
return engine;
}
/**
* Get the server object. You can add listeners and few more
* customizations. JNDI is disabled by default.
*/
public Server getServer() {
if (server != null) {
return server;
}
System.setProperty("catalina.useNaming", "false");
server = new StandardServer();
initBaseDir();
server.setPort( -1 );
service = new StandardService();
service.setName("Tomcat");
server.addService( service );
return server;
}
/**
* @see #addContext(String, String)
*/
public Context addContext(Host host, String contextPath, String dir) {
return addContext(host, contextPath, contextPath, dir);
}
/**
* @see #addContext(String, String)
*/
public Context addContext(Host host, String contextPath, String contextName,
String dir) {
silence(host, contextPath);
Context ctx = new StandardContext();
ctx.setName(contextName);
ctx.setPath(contextPath);
ctx.setDocBase(dir);
ctx.addLifecycleListener(new FixContextListener());
if (host == null) {
getHost().addChild(ctx);
} else {
host.addChild(ctx);
}
return ctx;
}
/**
* @see #addWebapp(String, String)
*/
public Context addWebapp(Host host, String url, String path) {
return addWebapp(host, url, url, path);
}
/**
* @see #addWebapp(String, String)
*/
public Context addWebapp(Host host, String url, String name, String path) {
silence(host, url);
Context ctx = new StandardContext();
ctx.setName(name);
ctx.setPath(url);
ctx.setDocBase(path);
ctx.addLifecycleListener(new DefaultWebXmlListener());
ContextConfig ctxCfg = new ContextConfig();
ctx.addLifecycleListener(ctxCfg);
// prevent it from looking ( if it finds one - it'll have dup error )
ctxCfg.setDefaultWebXml(noDefaultWebXmlPath());
if (host == null) {
getHost().addChild(ctx);
} else {
host.addChild(ctx);
}
return ctx;
}
/**
* Return a listener that provides the required configuration items for JSP
* processing. From the standard Tomcat global web.xml. Pass this to
* {@link Context#addLifecycleListener(LifecycleListener)} and then pass the
* result of {@link #noDefaultWebXmlPath()} to
* {@link ContextConfig#setDefaultWebXml(String)}.
* @return a listener object that configures default JSP processing.
*/
public LifecycleListener getDefaultWebXmlListener() {
return new DefaultWebXmlListener();
}
/**
* @return a pathname to pass to
* {@link ContextConfig#setDefaultWebXml(String)} when using
* {@link #getDefaultWebXmlListener()}.
*/
public String noDefaultWebXmlPath() {
return Constants.NoDefaultWebXml;
}
// ---------- Helper methods and classes -------------------
/**
* Create an in-memory realm. You can replace it for contexts with a real
* one. The Realm created here will be added to the Engine by default and
* may be replaced at the Engine level or over-ridden (as per normal Tomcat
* behaviour) at the Host or Context level.
*/
protected Realm createDefaultRealm() {
return new RealmBase() {
@Override
protected String getName() {
return "Simple";
}
@Override
protected String getPassword(String username) {
return userPass.get(username);
}
@Override
protected Principal getPrincipal(String username) {
Principal p = userPrincipals.get(username);
if (p == null) {
String pass = userPass.get(username);
if (pass != null) {
p = new GenericPrincipal(username, pass,
userRoles.get(username));
userPrincipals.put(username, p);
}
}
return p;
}
};
}
protected void initBaseDir() {
String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
if (basedir == null) {
basedir = System.getProperty(Globals.CATALINA_BASE_PROP);
}
if (basedir == null) {
basedir = catalinaHome;
}
if (basedir == null) {
// Create a temp dir.
basedir = System.getProperty("user.dir") +
"/tomcat." + port;
}
File baseFile = new File(basedir);
baseFile.mkdirs();
try {
baseFile = baseFile.getCanonicalFile();
} catch (IOException e) {
baseFile = baseFile.getAbsoluteFile();
}
server.setCatalinaBase(baseFile);
System.setProperty(Globals.CATALINA_BASE_PROP, baseFile.getPath());
basedir = baseFile.getPath();
if (catalinaHome == null) {
server.setCatalinaHome(baseFile);
} else {
File homeFile = new File(catalinaHome);
homeFile.mkdirs();
try {
homeFile = homeFile.getCanonicalFile();
} catch (IOException e) {
homeFile = homeFile.getAbsoluteFile();
}
server.setCatalinaHome(homeFile);
}
System.setProperty(Globals.CATALINA_HOME_PROP,
server.getCatalinaHome().getPath());
}
static final String[] silences = new String[] {
"org.apache.coyote.http11.Http11Protocol",
"org.apache.catalina.core.StandardService",
"org.apache.catalina.core.StandardEngine",
"org.apache.catalina.startup.ContextConfig",
"org.apache.catalina.core.ApplicationContext",
"org.apache.catalina.core.AprLifecycleListener"
};
/**
* Controls if the loggers will be silenced or not.
* @param silent <code>true</code> sets the log level to WARN for the
* loggers that log information on Tomcat start up. This
* prevents the usual startup information being logged.
* <code>false</code> sets the log level to the default
* level of INFO.
*/
public void setSilent(boolean silent) {
for (String s : silences) {
if (silent) {
Logger.getLogger(s).setLevel(Level.WARNING);
} else {
Logger.getLogger(s).setLevel(Level.INFO);
}
}
}
private void silence(Host host, String ctx) {
String base = "org.apache.catalina.core.ContainerBase.[default].[";
if (host == null) {
base += getHost().getName();
} else {
base += host.getName();
}
base += "].[";
base += ctx;
base += "]";
Logger.getLogger(base).setLevel(Level.WARNING);
}
/**
* Enables JNDI naming which is disabled by default. Server must implement
* {@link Lifecycle} in order for the {@link NamingContextListener} to be
* used.
*
*/
public void enableNaming() {
// Make sure getServer() has been called as that is where naming is
// disabled
getServer();
server.addLifecycleListener(new NamingContextListener());
System.setProperty("catalina.useNaming", "true");
String value = "org.apache.naming";
String oldValue =
System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
if (oldValue != null) {
if (oldValue.contains(value)) {
value = oldValue;
} else {
value = value + ":" + oldValue;
}
}
System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
value = System.getProperty
(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
if (value == null) {
System.setProperty
(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
}
}
/**
* Provide default configuration for a context. This is the programmatic
* equivalent of the default web.xml.
*
* TODO: in normal Tomcat, if default-web.xml is not found, use this
* method
*
* @param contextPath The context to set the defaults for
*/
public void initWebappDefaults(String contextPath) {
Container ctx = getHost().findChild(contextPath);
initWebappDefaults((Context) ctx);
}
/**
* Static version of {@link #initWebappDefaults(String)}
* @param ctx The context to set the defaults for
*/
public static void initWebappDefaults(Context ctx) {
// Default servlet
Wrapper servlet = addServlet(
ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
servlet.setLoadOnStartup(1);
servlet.setOverridable(true);
// JSP servlet (by class name - to avoid loading all deps)
servlet = addServlet(
ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
servlet.addInitParameter("fork", "false");
servlet.setLoadOnStartup(3);
servlet.setOverridable(true);
// Servlet mappings
ctx.addServletMapping("/", "default");
ctx.addServletMapping("*.jsp", "jsp");
ctx.addServletMapping("*.jspx", "jsp");
// Sessions
ctx.setSessionTimeout(30);
// MIME mappings
for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
DEFAULT_MIME_MAPPINGS[i++]);
}
// Welcome files
ctx.addWelcomeFile("index.html");
ctx.addWelcomeFile("index.htm");
ctx.addWelcomeFile("index.jsp");
}
/**
* Fix startup sequence - required if you don't use web.xml.
*
* The start() method in context will set 'configured' to false - and
* expects a listener to set it back to true.
*/
public static class FixContextListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent event) {
try {
Context context = (Context) event.getLifecycle();
if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
context.setConfigured(true);
}
// LoginConfig is required to process @ServletSecurity
// annotations
if (context.getLoginConfig() == null) {
context.setLoginConfig(
new LoginConfig("NONE", null, null, null));
context.getPipeline().addValve(new NonLoginAuthenticator());
}
} catch (ClassCastException e) {
return;
}
}
}
/**
* Fix reload - required if reloading and using programmatic configuration.
* When a context is reloaded, any programmatic configuration is lost. This
* listener sets the equivalent of conf/web.xml when the context starts.
*/
public static class DefaultWebXmlListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent event) {
if (Lifecycle.BEFORE_START_EVENT.equals(event.getType())) {
initWebappDefaults((Context) event.getLifecycle());
}
}
}
/**
* Helper class for wrapping existing servlets. This disables servlet
* lifecycle and normal reloading, but also reduces overhead and provide
* more direct control over the servlet.
*/
public static class ExistingStandardWrapper extends StandardWrapper {
private final Servlet existing;
@SuppressWarnings("deprecation")
public ExistingStandardWrapper( Servlet existing ) {
this.existing = existing;
if (existing instanceof javax.servlet.SingleThreadModel) {
singleThreadModel = true;
instancePool = new Stack<>();
}
this.asyncSupported = hasAsync();
}
public boolean hasAsync() {
if (isAsyncSupported()) return true;
boolean result = false;
Class<?> clazz = existing.getClass();
if (clazz.isAnnotationPresent(WebServlet.class)) {
WebServlet ws = clazz.getAnnotation(WebServlet.class);
result = ws.asyncSupported();
}
return result;
}
@Override
public synchronized Servlet loadServlet() throws ServletException {
if (singleThreadModel) {
Servlet instance;
try {
instance = existing.getClass().newInstance();
} catch (InstantiationException e) {
throw new ServletException(e);
} catch (IllegalAccessException e) {
throw new ServletException(e);
}
instance.init(facade);
return instance;
} else {
if (!instanceInitialized) {
existing.init(facade);
instanceInitialized = true;
}
return existing;
}
}
@Override
public long getAvailable() {
return 0;
}
@Override
public boolean isUnavailable() {
return false;
}
@Override
public Servlet getServlet() {
return existing;
}
@Override
public String getServletClass() {
return existing.getClass().getName();
}
}
/**
* TODO: would a properties resource be better ? Or just parsing
* /etc/mime.types ?
* This is needed because we don't use the default web.xml, where this
* is encoded.
*/
private static final String[] DEFAULT_MIME_MAPPINGS = {
"abs", "audio/x-mpeg",
"ai", "application/postscript",
"aif", "audio/x-aiff",
"aifc", "audio/x-aiff",
"aiff", "audio/x-aiff",
"aim", "application/x-aim",
"art", "image/x-jg",
"asf", "video/x-ms-asf",
"asx", "video/x-ms-asf",
"au", "audio/basic",
"avi", "video/x-msvideo",
"avx", "video/x-rad-screenplay",
"bcpio", "application/x-bcpio",
"bin", "application/octet-stream",
"bmp", "image/bmp",
"body", "text/html",
"cdf", "application/x-cdf",
"cer", "application/pkix-cert",
"class", "application/java",
"cpio", "application/x-cpio",
"csh", "application/x-csh",
"css", "text/css",
"dib", "image/bmp",
"doc", "application/msword",
"dtd", "application/xml-dtd",
"dv", "video/x-dv",
"dvi", "application/x-dvi",
"eps", "application/postscript",
"etx", "text/x-setext",
"exe", "application/octet-stream",
"gif", "image/gif",
"gtar", "application/x-gtar",
"gz", "application/x-gzip",
"hdf", "application/x-hdf",
"hqx", "application/mac-binhex40",
"htc", "text/x-component",
"htm", "text/html",
"html", "text/html",
"ief", "image/ief",
"jad", "text/vnd.sun.j2me.app-descriptor",
"jar", "application/java-archive",
"java", "text/x-java-source",
"jnlp", "application/x-java-jnlp-file",
"jpe", "image/jpeg",
"jpeg", "image/jpeg",
"jpg", "image/jpeg",
"js", "application/javascript",
"jsf", "text/plain",
"jspf", "text/plain",
"kar", "audio/midi",
"latex", "application/x-latex",
"m3u", "audio/x-mpegurl",
"mac", "image/x-macpaint",
"man", "text/troff",
"mathml", "application/mathml+xml",
"me", "text/troff",
"mid", "audio/midi",
"midi", "audio/midi",
"mif", "application/x-mif",
"mov", "video/quicktime",
"movie", "video/x-sgi-movie",
"mp1", "audio/mpeg",
"mp2", "audio/mpeg",
"mp3", "audio/mpeg",
"mp4", "video/mp4",
"mpa", "audio/mpeg",
"mpe", "video/mpeg",
"mpeg", "video/mpeg",
"mpega", "audio/x-mpeg",
"mpg", "video/mpeg",
"mpv2", "video/mpeg2",
"nc", "application/x-netcdf",
"oda", "application/oda",
"odb", "application/vnd.oasis.opendocument.database",
"odc", "application/vnd.oasis.opendocument.chart",
"odf", "application/vnd.oasis.opendocument.formula",
"odg", "application/vnd.oasis.opendocument.graphics",
"odi", "application/vnd.oasis.opendocument.image",
"odm", "application/vnd.oasis.opendocument.text-master",
"odp", "application/vnd.oasis.opendocument.presentation",
"ods", "application/vnd.oasis.opendocument.spreadsheet",
"odt", "application/vnd.oasis.opendocument.text",
"otg", "application/vnd.oasis.opendocument.graphics-template",
"oth", "application/vnd.oasis.opendocument.text-web",
"otp", "application/vnd.oasis.opendocument.presentation-template",
"ots", "application/vnd.oasis.opendocument.spreadsheet-template ",
"ott", "application/vnd.oasis.opendocument.text-template",
"ogx", "application/ogg",
"ogv", "video/ogg",
"oga", "audio/ogg",
"ogg", "audio/ogg",
"spx", "audio/ogg",
"flac", "audio/flac",
"anx", "application/annodex",
"axa", "audio/annodex",
"axv", "video/annodex",
"xspf", "application/xspf+xml",
"pbm", "image/x-portable-bitmap",
"pct", "image/pict",
"pdf", "application/pdf",
"pgm", "image/x-portable-graymap",
"pic", "image/pict",
"pict", "image/pict",
"pls", "audio/x-scpls",
"png", "image/png",
"pnm", "image/x-portable-anymap",
"pnt", "image/x-macpaint",
"ppm", "image/x-portable-pixmap",
"ppt", "application/vnd.ms-powerpoint",
"pps", "application/vnd.ms-powerpoint",
"ps", "application/postscript",
"psd", "image/vnd.adobe.photoshop",
"qt", "video/quicktime",
"qti", "image/x-quicktime",
"qtif", "image/x-quicktime",
"ras", "image/x-cmu-raster",
"rdf", "application/rdf+xml",
"rgb", "image/x-rgb",
"rm", "application/vnd.rn-realmedia",
"roff", "text/troff",
"rtf", "application/rtf",
"rtx", "text/richtext",
"sh", "application/x-sh",
"shar", "application/x-shar",
/*"shtml", "text/x-server-parsed-html",*/
"sit", "application/x-stuffit",
"snd", "audio/basic",
"src", "application/x-wais-source",
"sv4cpio", "application/x-sv4cpio",
"sv4crc", "application/x-sv4crc",
"svg", "image/svg+xml",
"svgz", "image/svg+xml",
"swf", "application/x-shockwave-flash",
"t", "text/troff",
"tar", "application/x-tar",
"tcl", "application/x-tcl",
"tex", "application/x-tex",
"texi", "application/x-texinfo",
"texinfo", "application/x-texinfo",
"tif", "image/tiff",
"tiff", "image/tiff",
"tr", "text/troff",
"tsv", "text/tab-separated-values",
"txt", "text/plain",
"ulw", "audio/basic",
"ustar", "application/x-ustar",
"vxml", "application/voicexml+xml",
"xbm", "image/x-xbitmap",
"xht", "application/xhtml+xml",
"xhtml", "application/xhtml+xml",
"xls", "application/vnd.ms-excel",
"xml", "application/xml",
"xpm", "image/x-xpixmap",
"xsl", "application/xml",
"xslt", "application/xslt+xml",
"xul", "application/vnd.mozilla.xul+xml",
"xwd", "image/x-xwindowdump",
"vsd", "application/vnd.visio",
"wav", "audio/x-wav",
"wbmp", "image/vnd.wap.wbmp",
"wml", "text/vnd.wap.wml",
"wmlc", "application/vnd.wap.wmlc",
"wmls", "text/vnd.wap.wmlsc",
"wmlscriptc", "application/vnd.wap.wmlscriptc",
"wmv", "video/x-ms-wmv",
"wrl", "model/vrml",
"wspolicy", "application/wspolicy+xml",
"Z", "application/x-compress",
"z", "application/x-compress",
"zip", "application/zip"
};
}
|
51,526
|
Bug 51526 Process web application context config with embedded Tomcat.addWebApp(...)
|
It would be nice if org.apache.catalina.startup.Tomcat.addWebApp(...) would process the web application's META-INF/context.xml if found. The current implementation skips META-INF/context.xml loading, and does not appear to offer any hook to enable it--the StandardContext is instantiated and initialized with a null configFile in the single call to addWebApp(...).
|
resolved fixed
|
058f044
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-27T19:22:47Z
| 2011-07-19T01:46:40Z
|
test/org/apache/catalina/startup/TestTomcat.java
|
/*
* 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.startup;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.atomic.AtomicInteger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.descriptor.web.ApplicationListener;
import org.apache.tomcat.util.descriptor.web.ContextEnvironment;
import org.apache.tomcat.util.descriptor.web.ContextResourceLink;
import org.apache.tomcat.websocket.server.WsListener;
public class TestTomcat extends TomcatBaseTest {
/**
* Simple servlet to test in-line registration.
*/
public static class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.getWriter().write("Hello world");
}
}
/**
* Simple servlet to test the default session manager.
*/
public static class HelloWorldSession extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
HttpSession s = req.getSession(true);
s.getId();
res.getWriter().write("Hello world");
}
}
/**
* Simple servlet to test JNDI
*/
public static class HelloWorldJndi extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String JNDI_ENV_NAME = "test";
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
String name = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
name = (String) envCtx.lookup(JNDI_ENV_NAME);
} catch (NamingException e) {
throw new IOException(e);
}
res.getWriter().write("Hello, " + name);
}
}
/**
* Servlet that tries to obtain a URL for WEB-INF/web.xml
*/
public static class GetResource extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
URL url = req.getServletContext().getResource("/WEB-INF/web.xml");
res.getWriter().write("The URL obtained for /WEB-INF/web.xml was ");
if (url == null) {
res.getWriter().write("null");
} else {
res.getWriter().write(url.toString() + "\n");
res.getWriter().write("The first 20 characters of that resource are:\n");
// Read some content from the resource
URLConnection conn = url.openConnection();
InputStream is = null;
Reader reader = null;
char cbuf[] = new char[20];
int read = 0;
try {
is = conn.getInputStream();
reader = new InputStreamReader(is);
while (read < 20) {
int len = reader.read(cbuf, read, cbuf.length - read);
res.getWriter().write(cbuf, read, len);
read = read + len;
}
} finally {
if (reader != null) {
try { reader.close(); } catch(IOException ioe) {/*Ignore*/}
}
if (is != null) {
try { is.close(); } catch(IOException ioe) {/*Ignore*/}
}
}
}
}
}
/**
* Simple servlet to test initialization of servlet instances.
*/
private static class InitCount extends HttpServlet {
private static final long serialVersionUID = 1L;
private AtomicInteger callCount = new AtomicInteger(0);
@Override
public void init() throws ServletException {
super.init();
callCount.incrementAndGet();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.getWriter().print("OK");
}
public int getCallCount() {
return callCount.intValue();
}
}
/**
* Start tomcat with a single context and one
* servlet - all programmatic, no server.xml or
* web.xml used.
*
* @throws Exception
*/
@Test
public void testProgrammatic() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
org.apache.catalina.Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
// You can customize the context by calling
// its API
Tomcat.addServlet(ctx, "myServlet", new HelloWorld());
ctx.addServletMapping("/", "myServlet");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
assertEquals("Hello world", res.toString());
}
@Test
public void testSingleWebapp() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File(getBuildDirectory(), "webapps/examples");
// app dir is relative to server home
org.apache.catalina.Context ctxt = tomcat.addWebapp(
null, "/examples", appDir.getAbsolutePath());
ctxt.addApplicationListener(new ApplicationListener(
WsListener.class.getName(), false));
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/examples/servlets/servlet/HelloWorldExample");
assertTrue(res.toString().indexOf("<h1>Hello World!</h1>") > 0);
}
@Test
public void testJsps() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File(getBuildDirectory(), "webapps/examples");
// app dir is relative to server home
org.apache.catalina.Context ctxt = tomcat.addWebapp(
null, "/examples", appDir.getAbsolutePath());
ctxt.addApplicationListener(new ApplicationListener(
WsListener.class.getName(), false));
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/examples/jsp/jsp2/el/basic-arithmetic.jsp");
assertTrue(res.toString().indexOf("<td>${(1==2) ? 3 : 4}</td>") > 0);
}
@Test
public void testSession() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
org.apache.catalina.Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
// You can customize the context by calling
// its API
Tomcat.addServlet(ctx, "myServlet", new HelloWorldSession());
ctx.addServletMapping("/", "myServlet");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
assertEquals("Hello world", res.toString());
}
@Test
public void testLaunchTime() throws Exception {
Tomcat tomcat = getTomcatInstance();
long t0 = System.currentTimeMillis();
tomcat.addContext(null, "/", ".");
tomcat.start();
System.err.println("Test time: " +
(System.currentTimeMillis() - t0));
}
/**
* Test for enabling JNDI.
*/
@Test
public void testEnableNaming() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
org.apache.catalina.Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
// You can customise the context by calling its API
// Enable JNDI - it is disabled by default
tomcat.enableNaming();
ContextEnvironment environment = new ContextEnvironment();
environment.setType("java.lang.String");
environment.setName(HelloWorldJndi.JNDI_ENV_NAME);
environment.setValue("Tomcat User");
ctx.getNamingResources().addEnvironment(environment);
Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi());
ctx.addServletMapping("/", "jndiServlet");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
assertEquals("Hello, Tomcat User", res.toString());
}
/**
* Test for enabling JNDI and using global resources.
*/
@Test
public void testEnableNamingGlobal() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
org.apache.catalina.Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
// You can customise the context by calling its API
// Enable JNDI - it is disabled by default
tomcat.enableNaming();
ContextEnvironment environment = new ContextEnvironment();
environment.setType("java.lang.String");
environment.setName("globalTest");
environment.setValue("Tomcat User");
tomcat.getServer().getGlobalNamingResources().addEnvironment(environment);
ContextResourceLink link = new ContextResourceLink();
link.setGlobal("globalTest");
link.setName(HelloWorldJndi.JNDI_ENV_NAME);
ctx.getNamingResources().addResourceLink(link);
Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi());
ctx.addServletMapping("/", "jndiServlet");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
assertEquals("Hello, Tomcat User", res.toString());
}
/**
* Test for https://issues.apache.org/bugzilla/show_bug.cgi?id=47866
*/
@Test
public void testGetResource() throws Exception {
Tomcat tomcat = getTomcatInstance();
String contextPath = "/examples";
File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
// app dir is relative to server home
org.apache.catalina.Context ctx =
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
ctx.addApplicationListener(new ApplicationListener(
WsListener.class.getName(), false));
Tomcat.addServlet(ctx, "testGetResource", new GetResource());
ctx.addServletMapping("/testGetResource", "testGetResource");
tomcat.start();
ByteChunk res = new ByteChunk();
int rc =getUrl("http://localhost:" + getPort() + contextPath +
"/testGetResource", res, null);
assertEquals(HttpServletResponse.SC_OK, rc);
assertTrue(res.toString().contains("<?xml version=\"1.0\" "));
}
@Test
public void testBug50826() throws Exception {
Tomcat tomcat = getTomcatInstance();
String contextPath = "/examples";
File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
// app dir is relative to server home
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
Exception e = null;
try {
tomcat.destroy();
} catch (Exception ex) {
ex.printStackTrace();
e = ex;
}
assertNull(e);
}
@Test
public void testBug53301() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
org.apache.catalina.Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
InitCount initCount = new InitCount();
Tomcat.addServlet(ctx, "initCount", initCount);
ctx.addServletMapping("/", "initCount");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
assertEquals("OK", res.toString());
assertEquals(1, initCount.getCallCount());
}
}
|
55,453
|
Bug 55453 AJP send Body with Status 304
| null |
resolved fixed
|
6d99103
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-28T13:01:03Z
| 2013-08-20T09:13:20Z
|
java/org/apache/coyote/ajp/AbstractAjpProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.http.HttpUpgradeHandler;
import org.apache.coyote.AbstractProcessor;
import org.apache.coyote.ActionCode;
import org.apache.coyote.AsyncContextCallback;
import org.apache.coyote.InputBuffer;
import org.apache.coyote.OutputBuffer;
import org.apache.coyote.Request;
import org.apache.coyote.RequestInfo;
import org.apache.coyote.Response;
import org.apache.juli.logging.Log;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.HexUtils;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.HttpMessages;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.SSLSupport;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.res.StringManager;
/**
* Base class for AJP Processor implementations.
*/
public abstract class AbstractAjpProcessor<S> extends AbstractProcessor<S> {
protected abstract Log getLog();
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* End message array.
*/
protected static final byte[] endMessageArray;
protected static final byte[] endAndCloseMessageArray;
/**
* Flush message array.
*/
protected static final byte[] flushMessageArray;
/**
* Pong message array.
*/
protected static final byte[] pongMessageArray;
static {
// Allocate the end message array
AjpMessage endMessage = new AjpMessage(16);
endMessage.reset();
endMessage.appendByte(Constants.JK_AJP13_END_RESPONSE);
endMessage.appendByte(1);
endMessage.end();
endMessageArray = new byte[endMessage.getLen()];
System.arraycopy(endMessage.getBuffer(), 0, endMessageArray, 0,
endMessage.getLen());
// Allocate the end and close message array
AjpMessage endAndCloseMessage = new AjpMessage(16);
endAndCloseMessage.reset();
endAndCloseMessage.appendByte(Constants.JK_AJP13_END_RESPONSE);
endAndCloseMessage.appendByte(0);
endAndCloseMessage.end();
endAndCloseMessageArray = new byte[endAndCloseMessage.getLen()];
System.arraycopy(endAndCloseMessage.getBuffer(), 0, endAndCloseMessageArray, 0,
endAndCloseMessage.getLen());
// Allocate the flush message array
AjpMessage flushMessage = new AjpMessage(16);
flushMessage.reset();
flushMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
flushMessage.appendInt(0);
flushMessage.appendByte(0);
flushMessage.end();
flushMessageArray = new byte[flushMessage.getLen()];
System.arraycopy(flushMessage.getBuffer(), 0, flushMessageArray, 0,
flushMessage.getLen());
// Allocate the pong message array
AjpMessage pongMessage = new AjpMessage(16);
pongMessage.reset();
pongMessage.appendByte(Constants.JK_AJP13_CPONG_REPLY);
pongMessage.end();
pongMessageArray = new byte[pongMessage.getLen()];
System.arraycopy(pongMessage.getBuffer(), 0, pongMessageArray,
0, pongMessage.getLen());
}
// ----------------------------------------------------- Instance Variables
/**
* GetBody message array. Not static like the other message arrays since the
* message varies with packetSize and that can vary per connector.
*/
protected final byte[] getBodyMessageArray;
/**
* AJP packet size.
*/
protected final int packetSize;
/**
* Header message. Note that this header is merely the one used during the
* processing of the first message of a "request", so it might not be a
* request header. It will stay unchanged during the processing of the whole
* request.
*/
protected final AjpMessage requestHeaderMessage;
/**
* Message used for response composition.
*/
protected final AjpMessage responseMessage;
/**
* Body message.
*/
protected final AjpMessage bodyMessage;
/**
* Body message.
*/
protected final MessageBytes bodyBytes = MessageBytes.newInstance();
/**
* Error flag.
*/
protected boolean error = false;
/**
* Host name (used to avoid useless B2C conversion on the host name).
*/
protected char[] hostNameC = new char[0];
/**
* Temp message bytes used for processing.
*/
protected final MessageBytes tmpMB = MessageBytes.newInstance();
/**
* Byte chunk for certs.
*/
protected final MessageBytes certificates = MessageBytes.newInstance();
/**
* End of stream flag.
*/
protected boolean endOfStream = false;
/**
* Request body empty flag.
*/
protected boolean empty = true;
/**
* First read.
*/
protected boolean first = true;
/**
* Replay read.
*/
protected boolean replay = false;
/**
* Finished response.
*/
protected boolean finished = false;
/**
* Bytes written to client for the current request.
*/
protected long bytesWritten = 0;
// ------------------------------------------------------------ Constructor
public AbstractAjpProcessor(int packetSize, AbstractEndpoint endpoint) {
super(endpoint);
this.packetSize = packetSize;
request.setInputBuffer(new SocketInputBuffer());
requestHeaderMessage = new AjpMessage(packetSize);
responseMessage = new AjpMessage(packetSize);
bodyMessage = new AjpMessage(packetSize);
// Set the getBody message buffer
AjpMessage getBodyMessage = new AjpMessage(16);
getBodyMessage.reset();
getBodyMessage.appendByte(Constants.JK_AJP13_GET_BODY_CHUNK);
// Adjust read size if packetSize != default (Constants.MAX_PACKET_SIZE)
getBodyMessage.appendInt(Constants.MAX_READ_SIZE + packetSize -
Constants.MAX_PACKET_SIZE);
getBodyMessage.end();
getBodyMessageArray = new byte[getBodyMessage.getLen()];
System.arraycopy(getBodyMessage.getBuffer(), 0, getBodyMessageArray,
0, getBodyMessage.getLen());
}
// ------------------------------------------------------------- Properties
/**
* The number of milliseconds Tomcat will wait for a subsequent request
* before closing the connection. The default is the same as for
* Apache HTTP Server (15 000 milliseconds).
*/
protected int keepAliveTimeout = -1;
public int getKeepAliveTimeout() { return keepAliveTimeout; }
public void setKeepAliveTimeout(int timeout) { keepAliveTimeout = timeout; }
/**
* Use Tomcat authentication ?
*/
protected boolean tomcatAuthentication = true;
public boolean getTomcatAuthentication() { return tomcatAuthentication; }
public void setTomcatAuthentication(boolean tomcatAuthentication) {
this.tomcatAuthentication = tomcatAuthentication;
}
/**
* Required secret.
*/
protected String requiredSecret = null;
public void setRequiredSecret(String requiredSecret) {
this.requiredSecret = requiredSecret;
}
/**
* When client certificate information is presented in a form other than
* instances of {@link java.security.cert.X509Certificate} it needs to be
* converted before it can be used and this property controls which JSSE
* provider is used to perform the conversion. For example it is used with
* the AJP connectors, the HTTP APR connector and with the
* {@link org.apache.catalina.valves.SSLValve}. If not specified, the
* default provider will be used.
*/
protected String clientCertProvider = null;
public String getClientCertProvider() { return clientCertProvider; }
public void setClientCertProvider(String s) { this.clientCertProvider = s; }
// --------------------------------------------------------- Public Methods
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
public final void action(ActionCode actionCode, Object param) {
if (actionCode == ActionCode.COMMIT) {
if (response.isCommitted())
return;
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
}
try {
flush(false);
} catch (IOException e) {
// Set error flag
error = true;
}
} else if (actionCode == ActionCode.CLIENT_FLUSH) {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
return;
}
}
try {
flush(true);
} catch (IOException e) {
// Set error flag
error = true;
}
} else if (actionCode == ActionCode.DISABLE_SWALLOW_INPUT) {
// TODO: Do not swallow request input but
// make sure we are closing the connection
error = true;
} else if (actionCode == ActionCode.CLOSE) {
// Close
// End the processing of the current request, and stop any further
// transactions with the client
try {
finish();
} catch (IOException e) {
// Set error flag
error = true;
}
} else if (actionCode == ActionCode.REQ_SSL_ATTRIBUTE ) {
if (!certificates.isNull()) {
ByteChunk certData = certificates.getByteChunk();
X509Certificate jsseCerts[] = null;
ByteArrayInputStream bais =
new ByteArrayInputStream(certData.getBytes(),
certData.getStart(),
certData.getLength());
// Fill the elements.
try {
CertificateFactory cf;
if (clientCertProvider == null) {
cf = CertificateFactory.getInstance("X.509");
} else {
cf = CertificateFactory.getInstance("X.509",
clientCertProvider);
}
while(bais.available() > 0) {
X509Certificate cert = (X509Certificate)
cf.generateCertificate(bais);
if(jsseCerts == null) {
jsseCerts = new X509Certificate[1];
jsseCerts[0] = cert;
} else {
X509Certificate [] temp = new X509Certificate[jsseCerts.length+1];
System.arraycopy(jsseCerts,0,temp,0,jsseCerts.length);
temp[jsseCerts.length] = cert;
jsseCerts = temp;
}
}
} catch (java.security.cert.CertificateException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
} catch (NoSuchProviderException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
}
request.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts);
}
} else if (actionCode == ActionCode.REQ_HOST_ATTRIBUTE) {
// Get remote host name using a DNS resolution
if (request.remoteHost().isNull()) {
try {
request.remoteHost().setString(InetAddress.getByName
(request.remoteAddr().toString()).getHostName());
} catch (IOException iex) {
// Ignore
}
}
} else if (actionCode == ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE) {
// Copy from local name for now, which should simply be an address
request.localAddr().setString(request.localName().toString());
} else if (actionCode == ActionCode.REQ_SET_BODY_REPLAY) {
// Set the given bytes as the content
ByteChunk bc = (ByteChunk) param;
int length = bc.getLength();
bodyBytes.setBytes(bc.getBytes(), bc.getStart(), length);
request.setContentLength(length);
first = false;
empty = false;
replay = true;
endOfStream = false;
} else if (actionCode == ActionCode.ASYNC_START) {
asyncStateMachine.asyncStart((AsyncContextCallback) param);
} else if (actionCode == ActionCode.ASYNC_DISPATCHED) {
asyncStateMachine.asyncDispatched();
} else if (actionCode == ActionCode.ASYNC_TIMEOUT) {
AtomicBoolean result = (AtomicBoolean) param;
result.set(asyncStateMachine.asyncTimeout());
} else if (actionCode == ActionCode.ASYNC_RUN) {
asyncStateMachine.asyncRun((Runnable) param);
} else if (actionCode == ActionCode.ASYNC_ERROR) {
asyncStateMachine.asyncError();
} else if (actionCode == ActionCode.ASYNC_IS_STARTED) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted());
} else if (actionCode == ActionCode.ASYNC_IS_DISPATCHING) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching());
} else if (actionCode == ActionCode.ASYNC_IS_ASYNC) {
((AtomicBoolean) param).set(asyncStateMachine.isAsync());
} else if (actionCode == ActionCode.ASYNC_IS_TIMINGOUT) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut());
} else if (actionCode == ActionCode.ASYNC_IS_ERROR) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncError());
} else if (actionCode == ActionCode.UPGRADE) {
// HTTP connections only. Unsupported for AJP.
// NOOP
} else {
actionInternal(actionCode, param);
}
}
@Override
public SocketState asyncDispatch(SocketStatus status) {
RequestInfo rp = request.getRequestProcessor();
try {
rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
error = !getAdapter().asyncDispatch(request, response, status);
} catch (InterruptedIOException e) {
error = true;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().error(sm.getString("http11processor.request.process"), t);
error = true;
} finally {
if (error) {
// 500 - Internal Server Error
response.setStatus(500);
getAdapter().log(request, response, 0);
}
}
rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
if (isAsync()) {
if (error) {
request.updateCounters();
return SocketState.CLOSED;
} else {
return SocketState.LONG;
}
} else {
request.updateCounters();
if (error) {
return SocketState.CLOSED;
} else {
return SocketState.OPEN;
}
}
}
@Override
public void setSslSupport(SSLSupport sslSupport) {
// Should never reach this code but in case we do...
throw new IllegalStateException(
sm.getString("ajpprocessor.ssl.notsupported"));
}
@Override
public SocketState event(SocketStatus status) throws IOException {
// Should never reach this code but in case we do...
throw new IOException(
sm.getString("ajpprocessor.comet.notsupported"));
}
@Override
public SocketState upgradeDispatch(SocketStatus status) throws IOException {
// Should never reach this code but in case we do...
throw new IOException(
sm.getString("ajpprocessor.httpupgrade.notsupported"));
}
@Override
public HttpUpgradeHandler getHttpUpgradeHandler() {
// Should never reach this code but in case we do...
throw new IllegalStateException(
sm.getString("ajpprocessor.httpupgrade.notsupported"));
}
/**
* Recycle the processor, ready for the next request which may be on the
* same connection or a different connection.
*
* @param socketClosing Indicates if the socket is about to be closed
* allowing the processor to perform any additional
* clean-up that may be required
*/
@Override
public void recycle(boolean socketClosing) {
asyncStateMachine.recycle();
// Recycle Request object
first = true;
endOfStream = false;
empty = true;
replay = false;
finished = false;
request.recycle();
response.recycle();
certificates.recycle();
bytesWritten = 0;
}
// ------------------------------------------------------ Protected Methods
// Methods called by action()
protected abstract void actionInternal(ActionCode actionCode, Object param);
// Methods called by prepareResponse()
protected abstract void output(byte[] src, int offset, int length)
throws IOException;
// Methods used by SocketInputBuffer
protected abstract boolean receive() throws IOException;
@Override
public final boolean isComet() {
// AJP does not support Comet
return false;
}
@Override
public final boolean isUpgrade() {
// AJP does not support HTTP upgrade
return false;
}
/**
* Get more request body data from the web server and store it in the
* internal buffer.
*
* @return true if there is more data, false if not.
*/
protected boolean refillReadBuffer() throws IOException {
// If the server returns an empty packet, assume that that end of
// the stream has been reached (yuck -- fix protocol??).
// FORM support
if (replay) {
endOfStream = true; // we've read everything there is
}
if (endOfStream) {
return false;
}
// Request more data immediately
output(getBodyMessageArray, 0, getBodyMessageArray.length);
boolean moreData = receive();
if( !moreData ) {
endOfStream = true;
}
return moreData;
}
/**
* After reading the request headers, we have to setup the request filters.
*/
protected void prepareRequest() {
// Translate the HTTP method code to a String.
byte methodCode = requestHeaderMessage.getByte();
if (methodCode != Constants.SC_M_JK_STORED) {
String methodName = Constants.getMethodForCode(methodCode - 1);
request.method().setString(methodName);
}
requestHeaderMessage.getBytes(request.protocol());
requestHeaderMessage.getBytes(request.requestURI());
requestHeaderMessage.getBytes(request.remoteAddr());
requestHeaderMessage.getBytes(request.remoteHost());
requestHeaderMessage.getBytes(request.localName());
request.setLocalPort(requestHeaderMessage.getInt());
boolean isSSL = requestHeaderMessage.getByte() != 0;
if (isSSL) {
request.scheme().setString("https");
}
// Decode headers
MimeHeaders headers = request.getMimeHeaders();
// Set this every time in case limit has been changed via JMX
headers.setLimit(endpoint.getMaxHeaderCount());
int hCount = requestHeaderMessage.getInt();
for(int i = 0 ; i < hCount ; i++) {
String hName = null;
// Header names are encoded as either an integer code starting
// with 0xA0, or as a normal string (in which case the first
// two bytes are the length).
int isc = requestHeaderMessage.peekInt();
int hId = isc & 0xFF;
MessageBytes vMB = null;
isc &= 0xFF00;
if(0xA000 == isc) {
requestHeaderMessage.getInt(); // To advance the read position
hName = Constants.getHeaderForCode(hId - 1);
vMB = headers.addValue(hName);
} else {
// reset hId -- if the header currently being read
// happens to be 7 or 8 bytes long, the code below
// will think it's the content-type header or the
// content-length header - SC_REQ_CONTENT_TYPE=7,
// SC_REQ_CONTENT_LENGTH=8 - leading to unexpected
// behaviour. see bug 5861 for more information.
hId = -1;
requestHeaderMessage.getBytes(tmpMB);
ByteChunk bc = tmpMB.getByteChunk();
vMB = headers.addValue(bc.getBuffer(),
bc.getStart(), bc.getLength());
}
requestHeaderMessage.getBytes(vMB);
if (hId == Constants.SC_REQ_CONTENT_LENGTH ||
(hId == -1 && tmpMB.equalsIgnoreCase("Content-Length"))) {
// just read the content-length header, so set it
request.setContentLength(vMB.getLong());
} else if (hId == Constants.SC_REQ_CONTENT_TYPE ||
(hId == -1 && tmpMB.equalsIgnoreCase("Content-Type"))) {
// just read the content-type header, so set it
ByteChunk bchunk = vMB.getByteChunk();
request.contentType().setBytes(bchunk.getBytes(),
bchunk.getOffset(),
bchunk.getLength());
}
}
// Decode extra attributes
boolean secret = false;
byte attributeCode;
while ((attributeCode = requestHeaderMessage.getByte())
!= Constants.SC_A_ARE_DONE) {
switch (attributeCode) {
case Constants.SC_A_REQ_ATTRIBUTE :
requestHeaderMessage.getBytes(tmpMB);
String n = tmpMB.toString();
requestHeaderMessage.getBytes(tmpMB);
String v = tmpMB.toString();
/*
* AJP13 misses to forward the remotePort.
* Allow the AJP connector to add this info via
* a private request attribute.
* We will accept the forwarded data as the remote port,
* and remove it from the public list of request attributes.
*/
if(n.equals(Constants.SC_A_REQ_REMOTE_PORT)) {
try {
request.setRemotePort(Integer.parseInt(v));
} catch (NumberFormatException nfe) {
// Ignore invalid value
}
} else {
request.setAttribute(n, v );
}
break;
case Constants.SC_A_CONTEXT :
requestHeaderMessage.getBytes(tmpMB);
// nothing
break;
case Constants.SC_A_SERVLET_PATH :
requestHeaderMessage.getBytes(tmpMB);
// nothing
break;
case Constants.SC_A_REMOTE_USER :
if (tomcatAuthentication) {
// ignore server
requestHeaderMessage.getBytes(tmpMB);
} else {
requestHeaderMessage.getBytes(request.getRemoteUser());
}
break;
case Constants.SC_A_AUTH_TYPE :
if (tomcatAuthentication) {
// ignore server
requestHeaderMessage.getBytes(tmpMB);
} else {
requestHeaderMessage.getBytes(request.getAuthType());
}
break;
case Constants.SC_A_QUERY_STRING :
requestHeaderMessage.getBytes(request.queryString());
break;
case Constants.SC_A_JVM_ROUTE :
requestHeaderMessage.getBytes(request.instanceId());
break;
case Constants.SC_A_SSL_CERT :
// SSL certificate extraction is lazy, moved to JkCoyoteHandler
requestHeaderMessage.getBytes(certificates);
break;
case Constants.SC_A_SSL_CIPHER :
requestHeaderMessage.getBytes(tmpMB);
request.setAttribute(SSLSupport.CIPHER_SUITE_KEY,
tmpMB.toString());
break;
case Constants.SC_A_SSL_SESSION :
requestHeaderMessage.getBytes(tmpMB);
request.setAttribute(SSLSupport.SESSION_ID_KEY,
tmpMB.toString());
break;
case Constants.SC_A_SSL_KEY_SIZE :
request.setAttribute(SSLSupport.KEY_SIZE_KEY,
Integer.valueOf(requestHeaderMessage.getInt()));
break;
case Constants.SC_A_STORED_METHOD:
requestHeaderMessage.getBytes(request.method());
break;
case Constants.SC_A_SECRET:
requestHeaderMessage.getBytes(tmpMB);
if (requiredSecret != null) {
secret = true;
if (!tmpMB.equals(requiredSecret)) {
response.setStatus(403);
error = true;
}
}
break;
default:
// Ignore unknown attribute for backward compatibility
break;
}
}
// Check if secret was submitted if required
if ((requiredSecret != null) && !secret) {
response.setStatus(403);
error = true;
}
// Check for a full URI (including protocol://host:port/)
ByteChunk uriBC = request.requestURI().getByteChunk();
if (uriBC.startsWithIgnoreCase("http", 0)) {
int pos = uriBC.indexOf("://", 0, 3, 4);
int uriBCStart = uriBC.getStart();
int slashPos = -1;
if (pos != -1) {
byte[] uriB = uriBC.getBytes();
slashPos = uriBC.indexOf('/', pos + 3);
if (slashPos == -1) {
slashPos = uriBC.getLength();
// Set URI as "/"
request.requestURI().setBytes
(uriB, uriBCStart + pos + 1, 1);
} else {
request.requestURI().setBytes
(uriB, uriBCStart + slashPos,
uriBC.getLength() - slashPos);
}
MessageBytes hostMB = headers.setValue("host");
hostMB.setBytes(uriB, uriBCStart + pos + 3,
slashPos - pos - 3);
}
}
MessageBytes valueMB = request.getMimeHeaders().getValue("host");
parseHost(valueMB);
if (error) {
getAdapter().log(request, response, 0);
}
}
/**
* Parse host.
*/
protected void parseHost(MessageBytes valueMB) {
if (valueMB == null || valueMB.isNull()) {
// HTTP/1.0
request.setServerPort(request.getLocalPort());
try {
request.serverName().duplicate(request.localName());
} catch (IOException e) {
response.setStatus(400);
error = true;
}
return;
}
ByteChunk valueBC = valueMB.getByteChunk();
byte[] valueB = valueBC.getBytes();
int valueL = valueBC.getLength();
int valueS = valueBC.getStart();
int colonPos = -1;
if (hostNameC.length < valueL) {
hostNameC = new char[valueL];
}
boolean ipv6 = (valueB[valueS] == '[');
boolean bracketClosed = false;
for (int i = 0; i < valueL; i++) {
char b = (char) valueB[i + valueS];
hostNameC[i] = b;
if (b == ']') {
bracketClosed = true;
} else if (b == ':') {
if (!ipv6 || bracketClosed) {
colonPos = i;
break;
}
}
}
if (colonPos < 0) {
if (request.scheme().equalsIgnoreCase("https")) {
// 443 - Default HTTPS port
request.setServerPort(443);
} else {
// 80 - Default HTTTP port
request.setServerPort(80);
}
request.serverName().setChars(hostNameC, 0, valueL);
} else {
request.serverName().setChars(hostNameC, 0, colonPos);
int port = 0;
int mult = 1;
for (int i = valueL - 1; i > colonPos; i--) {
int charValue = HexUtils.getDec(valueB[i + valueS]);
if (charValue == -1) {
// Invalid character
error = true;
// 400 - Bad request
response.setStatus(400);
break;
}
port = port + (charValue * mult);
mult = 10 * mult;
}
request.setServerPort(port);
}
}
/**
* When committing the response, we have to validate the set of headers, as
* well as setup the response filters.
*/
protected void prepareResponse() throws IOException {
response.setCommitted(true);
responseMessage.reset();
responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS);
// HTTP header contents
responseMessage.appendInt(response.getStatus());
String message = null;
if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER &&
HttpMessages.isSafeInHttpHeader(response.getMessage())) {
message = response.getMessage();
}
if (message == null){
message = HttpMessages.getInstance(
response.getLocale()).getMessage(response.getStatus());
}
if (message == null) {
// mod_jk + httpd 2.x fails with a null status message - bug 45026
message = Integer.toString(response.getStatus());
}
tmpMB.setString(message);
responseMessage.appendBytes(tmpMB);
// Special headers
MimeHeaders headers = response.getMimeHeaders();
String contentType = response.getContentType();
if (contentType != null) {
headers.setValue("Content-Type").setString(contentType);
}
String contentLanguage = response.getContentLanguage();
if (contentLanguage != null) {
headers.setValue("Content-Language").setString(contentLanguage);
}
long contentLength = response.getContentLengthLong();
if (contentLength >= 0) {
headers.setValue("Content-Length").setLong(contentLength);
}
// Other headers
int numHeaders = headers.size();
responseMessage.appendInt(numHeaders);
for (int i = 0; i < numHeaders; i++) {
MessageBytes hN = headers.getName(i);
int hC = Constants.getResponseAjpIndex(hN.toString());
if (hC > 0) {
responseMessage.appendInt(hC);
}
else {
responseMessage.appendBytes(hN);
}
MessageBytes hV=headers.getValue(i);
responseMessage.appendBytes(hV);
}
// Write to buffer
responseMessage.end();
output(responseMessage.getBuffer(), 0,
responseMessage.getLen());
}
/**
* Callback to write data from the buffer.
*/
protected void flush(boolean explicit) throws IOException {
if (explicit && !finished) {
// Send the flush message
output(flushMessageArray, 0, flushMessageArray.length);
}
}
/**
* Finish AJP response.
*/
protected void finish() throws IOException {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
}
}
if (finished)
return;
finished = true;
// Swallow the unread body packet if present
if (first && request.getContentLengthLong() > 0) {
receive();
}
// Add the end message
if (error) {
output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length);
} else {
output(endMessageArray, 0, endMessageArray.length);
}
}
// ------------------------------------- InputStreamInputBuffer Inner Class
/**
* This class is an input buffer which will read its data from an input
* stream.
*/
protected class SocketInputBuffer implements InputBuffer {
/**
* Read bytes into the specified chunk.
*/
@Override
public int doRead(ByteChunk chunk, Request req)
throws IOException {
if (endOfStream) {
return -1;
}
if (first && req.getContentLengthLong() > 0) {
// Handle special first-body-chunk
if (!receive()) {
return 0;
}
} else if (empty) {
if (!refillReadBuffer()) {
return -1;
}
}
ByteChunk bc = bodyBytes.getByteChunk();
chunk.setBytes(bc.getBuffer(), bc.getStart(), bc.getLength());
empty = true;
return chunk.getLength();
}
}
// ----------------------------------- OutputStreamOutputBuffer Inner Class
/**
* This class is an output buffer which will write data to an output
* stream.
*/
protected class SocketOutputBuffer implements OutputBuffer {
/**
* Write chunk.
*/
@Override
public int doWrite(ByteChunk chunk, Response res)
throws IOException {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
}
}
int len = chunk.getLength();
// 4 - hardcoded, byte[] marshaling overhead
// Adjust allowed size if packetSize != default (Constants.MAX_PACKET_SIZE)
int chunkSize = Constants.MAX_SEND_SIZE + packetSize - Constants.MAX_PACKET_SIZE;
int off = 0;
while (len > 0) {
int thisTime = len;
if (thisTime > chunkSize) {
thisTime = chunkSize;
}
len -= thisTime;
responseMessage.reset();
responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
responseMessage.appendBytes(chunk.getBytes(), chunk.getOffset() + off, thisTime);
responseMessage.end();
output(responseMessage.getBuffer(), 0, responseMessage.getLen());
off += thisTime;
}
bytesWritten += chunk.getLength();
return chunk.getLength();
}
@Override
public long getBytesWritten() {
return bytesWritten;
}
}
}
|
55,453
|
Bug 55453 AJP send Body with Status 304
| null |
resolved fixed
|
6d99103
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-28T13:01:03Z
| 2013-08-20T09:13:20Z
|
test/org/apache/coyote/ajp/TestAbstractAjpProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
public class TestAbstractAjpProcessor extends TomcatBaseTest {
@Override
protected String getProtocol() {
/*
* The tests are all setup for HTTP so need to convert the protocol
* values to AJP.
*/
// Has a protocol been specified
String protocol = System.getProperty("tomcat.test.protocol");
// Use BIO by default
if (protocol == null) {
protocol = "org.apache.coyote.ajp.AjpProtocol";
} else if (protocol.contains("Nio")) {
protocol = "org.apache.coyote.ajp.AjpNioProtocol";
} else if (protocol.contains("Apr")) {
protocol = "org.apache.coyote.ajp.AjpAprProtocol";
} else {
protocol = "org.apache.coyote.ajp.AjpProtocol";
}
return protocol;
}
@Test
public void testKeepAlive() throws Exception {
Tomcat tomcat = getTomcatInstance();
tomcat.getConnector().setProperty("connectionTimeout", "-1");
tomcat.start();
// Must have a real docBase - just use temp
Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
Tomcat.addServlet(ctx, "helloWorld", new HelloWorldServlet());
ctx.addServletMapping("/", "helloWorld");
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage("/");
// Complete the message - no extra headers required.
forwardMessage.end();
// Two requests
for (int i = 0; i < 2; i++) {
TesterAjpMessage responseHeaders = ajpClient.sendMessage(forwardMessage);
// Expect 3 packets: headers, body, end
validateResponseHeaders(responseHeaders, 200);
TesterAjpMessage responseBody = ajpClient.readMessage();
validateResponseBody(responseBody, HelloWorldServlet.RESPONSE_TEXT);
validateResponseEnd(ajpClient.readMessage(), true);
// Give connections plenty of time to time out
Thread.sleep(2000);
// Double check the connection is still open
validateCpong(ajpClient.cping());
}
ajpClient.disconnect();
}
@Test
public void testSimplePost() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Use the normal Tomcat ROOT context
File root = new File("test/webapp");
tomcat.addWebapp("", root.getAbsolutePath());
tomcat.start();
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
TesterAjpMessage forwardMessage =
ajpClient.createForwardMessage("/echo-params.jsp", 4);
forwardMessage.addHeader(0xA008, "9");
forwardMessage.addHeader(0xA007, "application/x-www-form-urlencoded");
forwardMessage.end();
TesterAjpMessage bodyMessage =
ajpClient.createBodyMessage("test=data".getBytes());
TesterAjpMessage responseHeaders =
ajpClient.sendMessage(forwardMessage, bodyMessage);
// Expect 3 messages: headers, body, end
validateResponseHeaders(responseHeaders, 200);
// Skip the body
TesterAjpMessage responseBody = ajpClient.readMessage();
validateResponseBody(responseBody, "test - data");
validateResponseEnd(ajpClient.readMessage(), true);
// Double check the connection is still open
validateCpong(ajpClient.cping());
ajpClient.disconnect();
}
/**
* Process response header packet and checks the status. Any other data is
* ignored.
*/
private void validateResponseHeaders(TesterAjpMessage message,
int expectedStatus) throws Exception {
// First two bytes should always be AB
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// Set the start position and read the length
message.processHeader(false);
// Check the length
Assert.assertTrue(message.len > 0);
// Should be a header message
Assert.assertEquals(0x04, message.readByte());
// Check status
Assert.assertEquals(expectedStatus, message.readInt());
// Read the status message
message.readString();
// Get the number of headers
int headerCount = message.readInt();
for (int i = 0; i < headerCount; i++) {
// Read the header name
message.readHeaderName();
// Read the header value
message.readString();
}
}
/**
* Validates that the response message is valid and contains the expected
* content.
*/
private void validateResponseBody(TesterAjpMessage message,
String expectedBody) throws Exception {
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// Set the start position and read the length
message.processHeader(false);
// Should be a body chunk message
Assert.assertEquals(0x03, message.readByte());
int len = message.readInt();
Assert.assertTrue(len > 0);
String body = message.readString(len);
Assert.assertTrue(body.contains(expectedBody));
}
private void validateResponseEnd(TesterAjpMessage message,
boolean expectedReuse) {
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
message.processHeader(false);
// Should be an end body message
Assert.assertEquals(0x05, message.readByte());
// Check the length
Assert.assertEquals(2, message.getLen());
boolean reuse = false;
if (message.readByte() > 0) {
reuse = true;
}
Assert.assertEquals(Boolean.valueOf(expectedReuse), Boolean.valueOf(reuse));
}
private void validateCpong(TesterAjpMessage message) throws Exception {
// First two bytes should always be AB
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// CPONG should have a message length of 1
// This effectively checks the next two bytes
Assert.assertEquals(1, message.getLen());
// Data should be the value 9
Assert.assertEquals(9, message.buf[4]);
}
}
|
55,494
|
Bug 55494 JNDIRealm throws exception after timeout / Connection reset
| null |
resolved fixed
|
7e74aee
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-08-28T14:02:50Z
| 2013-08-28T17:13:20Z
|
java/org/apache/catalina/realm/JNDIRealm.java
|
/*
* 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.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
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.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.tomcat.util.codec.binary.Base64;
import org.ietf.jgss.GSSCredential;
/**
* <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, and/or "{2}" the value of an attribute from the
* user's directory entry (the attribute is specified by the
* <code>userRoleAttribute</code> property), 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 $Id$
*/
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 static final String DEREF_ALIASES = "java.naming.ldap.derefAliases";
/**
* 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;
/**
* The name of the attribute inside the users
* directory entry where the value will be
* taken to search for roles
* This attribute is not used during a nested search
*/
protected String userRoleAttribute = 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>roleBase</code>.
*/
protected MessageFormat roleBaseFormat = null;
/**
* 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. The "{1}"
* and "{2}" are described in the Configuration Reference.
*/
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;
/**
* When searching for user roles, should the search be performed as the user
* currently being authenticated? If false, {@link #connectionName} and
* {@link #connectionPassword} will be used if specified, else an anonymous
* connection will be used.
*/
protected boolean roleSearchAsUser = 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";
/**
* The sizeLimit (also known as the countLimit) to use when the realm is
* configured with {@link #userSearch}. Zero for no limit.
*/
protected long sizeLimit = 0;
/**
* The timeLimit (in milliseconds) to use when the realm is configured with
* {@link #userSearch}. Zero for no limit.
*/
protected int timeLimit = 0;
/**
* Should delegated credentials from the SPNEGO authenticator be used if
* available
*/
protected boolean useDelegatedCredential = true;
// ------------------------------------------------------------- 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 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;
if (roleBase == null)
roleBaseFormat = null;
else
roleBaseFormat = new MessageFormat(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);
}
public boolean isRoleSearchAsUser() {
return roleSearchAsUser;
}
public void setRoleSearchAsUser(boolean roleSearchAsUser) {
this.roleSearchAsUser = roleSearchAsUser;
}
/**
* 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;
}
public String getUserRoleAttribute() {
return userRoleAttribute;
}
public void setUserRoleAttribute(String userRoleAttribute) {
this.userRoleAttribute = userRoleAttribute;
}
/**
* 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;
}
/**
* 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;
}
public long getSizeLimit() {
return sizeLimit;
}
public void setSizeLimit(long sizeLimit) {
this.sizeLimit = sizeLimit;
}
public int getTimeLimit() {
return timeLimit;
}
public void setTimeLimit(int timeLimit) {
this.timeLimit = timeLimit;
}
public boolean isUseDelegatedCredential() {
return useDelegatedCredential;
}
public void setUseDelegatedCredential(boolean useDelegatedCredential) {
this.useDelegatedCredential = useDelegatedCredential;
}
// ---------------------------------------------------------- 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
*/
@Override
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();
// TODO: Use a single log message
while (it.hasNext()) {
containerLog.debug("Found role: " + it.next());
}
}
return (new GenericPrincipal(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();
// TODO: Use a single log message
while (it.hasNext()) {
containerLog.debug("Found role: " + it.next());
}
}
// Create and return a suitable Principal for this user
return (new GenericPrincipal(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, 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<>();
if (userPassword != null)
list.add(userPassword);
if (userRoleName != null)
list.add(userRoleName);
if (userRoleAttribute != null) {
list.add(userRoleAttribute);
}
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 {
// If no attributes are requested, no need to look for them
if (attrIds == null || attrIds.length == 0) {
return new User(username, dn, null, null,null);
}
// 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);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, 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, userRoleAttrValue);
}
/**
* 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 {
userCredentialsAdd(context, dn, credentials);
user = getUserByPattern(context, username, attrIds, dn);
} finally {
userCredentialsRemove(context);
}
}
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);
}
constraints.setCountLimit(sizeLimit);
constraints.setTimeLimit(timeLimit);
// 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);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, 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, userRoleAttrValue);
}
/**
* 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.getUserName()));
} else {
containerLog.trace(sm.getString("jndiRealm.authenticateFailure",
user.getUserName()));
}
}
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.getPassword();
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(StandardCharsets.ISO_8859_1));
byte[] encoded = Base64.encodeBase64(md.digest());
String digestedPassword =
new String(encoded, StandardCharsets.ISO_8859_1);
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(StandardCharsets.ISO_8859_1));
// Decode stored password.
byte[] decoded = Base64.decodeBase64(password);
// Split decoded password into hash and salt.
final int saltpos = 20;
byte[] hash = new byte[saltpos];
System.arraycopy(decoded, 0, hash, 0, saltpos);
md.update(decoded, saltpos, decoded.length - saltpos);
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.getDN();
if (dn == null)
return (false);
// Validate the credentials specified by the user
if (containerLog.isTraceEnabled()) {
containerLog.trace(" validating credentials by binding as the user");
}
userCredentialsAdd(context, dn, 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");
}
}
userCredentialsRemove(context);
return (validated);
}
/**
* Configure the context to use the provided credentials for
* authentication.
*
* @param context DirContext to configure
* @param dn Distinguished name of user
* @param credentials Credentials of user
*/
private void userCredentialsAdd(DirContext context, String dn,
String credentials) throws NamingException {
// Set up security environment to bind as the user
context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
}
/**
* Configure the context to use {@link #connectionName} and
* {@link #connectionPassword} if specified or an anonymous connection if
* those attributes are not specified.
*
* @param context DirContext to configure
*/
private void userCredentialsRemove(DirContext context)
throws NamingException {
// 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 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.getDN();
String username = user.getUserName();
String userRoleId = user.getUserRoleId();
if (dn == null || username == null)
return (null);
if (containerLog.isTraceEnabled())
containerLog.trace(" getRoles(" + dn + ")");
// Start with roles retrieved from the user entry
List<String> list = new ArrayList<>();
List<String> userRoles = user.getRoles();
if (userRoles != null) {
list.addAll(userRoles);
}
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, userRoleId });
SearchControls controls = new SearchControls();
if (roleSubtree)
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
else
controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
controls.setReturningAttributes(new String[] {roleName});
String base = null;
if (roleBaseFormat != null) {
NameParser np = context.getNameParser("");
Name name = np.parse(dn);
String nameParts[] = new String[name.size()];
for (int i = 0; i < name.size(); i++) {
nameParts[i] = name.get(i);
}
base = roleBaseFormat.format(nameParts);
}
// Perform the configured search and process the results
NamingEnumeration<SearchResult> results = null;
try {
if (roleSearchAsUser) {
userCredentialsAdd(context, dn, user.getPassword());
}
results = context.search(base, filter, controls);
} finally {
if (roleSearchAsUser) {
userCredentialsRemove(context);
}
}
if (results == null)
return (list); // Should never happen, but just in case ...
HashMap<String, String> groupMap = new HashMap<>();
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
Map<String, String> newGroups = new HashMap<>(groupMap);
while (!newGroups.isEmpty()) {
Map<String, String> newThisRound = new HashMap<>(); // Stores the groups we find in this iteration
for (Entry<String, String> group : newGroups.entrySet()) {
filter = roleFormat.format(new String[] { group.getKey(), group.getValue(), group.getValue() });
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.put(dname, name);
if (containerLog.isTraceEnabled()) {
containerLog.trace(" Found nested role " + dname + " -> " + name);
}
}
}
} catch (PartialResultException ex) {
if (!adCompat)
throw ex;
}
}
newGroups = newThisRound;
}
}
list.addAll(groupMap.values());
return list;
}
/**
* 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<>();
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.
*/
@Override
protected String getName() {
return (name);
}
/**
* Return the password associated with the given principal's user name.
*/
@Override
protected String getPassword(String username) {
return (null);
}
/**
* Return the Principal associated with the given user name.
*/
@Override
protected Principal getPrincipal(String username) {
return getPrincipal(username, null);
}
@Override
protected Principal getPrincipal(String username,
GSSCredential gssCredential) {
DirContext context = null;
Principal principal = null;
try {
// Ensure that we have a directory context available
context = open();
// Occasionally the directory context will timeout. Try one more
// time before giving up.
try {
// Authenticate the specified username if possible
principal = getPrincipal(context, username, gssCredential);
} 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, gssCredential);
} 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, gssCredential);
}
// 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, GSSCredential gssCredential)
throws NamingException {
User user = null;
List<String> roles = null;
Hashtable<?, ?> preservedEnvironment = null;
try {
if (gssCredential != null && isUseDelegatedCredential()) {
// Preserve the current context environment parameters
preservedEnvironment = context.getEnvironment();
// Set up context
context.addToEnvironment(
Context.SECURITY_AUTHENTICATION, "GSSAPI");
context.addToEnvironment(
"javax.security.sasl.server.authentication", "true");
context.addToEnvironment(
"javax.security.sasl.qop", "auth-conf");
// Note: Subject already set in SPNEGO authenticator so no need
// for Subject.doAs() here
}
user = getUser(context, username);
if (user != null) {
roles = getRoles(context, user);
}
} finally {
restoreEnvironmentParameter(context,
Context.SECURITY_AUTHENTICATION, preservedEnvironment);
restoreEnvironmentParameter(context,
"javax.security.sasl.server.authentication", preservedEnvironment);
restoreEnvironmentParameter(context, "javax.security.sasl.qop",
preservedEnvironment);
}
if (user != null) {
return new GenericPrincipal(user.getUserName(), user.getPassword(),
roles, null, null, gssCredential);
}
return null;
}
private void restoreEnvironmentParameter(DirContext context,
String parameterName, Hashtable<?, ?> preservedEnvironment) {
try {
context.removeFromEnvironment(parameterName);
if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) {
context.addToEnvironment(parameterName,
preservedEnvironment.get(parameterName));
}
} catch (NamingException e) {
// Ignore
}
}
/**
* 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<>();
// 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 the beginning of active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected void startInternal() throws LifecycleException {
// Validate that we can open our connection
try {
open();
} catch (NamingException e) {
throw new LifecycleException(sm.getString("jndiRealm.open"), e);
}
super.startInternal();
}
/**
* Gracefully terminate the active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
super.stopInternal();
// 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<>();
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 );
}
}
}
// ------------------------------------------------------ Private Classes
/**
* A protected class representing a User
*/
protected static class User {
private final String username;
private final String dn;
private final String password;
private final List<String> roles;
private final String userRoleId;
public User(String username, String dn, String password,
List<String> roles, String userRoleId) {
this.username = username;
this.dn = dn;
this.password = password;
if (roles == null) {
this.roles = Collections.emptyList();
} else {
this.roles = Collections.unmodifiableList(roles);
}
this.userRoleId = userRoleId;
}
public String getUserName() {
return username;
}
public String getDN() {
return dn;
}
public String getPassword() {
return password;
}
public List<String> getRoles() {
return roles;
}
public String getUserRoleId() {
return userRoleId;
}
}
}
|
55,500
|
Bug 55500 AsyncListener.onTimeout is not called via AJP AjpNioProtocol connector
|
The AsyncListener.onTimeout is not called, when timeout occurs, when traffic routed via AJP connector configured with AjpNioProtocol protocol.
|
resolved fixed
|
cf1e104
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-03T09:24:08Z
| 2013-08-29T15:26:40Z
|
java/org/apache/coyote/ajp/AbstractAjpProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.http.HttpUpgradeHandler;
import org.apache.coyote.AbstractProcessor;
import org.apache.coyote.ActionCode;
import org.apache.coyote.AsyncContextCallback;
import org.apache.coyote.InputBuffer;
import org.apache.coyote.OutputBuffer;
import org.apache.coyote.Request;
import org.apache.coyote.RequestInfo;
import org.apache.coyote.Response;
import org.apache.juli.logging.Log;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.HexUtils;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.HttpMessages;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.DispatchType;
import org.apache.tomcat.util.net.SSLSupport;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapper;
import org.apache.tomcat.util.res.StringManager;
/**
* Base class for AJP Processor implementations.
*/
public abstract class AbstractAjpProcessor<S> extends AbstractProcessor<S> {
protected abstract Log getLog();
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* End message array.
*/
protected static final byte[] endMessageArray;
protected static final byte[] endAndCloseMessageArray;
/**
* Flush message array.
*/
protected static final byte[] flushMessageArray;
/**
* Pong message array.
*/
protected static final byte[] pongMessageArray;
static {
// Allocate the end message array
AjpMessage endMessage = new AjpMessage(16);
endMessage.reset();
endMessage.appendByte(Constants.JK_AJP13_END_RESPONSE);
endMessage.appendByte(1);
endMessage.end();
endMessageArray = new byte[endMessage.getLen()];
System.arraycopy(endMessage.getBuffer(), 0, endMessageArray, 0,
endMessage.getLen());
// Allocate the end and close message array
AjpMessage endAndCloseMessage = new AjpMessage(16);
endAndCloseMessage.reset();
endAndCloseMessage.appendByte(Constants.JK_AJP13_END_RESPONSE);
endAndCloseMessage.appendByte(0);
endAndCloseMessage.end();
endAndCloseMessageArray = new byte[endAndCloseMessage.getLen()];
System.arraycopy(endAndCloseMessage.getBuffer(), 0, endAndCloseMessageArray, 0,
endAndCloseMessage.getLen());
// Allocate the flush message array
AjpMessage flushMessage = new AjpMessage(16);
flushMessage.reset();
flushMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
flushMessage.appendInt(0);
flushMessage.appendByte(0);
flushMessage.end();
flushMessageArray = new byte[flushMessage.getLen()];
System.arraycopy(flushMessage.getBuffer(), 0, flushMessageArray, 0,
flushMessage.getLen());
// Allocate the pong message array
AjpMessage pongMessage = new AjpMessage(16);
pongMessage.reset();
pongMessage.appendByte(Constants.JK_AJP13_CPONG_REPLY);
pongMessage.end();
pongMessageArray = new byte[pongMessage.getLen()];
System.arraycopy(pongMessage.getBuffer(), 0, pongMessageArray,
0, pongMessage.getLen());
}
// ----------------------------------------------------- Instance Variables
/**
* GetBody message array. Not static like the other message arrays since the
* message varies with packetSize and that can vary per connector.
*/
protected final byte[] getBodyMessageArray;
/**
* AJP packet size.
*/
protected final int packetSize;
/**
* Header message. Note that this header is merely the one used during the
* processing of the first message of a "request", so it might not be a
* request header. It will stay unchanged during the processing of the whole
* request.
*/
protected final AjpMessage requestHeaderMessage;
/**
* Message used for response composition.
*/
protected final AjpMessage responseMessage;
/**
* Body message.
*/
protected final AjpMessage bodyMessage;
/**
* Body message.
*/
protected final MessageBytes bodyBytes = MessageBytes.newInstance();
/**
* Error flag.
*/
protected boolean error = false;
/**
* Host name (used to avoid useless B2C conversion on the host name).
*/
protected char[] hostNameC = new char[0];
/**
* Temp message bytes used for processing.
*/
protected final MessageBytes tmpMB = MessageBytes.newInstance();
/**
* Byte chunk for certs.
*/
protected final MessageBytes certificates = MessageBytes.newInstance();
/**
* End of stream flag.
*/
protected boolean endOfStream = false;
/**
* Request body empty flag.
*/
protected boolean empty = true;
/**
* First read.
*/
protected boolean first = true;
/**
* Replay read.
*/
protected boolean replay = false;
/**
* Should any response body be swallowed and not sent to the client.
*/
private boolean swallowResponse = false;
/**
* Finished response.
*/
protected boolean finished = false;
/**
* Bytes written to client for the current request.
*/
protected long bytesWritten = 0;
// ------------------------------------------------------------ Constructor
public AbstractAjpProcessor(int packetSize, AbstractEndpoint endpoint) {
super(endpoint);
this.packetSize = packetSize;
request.setInputBuffer(new SocketInputBuffer());
requestHeaderMessage = new AjpMessage(packetSize);
responseMessage = new AjpMessage(packetSize);
bodyMessage = new AjpMessage(packetSize);
// Set the getBody message buffer
AjpMessage getBodyMessage = new AjpMessage(16);
getBodyMessage.reset();
getBodyMessage.appendByte(Constants.JK_AJP13_GET_BODY_CHUNK);
// Adjust read size if packetSize != default (Constants.MAX_PACKET_SIZE)
getBodyMessage.appendInt(Constants.MAX_READ_SIZE + packetSize -
Constants.MAX_PACKET_SIZE);
getBodyMessage.end();
getBodyMessageArray = new byte[getBodyMessage.getLen()];
System.arraycopy(getBodyMessage.getBuffer(), 0, getBodyMessageArray,
0, getBodyMessage.getLen());
}
// ------------------------------------------------------------- Properties
/**
* The number of milliseconds Tomcat will wait for a subsequent request
* before closing the connection. The default is -1 which is an infinite
* timeout.
*/
protected int keepAliveTimeout = -1;
public int getKeepAliveTimeout() { return keepAliveTimeout; }
public void setKeepAliveTimeout(int timeout) { keepAliveTimeout = timeout; }
/**
* Use Tomcat authentication ?
*/
protected boolean tomcatAuthentication = true;
public boolean getTomcatAuthentication() { return tomcatAuthentication; }
public void setTomcatAuthentication(boolean tomcatAuthentication) {
this.tomcatAuthentication = tomcatAuthentication;
}
/**
* Required secret.
*/
protected String requiredSecret = null;
public void setRequiredSecret(String requiredSecret) {
this.requiredSecret = requiredSecret;
}
/**
* When client certificate information is presented in a form other than
* instances of {@link java.security.cert.X509Certificate} it needs to be
* converted before it can be used and this property controls which JSSE
* provider is used to perform the conversion. For example it is used with
* the AJP connectors, the HTTP APR connector and with the
* {@link org.apache.catalina.valves.SSLValve}. If not specified, the
* default provider will be used.
*/
protected String clientCertProvider = null;
public String getClientCertProvider() { return clientCertProvider; }
public void setClientCertProvider(String s) { this.clientCertProvider = s; }
// --------------------------------------------------------- Public Methods
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
public final void action(ActionCode actionCode, Object param) {
if (actionCode == ActionCode.CLOSE) {
// End the processing of the current request, and stop any further
// transactions with the client
try {
finish();
} catch (IOException e) {
// Set error flag
error = true;
}
} else if (actionCode == ActionCode.COMMIT) {
if (response.isCommitted())
return;
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
}
try {
flush(false);
} catch (IOException e) {
// Set error flag
error = true;
}
} else if (actionCode == ActionCode.ACK) {
// NO_OP for AJP
} else if (actionCode == ActionCode.CLIENT_FLUSH) {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
return;
}
}
try {
flush(true);
} catch (IOException e) {
// Set error flag
error = true;
}
} else if (actionCode == ActionCode.DISABLE_SWALLOW_INPUT) {
// TODO: Do not swallow request input but
// make sure we are closing the connection
error = true;
} else if (actionCode == ActionCode.RESET) {
// NO-OP
} else if (actionCode == ActionCode.REQ_SSL_ATTRIBUTE ) {
if (!certificates.isNull()) {
ByteChunk certData = certificates.getByteChunk();
X509Certificate jsseCerts[] = null;
ByteArrayInputStream bais =
new ByteArrayInputStream(certData.getBytes(),
certData.getStart(),
certData.getLength());
// Fill the elements.
try {
CertificateFactory cf;
if (clientCertProvider == null) {
cf = CertificateFactory.getInstance("X.509");
} else {
cf = CertificateFactory.getInstance("X.509",
clientCertProvider);
}
while(bais.available() > 0) {
X509Certificate cert = (X509Certificate)
cf.generateCertificate(bais);
if(jsseCerts == null) {
jsseCerts = new X509Certificate[1];
jsseCerts[0] = cert;
} else {
X509Certificate [] temp = new X509Certificate[jsseCerts.length+1];
System.arraycopy(jsseCerts,0,temp,0,jsseCerts.length);
temp[jsseCerts.length] = cert;
jsseCerts = temp;
}
}
} catch (java.security.cert.CertificateException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
} catch (NoSuchProviderException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
}
request.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts);
}
} else if (actionCode == ActionCode.REQ_SSL_CERTIFICATE) {
// NO-OP. Can't force a new SSL handshake with the client when using
// AJP as the reverse proxy controls that connection.
} else if (actionCode == ActionCode.REQ_HOST_ATTRIBUTE) {
// Get remote host name using a DNS resolution
if (request.remoteHost().isNull()) {
try {
request.remoteHost().setString(InetAddress.getByName
(request.remoteAddr().toString()).getHostName());
} catch (IOException iex) {
// Ignore
}
}
} else if (actionCode == ActionCode.REQ_HOST_ADDR_ATTRIBUTE) {
// NO-OP
// Automatically populated during prepareRequest()
} else if (actionCode == ActionCode.REQ_LOCAL_NAME_ATTRIBUTE) {
// NO-OP
// Automatically populated during prepareRequest()
} else if (actionCode == ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE) {
// Copy from local name for now, which should simply be an address
request.localAddr().setString(request.localName().toString());
} else if (actionCode == ActionCode.REQ_REMOTEPORT_ATTRIBUTE) {
// NO-OP
// This information is not available when using the AJP protocol
} else if (actionCode == ActionCode.REQ_LOCALPORT_ATTRIBUTE) {
// NO-OP
// Automatically populated during prepareRequest()
} else if (actionCode == ActionCode.REQ_SET_BODY_REPLAY) {
// Set the given bytes as the content
ByteChunk bc = (ByteChunk) param;
int length = bc.getLength();
bodyBytes.setBytes(bc.getBytes(), bc.getStart(), length);
request.setContentLength(length);
first = false;
empty = false;
replay = true;
endOfStream = false;
} else if (actionCode == ActionCode.ASYNC_START) {
asyncStateMachine.asyncStart((AsyncContextCallback) param);
} else if (actionCode == ActionCode.ASYNC_DISPATCHED) {
asyncStateMachine.asyncDispatched();
} else if (actionCode == ActionCode.ASYNC_TIMEOUT) {
AtomicBoolean result = (AtomicBoolean) param;
result.set(asyncStateMachine.asyncTimeout());
} else if (actionCode == ActionCode.ASYNC_RUN) {
asyncStateMachine.asyncRun((Runnable) param);
} else if (actionCode == ActionCode.ASYNC_ERROR) {
asyncStateMachine.asyncError();
} else if (actionCode == ActionCode.ASYNC_IS_STARTED) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted());
} else if (actionCode == ActionCode.ASYNC_IS_DISPATCHING) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching());
} else if (actionCode == ActionCode.ASYNC_IS_ASYNC) {
((AtomicBoolean) param).set(asyncStateMachine.isAsync());
} else if (actionCode == ActionCode.ASYNC_IS_TIMINGOUT) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut());
} else if (actionCode == ActionCode.ASYNC_IS_ERROR) {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncError());
} else if (actionCode == ActionCode.UPGRADE) {
// HTTP connections only. Unsupported for AJP.
throw new UnsupportedOperationException(
sm.getString("ajpprocessor.httpupgrade.notsupported"));
} else if (actionCode == ActionCode.COMET_BEGIN) {
// HTTP connections only. Unsupported for AJP.
throw new UnsupportedOperationException(
sm.getString("ajpprocessor.comet.notsupported"));
} else if (actionCode == ActionCode.COMET_END) {
// HTTP connections only. Unsupported for AJP.
throw new UnsupportedOperationException(
sm.getString("ajpprocessor.comet.notsupported"));
} else if (actionCode == ActionCode.COMET_CLOSE) {
// HTTP connections only. Unsupported for AJP.
throw new UnsupportedOperationException(
sm.getString("ajpprocessor.comet.notsupported"));
} else if (actionCode == ActionCode.COMET_SETTIMEOUT) {
// HTTP connections only. Unsupported for AJP.
throw new UnsupportedOperationException(
sm.getString("ajpprocessor.comet.notsupported"));
} else if (actionCode == ActionCode.AVAILABLE) {
// Web Server only sends data when asked so unless end of stream has
// been reached, there should be data available.
// TODO Figure out if a 'true' non-blocking approach is possible
// for AJP and what changes would be required to support it.
if (!endOfStream) {
request.setAvailable(1);
}
} else if (actionCode == ActionCode.NB_WRITE_INTEREST) {
// Until 'true' non-blocking IO is implemented, assume it is always
// possible write data.
AtomicBoolean isReady = (AtomicBoolean)param;
isReady.set(true);
} else if (actionCode == ActionCode.NB_READ_INTEREST) {
// NO-OP. Not required until 'true' non-blocking IO is implemented.
} else if (actionCode == ActionCode.REQUEST_BODY_FULLY_READ) {
AtomicBoolean result = (AtomicBoolean) param;
result.set(endOfStream);
} else if (actionCode == ActionCode.DISPATCH_READ) {
socketWrapper.addDispatch(DispatchType.NON_BLOCKING_READ);
} else if (actionCode == ActionCode.DISPATCH_WRITE) {
socketWrapper.addDispatch(DispatchType.NON_BLOCKING_WRITE);
} else {
actionInternal(actionCode, param);
}
}
@Override
public SocketState asyncDispatch(SocketStatus status) {
RequestInfo rp = request.getRequestProcessor();
try {
rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
error = !getAdapter().asyncDispatch(request, response, status);
} catch (InterruptedIOException e) {
error = true;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().error(sm.getString("http11processor.request.process"), t);
error = true;
}
rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
if (isAsync()) {
if (error) {
request.updateCounters();
return SocketState.CLOSED;
} else {
return SocketState.LONG;
}
} else {
request.updateCounters();
if (error) {
return SocketState.CLOSED;
} else {
return SocketState.OPEN;
}
}
}
/**
* Process pipelined HTTP requests using the specified input and output
* streams.
*
* @throws IOException error during an I/O operation
*/
@Override
public SocketState process(SocketWrapper<S> socket) throws IOException {
RequestInfo rp = request.getRequestProcessor();
rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);
// Setting up the socket
this.socketWrapper = socket;
setupSocket(socket);
int soTimeout = endpoint.getSoTimeout();
boolean cping = false;
// Error flag
error = false;
boolean keptAlive = false;
while (!error && !endpoint.isPaused()) {
// Parsing the request header
try {
// Get first message of the request
if (!readMessage(requestHeaderMessage, !keptAlive)) {
break;
}
// Set back timeout if keep alive timeout is enabled
if (keepAliveTimeout > 0) {
setTimeout(socketWrapper, soTimeout);
}
// Check message type, process right away and break if
// not regular request processing
int type = requestHeaderMessage.getByte();
if (type == Constants.JK_AJP13_CPING_REQUEST) {
if (endpoint.isPaused()) {
recycle(true);
break;
}
cping = true;
try {
output(pongMessageArray, 0, pongMessageArray.length);
} catch (IOException e) {
error = true;
}
recycle(false);
continue;
} else if(type != Constants.JK_AJP13_FORWARD_REQUEST) {
// Unexpected packet type. Unread body packets should have
// been swallowed in finish().
if (getLog().isDebugEnabled()) {
getLog().debug("Unexpected message: " + type);
}
error = true;
break;
}
keptAlive = true;
request.setStartTime(System.currentTimeMillis());
} catch (IOException e) {
error = true;
break;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().debug(sm.getString("ajpprocessor.header.error"), t);
// 400 - Bad Request
response.setStatus(400);
getAdapter().log(request, response, 0);
error = true;
}
if (!error) {
// Setting up filters, and parse some request headers
rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE);
try {
prepareRequest();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().debug(sm.getString("ajpprocessor.request.prepare"), t);
// 400 - Internal Server Error
response.setStatus(400);
getAdapter().log(request, response, 0);
error = true;
}
}
if (!error && !cping && endpoint.isPaused()) {
// 503 - Service unavailable
response.setStatus(503);
getAdapter().log(request, response, 0);
error = true;
}
cping = false;
// Process the request in the adapter
if (!error) {
try {
rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
getAdapter().service(request, response);
} catch (InterruptedIOException e) {
error = true;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().error(sm.getString("ajpprocessor.request.process"), t);
// 500 - Internal Server Error
response.setStatus(500);
getAdapter().log(request, response, 0);
error = true;
}
}
if (isAsync() && !error) {
break;
}
// Finish the response if not done yet
if (!finished) {
try {
finish();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
error = true;
}
}
// If there was an error, make sure the request is counted as
// and error, and update the statistics counter
if (error) {
response.setStatus(500);
}
request.updateCounters();
rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE);
// Set keep alive timeout if enabled
if (keepAliveTimeout > 0) {
setTimeout(socketWrapper, keepAliveTimeout);
}
recycle(false);
}
rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
if (!error && !endpoint.isPaused()) {
if (isAsync()) {
return SocketState.LONG;
} else {
return SocketState.OPEN;
}
} else {
return SocketState.CLOSED;
}
}
@Override
public void setSslSupport(SSLSupport sslSupport) {
// Should never reach this code but in case we do...
throw new IllegalStateException(
sm.getString("ajpprocessor.ssl.notsupported"));
}
@Override
public SocketState event(SocketStatus status) throws IOException {
// Should never reach this code but in case we do...
throw new IOException(
sm.getString("ajpprocessor.comet.notsupported"));
}
@Override
public SocketState upgradeDispatch(SocketStatus status) throws IOException {
// Should never reach this code but in case we do...
throw new IOException(
sm.getString("ajpprocessor.httpupgrade.notsupported"));
}
@Override
public HttpUpgradeHandler getHttpUpgradeHandler() {
// Should never reach this code but in case we do...
throw new IllegalStateException(
sm.getString("ajpprocessor.httpupgrade.notsupported"));
}
/**
* Recycle the processor, ready for the next request which may be on the
* same connection or a different connection.
*
* @param socketClosing Indicates if the socket is about to be closed
* allowing the processor to perform any additional
* clean-up that may be required
*/
@Override
public void recycle(boolean socketClosing) {
asyncStateMachine.recycle();
// Recycle Request object
first = true;
endOfStream = false;
empty = true;
replay = false;
finished = false;
request.recycle();
response.recycle();
certificates.recycle();
swallowResponse = false;
bytesWritten = 0;
}
// ------------------------------------------------------ Protected Methods
// Methods called by action()
protected abstract void actionInternal(ActionCode actionCode, Object param);
// Methods called by process()
protected abstract void setupSocket(SocketWrapper<S> socketWrapper)
throws IOException;
protected abstract void setTimeout(SocketWrapper<S> socketWrapper,
int timeout) throws IOException;
// Methods called by prepareResponse()
protected abstract void output(byte[] src, int offset, int length)
throws IOException;
// Methods used by readMessage
/**
* Read at least the specified amount of bytes, and place them
* in the input buffer. Note that if any data is available to read then this
* method will always block until at least the specified number of bytes
* have been read.
*
* @param buf Buffer to read data into
* @param pos Start position
* @param n The minimum number of bytes to read
* @param block If there is no data available to read when this method is
* called, should this call block until data becomes available?
* @return <code>true</code> if the requested number of bytes were read
* else <code>false</code>
* @throws IOException
*/
protected abstract boolean read(byte[] buf, int pos, int n, boolean block)
throws IOException;
// Methods used by SocketInputBuffer
/** Receive a chunk of data. Called to implement the
* 'special' packet in ajp13 and to receive the data
* after we send a GET_BODY packet
*/
protected boolean receive() throws IOException {
first = false;
bodyMessage.reset();
readMessage(bodyMessage, true);
// No data received.
if (bodyMessage.getLen() == 0) {
// just the header
// Don't mark 'end of stream' for the first chunk.
return false;
}
int blen = bodyMessage.peekInt();
if (blen == 0) {
return false;
}
bodyMessage.getBodyBytes(bodyBytes);
empty = false;
return true;
}
/**
* Read an AJP message.
*
* @param message The message to populate
* @param block If there is no data available to read when this method is
* called, should this call block until data becomes available?
* @return true if the message has been read, false if no data was read
*
* @throws IOException any other failure, including incomplete reads
*/
protected boolean readMessage(AjpMessage message, boolean block)
throws IOException {
byte[] buf = message.getBuffer();
int headerLength = message.getHeaderLength();
if (!read(buf, 0, headerLength, block)) {
return false;
}
int messageLength = message.processHeader(true);
if (messageLength < 0) {
// Invalid AJP header signature
throw new IOException(sm.getString("ajpmessage.invalidLength",
Integer.valueOf(messageLength)));
}
else if (messageLength == 0) {
// Zero length message.
return true;
}
else {
if (messageLength > message.getBuffer().length) {
// Message too long for the buffer
// Need to trigger a 400 response
throw new IllegalArgumentException(sm.getString(
"ajpprocessor.header.tooLong",
Integer.valueOf(messageLength),
Integer.valueOf(buf.length)));
}
read(buf, headerLength, messageLength, true);
return true;
}
}
@Override
public final boolean isComet() {
// AJP does not support Comet
return false;
}
@Override
public final boolean isUpgrade() {
// AJP does not support HTTP upgrade
return false;
}
/**
* Get more request body data from the web server and store it in the
* internal buffer.
*
* @return true if there is more data, false if not.
*/
protected boolean refillReadBuffer() throws IOException {
// If the server returns an empty packet, assume that that end of
// the stream has been reached (yuck -- fix protocol??).
// FORM support
if (replay) {
endOfStream = true; // we've read everything there is
}
if (endOfStream) {
return false;
}
// Request more data immediately
output(getBodyMessageArray, 0, getBodyMessageArray.length);
boolean moreData = receive();
if( !moreData ) {
endOfStream = true;
}
return moreData;
}
/**
* After reading the request headers, we have to setup the request filters.
*/
protected void prepareRequest() {
// Translate the HTTP method code to a String.
byte methodCode = requestHeaderMessage.getByte();
if (methodCode != Constants.SC_M_JK_STORED) {
String methodName = Constants.getMethodForCode(methodCode - 1);
request.method().setString(methodName);
}
requestHeaderMessage.getBytes(request.protocol());
requestHeaderMessage.getBytes(request.requestURI());
requestHeaderMessage.getBytes(request.remoteAddr());
requestHeaderMessage.getBytes(request.remoteHost());
requestHeaderMessage.getBytes(request.localName());
request.setLocalPort(requestHeaderMessage.getInt());
boolean isSSL = requestHeaderMessage.getByte() != 0;
if (isSSL) {
request.scheme().setString("https");
}
// Decode headers
MimeHeaders headers = request.getMimeHeaders();
// Set this every time in case limit has been changed via JMX
headers.setLimit(endpoint.getMaxHeaderCount());
int hCount = requestHeaderMessage.getInt();
for(int i = 0 ; i < hCount ; i++) {
String hName = null;
// Header names are encoded as either an integer code starting
// with 0xA0, or as a normal string (in which case the first
// two bytes are the length).
int isc = requestHeaderMessage.peekInt();
int hId = isc & 0xFF;
MessageBytes vMB = null;
isc &= 0xFF00;
if(0xA000 == isc) {
requestHeaderMessage.getInt(); // To advance the read position
hName = Constants.getHeaderForCode(hId - 1);
vMB = headers.addValue(hName);
} else {
// reset hId -- if the header currently being read
// happens to be 7 or 8 bytes long, the code below
// will think it's the content-type header or the
// content-length header - SC_REQ_CONTENT_TYPE=7,
// SC_REQ_CONTENT_LENGTH=8 - leading to unexpected
// behaviour. see bug 5861 for more information.
hId = -1;
requestHeaderMessage.getBytes(tmpMB);
ByteChunk bc = tmpMB.getByteChunk();
vMB = headers.addValue(bc.getBuffer(),
bc.getStart(), bc.getLength());
}
requestHeaderMessage.getBytes(vMB);
if (hId == Constants.SC_REQ_CONTENT_LENGTH ||
(hId == -1 && tmpMB.equalsIgnoreCase("Content-Length"))) {
// just read the content-length header, so set it
request.setContentLength(vMB.getLong());
} else if (hId == Constants.SC_REQ_CONTENT_TYPE ||
(hId == -1 && tmpMB.equalsIgnoreCase("Content-Type"))) {
// just read the content-type header, so set it
ByteChunk bchunk = vMB.getByteChunk();
request.contentType().setBytes(bchunk.getBytes(),
bchunk.getOffset(),
bchunk.getLength());
}
}
// Decode extra attributes
boolean secret = false;
byte attributeCode;
while ((attributeCode = requestHeaderMessage.getByte())
!= Constants.SC_A_ARE_DONE) {
switch (attributeCode) {
case Constants.SC_A_REQ_ATTRIBUTE :
requestHeaderMessage.getBytes(tmpMB);
String n = tmpMB.toString();
requestHeaderMessage.getBytes(tmpMB);
String v = tmpMB.toString();
/*
* AJP13 misses to forward the remotePort.
* Allow the AJP connector to add this info via
* a private request attribute.
* We will accept the forwarded data as the remote port,
* and remove it from the public list of request attributes.
*/
if(n.equals(Constants.SC_A_REQ_REMOTE_PORT)) {
try {
request.setRemotePort(Integer.parseInt(v));
} catch (NumberFormatException nfe) {
// Ignore invalid value
}
} else {
request.setAttribute(n, v );
}
break;
case Constants.SC_A_CONTEXT :
requestHeaderMessage.getBytes(tmpMB);
// nothing
break;
case Constants.SC_A_SERVLET_PATH :
requestHeaderMessage.getBytes(tmpMB);
// nothing
break;
case Constants.SC_A_REMOTE_USER :
if (tomcatAuthentication) {
// ignore server
requestHeaderMessage.getBytes(tmpMB);
} else {
requestHeaderMessage.getBytes(request.getRemoteUser());
}
break;
case Constants.SC_A_AUTH_TYPE :
if (tomcatAuthentication) {
// ignore server
requestHeaderMessage.getBytes(tmpMB);
} else {
requestHeaderMessage.getBytes(request.getAuthType());
}
break;
case Constants.SC_A_QUERY_STRING :
requestHeaderMessage.getBytes(request.queryString());
break;
case Constants.SC_A_JVM_ROUTE :
requestHeaderMessage.getBytes(request.instanceId());
break;
case Constants.SC_A_SSL_CERT :
// SSL certificate extraction is lazy, moved to JkCoyoteHandler
requestHeaderMessage.getBytes(certificates);
break;
case Constants.SC_A_SSL_CIPHER :
requestHeaderMessage.getBytes(tmpMB);
request.setAttribute(SSLSupport.CIPHER_SUITE_KEY,
tmpMB.toString());
break;
case Constants.SC_A_SSL_SESSION :
requestHeaderMessage.getBytes(tmpMB);
request.setAttribute(SSLSupport.SESSION_ID_KEY,
tmpMB.toString());
break;
case Constants.SC_A_SSL_KEY_SIZE :
request.setAttribute(SSLSupport.KEY_SIZE_KEY,
Integer.valueOf(requestHeaderMessage.getInt()));
break;
case Constants.SC_A_STORED_METHOD:
requestHeaderMessage.getBytes(request.method());
break;
case Constants.SC_A_SECRET:
requestHeaderMessage.getBytes(tmpMB);
if (requiredSecret != null) {
secret = true;
if (!tmpMB.equals(requiredSecret)) {
response.setStatus(403);
error = true;
}
}
break;
default:
// Ignore unknown attribute for backward compatibility
break;
}
}
// Check if secret was submitted if required
if ((requiredSecret != null) && !secret) {
response.setStatus(403);
error = true;
}
// Check for a full URI (including protocol://host:port/)
ByteChunk uriBC = request.requestURI().getByteChunk();
if (uriBC.startsWithIgnoreCase("http", 0)) {
int pos = uriBC.indexOf("://", 0, 3, 4);
int uriBCStart = uriBC.getStart();
int slashPos = -1;
if (pos != -1) {
byte[] uriB = uriBC.getBytes();
slashPos = uriBC.indexOf('/', pos + 3);
if (slashPos == -1) {
slashPos = uriBC.getLength();
// Set URI as "/"
request.requestURI().setBytes
(uriB, uriBCStart + pos + 1, 1);
} else {
request.requestURI().setBytes
(uriB, uriBCStart + slashPos,
uriBC.getLength() - slashPos);
}
MessageBytes hostMB = headers.setValue("host");
hostMB.setBytes(uriB, uriBCStart + pos + 3,
slashPos - pos - 3);
}
}
MessageBytes valueMB = request.getMimeHeaders().getValue("host");
parseHost(valueMB);
if (error) {
getAdapter().log(request, response, 0);
}
}
/**
* Parse host.
*/
protected void parseHost(MessageBytes valueMB) {
if (valueMB == null || valueMB.isNull()) {
// HTTP/1.0
request.setServerPort(request.getLocalPort());
try {
request.serverName().duplicate(request.localName());
} catch (IOException e) {
response.setStatus(400);
error = true;
}
return;
}
ByteChunk valueBC = valueMB.getByteChunk();
byte[] valueB = valueBC.getBytes();
int valueL = valueBC.getLength();
int valueS = valueBC.getStart();
int colonPos = -1;
if (hostNameC.length < valueL) {
hostNameC = new char[valueL];
}
boolean ipv6 = (valueB[valueS] == '[');
boolean bracketClosed = false;
for (int i = 0; i < valueL; i++) {
char b = (char) valueB[i + valueS];
hostNameC[i] = b;
if (b == ']') {
bracketClosed = true;
} else if (b == ':') {
if (!ipv6 || bracketClosed) {
colonPos = i;
break;
}
}
}
if (colonPos < 0) {
if (request.scheme().equalsIgnoreCase("https")) {
// 443 - Default HTTPS port
request.setServerPort(443);
} else {
// 80 - Default HTTTP port
request.setServerPort(80);
}
request.serverName().setChars(hostNameC, 0, valueL);
} else {
request.serverName().setChars(hostNameC, 0, colonPos);
int port = 0;
int mult = 1;
for (int i = valueL - 1; i > colonPos; i--) {
int charValue = HexUtils.getDec(valueB[i + valueS]);
if (charValue == -1) {
// Invalid character
error = true;
// 400 - Bad request
response.setStatus(400);
break;
}
port = port + (charValue * mult);
mult = 10 * mult;
}
request.setServerPort(port);
}
}
/**
* When committing the response, we have to validate the set of headers, as
* well as setup the response filters.
*/
protected void prepareResponse() throws IOException {
response.setCommitted(true);
responseMessage.reset();
responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS);
// Responses with certain status codes are not permitted to include a
// response body.
int statusCode = response.getStatus();
if (statusCode < 200 || statusCode == 204 || statusCode == 205 ||
statusCode == 304) {
// No entity body
swallowResponse = true;
}
// Responses to HEAD requests are not permitted to incude a response
// body.
MessageBytes methodMB = request.method();
if (methodMB.equals("HEAD")) {
// No entity body
swallowResponse = true;
}
// HTTP header contents
responseMessage.appendInt(statusCode);
String message = null;
if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER &&
HttpMessages.isSafeInHttpHeader(response.getMessage())) {
message = response.getMessage();
}
if (message == null){
message = HttpMessages.getInstance(
response.getLocale()).getMessage(response.getStatus());
}
if (message == null) {
// mod_jk + httpd 2.x fails with a null status message - bug 45026
message = Integer.toString(response.getStatus());
}
tmpMB.setString(message);
responseMessage.appendBytes(tmpMB);
// Special headers
MimeHeaders headers = response.getMimeHeaders();
String contentType = response.getContentType();
if (contentType != null) {
headers.setValue("Content-Type").setString(contentType);
}
String contentLanguage = response.getContentLanguage();
if (contentLanguage != null) {
headers.setValue("Content-Language").setString(contentLanguage);
}
long contentLength = response.getContentLengthLong();
if (contentLength >= 0) {
headers.setValue("Content-Length").setLong(contentLength);
}
// Other headers
int numHeaders = headers.size();
responseMessage.appendInt(numHeaders);
for (int i = 0; i < numHeaders; i++) {
MessageBytes hN = headers.getName(i);
int hC = Constants.getResponseAjpIndex(hN.toString());
if (hC > 0) {
responseMessage.appendInt(hC);
}
else {
responseMessage.appendBytes(hN);
}
MessageBytes hV=headers.getValue(i);
responseMessage.appendBytes(hV);
}
// Write to buffer
responseMessage.end();
output(responseMessage.getBuffer(), 0,
responseMessage.getLen());
}
/**
* Callback to write data from the buffer.
*/
protected void flush(boolean explicit) throws IOException {
if (explicit && !finished) {
// Send the flush message
output(flushMessageArray, 0, flushMessageArray.length);
}
}
/**
* Finish AJP response.
*/
protected void finish() throws IOException {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
}
}
if (finished)
return;
finished = true;
// Swallow the unread body packet if present
if (first && request.getContentLengthLong() > 0) {
receive();
}
// Add the end message
if (error) {
output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length);
} else {
output(endMessageArray, 0, endMessageArray.length);
}
}
// ------------------------------------- InputStreamInputBuffer Inner Class
/**
* This class is an input buffer which will read its data from an input
* stream.
*/
protected class SocketInputBuffer implements InputBuffer {
/**
* Read bytes into the specified chunk.
*/
@Override
public int doRead(ByteChunk chunk, Request req)
throws IOException {
if (endOfStream) {
return -1;
}
if (first && req.getContentLengthLong() > 0) {
// Handle special first-body-chunk
if (!receive()) {
return 0;
}
} else if (empty) {
if (!refillReadBuffer()) {
return -1;
}
}
ByteChunk bc = bodyBytes.getByteChunk();
chunk.setBytes(bc.getBuffer(), bc.getStart(), bc.getLength());
empty = true;
return chunk.getLength();
}
}
// ----------------------------------- OutputStreamOutputBuffer Inner Class
/**
* This class is an output buffer which will write data to an output
* stream.
*/
protected class SocketOutputBuffer implements OutputBuffer {
/**
* Write chunk.
*/
@Override
public int doWrite(ByteChunk chunk, Response res)
throws IOException {
if (!response.isCommitted()) {
// Validate and write response headers
try {
prepareResponse();
} catch (IOException e) {
// Set error flag
error = true;
}
}
if (!swallowResponse) {
int len = chunk.getLength();
// 4 - hardcoded, byte[] marshaling overhead
// Adjust allowed size if packetSize != default (Constants.MAX_PACKET_SIZE)
int chunkSize = Constants.MAX_SEND_SIZE + packetSize - Constants.MAX_PACKET_SIZE;
int off = 0;
while (len > 0) {
int thisTime = len;
if (thisTime > chunkSize) {
thisTime = chunkSize;
}
len -= thisTime;
responseMessage.reset();
responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
responseMessage.appendBytes(chunk.getBytes(), chunk.getOffset() + off, thisTime);
responseMessage.end();
output(responseMessage.getBuffer(), 0, responseMessage.getLen());
off += thisTime;
}
bytesWritten += chunk.getLength();
}
return chunk.getLength();
}
@Override
public long getBytesWritten() {
return bytesWritten;
}
}
}
|
55,500
|
Bug 55500 AsyncListener.onTimeout is not called via AJP AjpNioProtocol connector
|
The AsyncListener.onTimeout is not called, when timeout occurs, when traffic routed via AJP connector configured with AjpNioProtocol protocol.
|
resolved fixed
|
cf1e104
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-03T09:24:08Z
| 2013-08-29T15:26:40Z
|
java/org/apache/coyote/ajp/AjpAprProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import org.apache.coyote.ActionCode;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jni.Socket;
import org.apache.tomcat.util.net.AprEndpoint;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapper;
/**
* Processes AJP requests.
*
* @author Remy Maucherat
* @author Henri Gomez
* @author Dan Milstein
* @author Keith Wannamaker
* @author Kevin Seguin
* @author Costin Manolache
* @author Bill Barker
*/
public class AjpAprProcessor extends AbstractAjpProcessor<Long> {
private static final Log log = LogFactory.getLog(AjpAprProcessor.class);
@Override
protected Log getLog() {
return log;
}
public AjpAprProcessor(int packetSize, AprEndpoint endpoint) {
super(packetSize, endpoint);
response.setOutputBuffer(new SocketOutputBuffer());
// Allocate input and output buffers
inputBuffer = ByteBuffer.allocateDirect(packetSize * 2);
inputBuffer.limit(0);
outputBuffer = ByteBuffer.allocateDirect(packetSize * 2);
}
/**
* Direct buffer used for input.
*/
protected final ByteBuffer inputBuffer;
/**
* Direct buffer used for output.
*/
protected final ByteBuffer outputBuffer;
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
protected void actionInternal(ActionCode actionCode, Object param) {
if (actionCode == ActionCode.ASYNC_COMPLETE) {
socketWrapper.clearDispatches();
if (asyncStateMachine.asyncComplete()) {
((AprEndpoint)endpoint).processSocketAsync(this.socketWrapper,
SocketStatus.OPEN_READ);
}
} else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) {
if (param == null) return;
long timeout = ((Long)param).longValue();
socketWrapper.setTimeout(timeout);
} else if (actionCode == ActionCode.ASYNC_DISPATCH) {
if (asyncStateMachine.asyncDispatch()) {
((AprEndpoint)endpoint).processSocketAsync(this.socketWrapper,
SocketStatus.OPEN_READ);
}
}
}
@Override
protected void setupSocket(SocketWrapper<Long> socketWrapper) {
long socketRef = socketWrapper.getSocket().longValue();
Socket.setrbb(socketRef, inputBuffer);
Socket.setsbb(socketRef, outputBuffer);
}
@Override
protected void setTimeout(SocketWrapper<Long> socketWrapper,
int timeout) throws IOException {
Socket.timeoutSet(
socketWrapper.getSocket().longValue(), timeout * 1000);
}
@Override
protected void output(byte[] src, int offset, int length)
throws IOException {
outputBuffer.put(src, offset, length);
long socketRef = socketWrapper.getSocket().longValue();
if (outputBuffer.position() > 0) {
if ((socketRef != 0) &&
writeSocket(0, outputBuffer.position(), true) < 0) {
// There are no re-tries so clear the buffer to prevent a
// possible overflow if the buffer is used again. BZ53119.
outputBuffer.clear();
throw new IOException(sm.getString("ajpprocessor.failedsend"));
}
outputBuffer.clear();
}
}
private int writeSocket(int pos, int len, boolean block) {
Lock readLock = socketWrapper.getBlockingStatusReadLock();
WriteLock writeLock = socketWrapper.getBlockingStatusWriteLock();
long socket = socketWrapper.getSocket().longValue();
boolean writeDone = false;
int result = 0;
try {
readLock.lock();
if (socketWrapper.getBlockingStatus() == block) {
result = Socket.sendbb(socket, pos, len);
writeDone = true;
}
} finally {
readLock.unlock();
}
if (!writeDone) {
try {
writeLock.lock();
socketWrapper.setBlockingStatus(block);
// Set the current settings for this socket
Socket.optSet(socket, Socket.APR_SO_NONBLOCK, (block ? 0 : 1));
// Downgrade the lock
try {
readLock.lock();
writeLock.unlock();
result = Socket.sendbb(socket, pos, len);
} finally {
readLock.unlock();
}
} finally {
// Should have been released above but may not have been on some
// exception paths
if (writeLock.isHeldByCurrentThread()) {
writeLock.unlock();
}
}
}
return result;
}
@Override
protected boolean read(byte[] buf, int pos, int n, boolean block)
throws IOException {
boolean nextReadBlocks = block;
if (!block && inputBuffer.remaining() > 0) {
nextReadBlocks = true;
}
if (inputBuffer.capacity() - inputBuffer.limit() <=
n - inputBuffer.remaining()) {
inputBuffer.compact();
inputBuffer.limit(inputBuffer.position());
inputBuffer.position(0);
}
int nRead;
while (inputBuffer.remaining() < n) {
nRead = readSocket(inputBuffer.limit(),
inputBuffer.capacity() - inputBuffer.limit(),
nextReadBlocks);
if (nRead == 0) {
// Must be a non-blocking read
return false;
} else if (nRead > 0) {
inputBuffer.limit(inputBuffer.limit() + nRead);
nextReadBlocks = true;
} else {
throw new IOException(sm.getString("ajpprocessor.failedread"));
}
}
inputBuffer.get(buf, pos, n);
return true;
}
private int readSocket(int pos, int len, boolean block) {
Lock readLock = socketWrapper.getBlockingStatusReadLock();
WriteLock writeLock = socketWrapper.getBlockingStatusWriteLock();
long socket = socketWrapper.getSocket().longValue();
boolean readDone = false;
int result = 0;
try {
readLock.lock();
if (socketWrapper.getBlockingStatus() == block) {
result = Socket.recvbb(socket, pos, len);
readDone = true;
}
} finally {
readLock.unlock();
}
if (!readDone) {
try {
writeLock.lock();
socketWrapper.setBlockingStatus(block);
// Set the current settings for this socket
Socket.optSet(socket, Socket.APR_SO_NONBLOCK, (block ? 0 : 1));
// Downgrade the lock
try {
readLock.lock();
writeLock.unlock();
result = Socket.recvbb(socket, pos, len);
} finally {
readLock.unlock();
}
} finally {
// Should have been released above but may not have been on some
// exception paths
if (writeLock.isHeldByCurrentThread()) {
writeLock.unlock();
}
}
}
return result;
}
/**
* Recycle the processor.
*/
@Override
public void recycle(boolean socketClosing) {
super.recycle(socketClosing);
inputBuffer.clear();
inputBuffer.limit(0);
outputBuffer.clear();
}
}
|
55,500
|
Bug 55500 AsyncListener.onTimeout is not called via AJP AjpNioProtocol connector
|
The AsyncListener.onTimeout is not called, when timeout occurs, when traffic routed via AJP connector configured with AjpNioProtocol protocol.
|
resolved fixed
|
cf1e104
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-03T09:24:08Z
| 2013-08-29T15:26:40Z
|
java/org/apache/coyote/ajp/AjpNioProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import org.apache.coyote.ActionCode;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.net.NioChannel;
import org.apache.tomcat.util.net.NioEndpoint;
import org.apache.tomcat.util.net.NioEndpoint.KeyAttachment;
import org.apache.tomcat.util.net.NioSelectorPool;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapper;
/**
* Processes AJP requests using NIO.
*/
public class AjpNioProcessor extends AbstractAjpProcessor<NioChannel> {
private static final Log log = LogFactory.getLog(AjpNioProcessor.class);
@Override
protected Log getLog() {
return log;
}
public AjpNioProcessor(int packetSize, NioEndpoint endpoint) {
super(packetSize, endpoint);
response.setOutputBuffer(new SocketOutputBuffer());
pool = endpoint.getSelectorPool();
}
/**
* Selector pool for the associated endpoint.
*/
protected final NioSelectorPool pool;
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
protected void actionInternal(ActionCode actionCode, Object param) {
if (actionCode == ActionCode.ASYNC_COMPLETE) {
socketWrapper.clearDispatches();
if (asyncStateMachine.asyncComplete()) {
((NioEndpoint)endpoint).dispatchForEvent(
socketWrapper.getSocket(), SocketStatus.OPEN_READ, true);
}
} else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) {
if (param == null) return;
long timeout = ((Long)param).longValue();
final KeyAttachment ka =
(KeyAttachment)socketWrapper.getSocket().getAttachment(false);
if (keepAliveTimeout > 0) {
ka.setTimeout(timeout);
}
} else if (actionCode == ActionCode.ASYNC_DISPATCH) {
if (asyncStateMachine.asyncDispatch()) {
((NioEndpoint)endpoint).dispatchForEvent(
socketWrapper.getSocket(), SocketStatus.OPEN_READ, true);
}
}
}
@Override
protected void setupSocket(SocketWrapper<NioChannel> socketWrapper)
throws IOException {
// NO-OP
}
@Override
protected void setTimeout(SocketWrapper<NioChannel> socketWrapper,
int timeout) throws IOException {
socketWrapper.setTimeout(timeout);
}
@Override
protected void output(byte[] src, int offset, int length)
throws IOException {
NioEndpoint.KeyAttachment att =
(NioEndpoint.KeyAttachment) socketWrapper.getSocket().getAttachment(false);
if ( att == null ) throw new IOException("Key must be cancelled");
ByteBuffer writeBuffer =
socketWrapper.getSocket().getBufHandler().getWriteBuffer();
writeBuffer.put(src, offset, length);
writeBuffer.flip();
long writeTimeout = att.getWriteTimeout();
Selector selector = null;
try {
selector = pool.get();
} catch (IOException x) {
//ignore
}
try {
pool.write(writeBuffer, socketWrapper.getSocket(), selector,
writeTimeout, true);
} finally {
writeBuffer.clear();
if (selector != null) {
pool.put(selector);
}
}
}
@Override
protected boolean read(byte[] buf, int pos, int n, boolean blockFirstRead)
throws IOException {
int read = 0;
int res = 0;
boolean block = blockFirstRead;
while (read < n) {
res = readSocket(buf, read + pos, n, block);
if (res > 0) {
read += res;
} else if (res == 0 && !block) {
return false;
} else {
throw new IOException(sm.getString("ajpprocessor.failedread"));
}
block = true;
}
return true;
}
private int readSocket(byte[] buf, int pos, int n, boolean block)
throws IOException {
int nRead = 0;
ByteBuffer readBuffer =
socketWrapper.getSocket().getBufHandler().getReadBuffer();
readBuffer.clear();
readBuffer.limit(n);
if ( block ) {
Selector selector = null;
try {
selector = pool.get();
} catch ( IOException x ) {
// Ignore
}
try {
NioEndpoint.KeyAttachment att =
(NioEndpoint.KeyAttachment) socketWrapper.getSocket().getAttachment(false);
if ( att == null ) throw new IOException("Key must be cancelled.");
nRead = pool.read(readBuffer, socketWrapper.getSocket(),
selector, att.getTimeout());
} catch ( EOFException eof ) {
nRead = -1;
} finally {
if ( selector != null ) pool.put(selector);
}
} else {
nRead = socketWrapper.getSocket().read(readBuffer);
}
if (nRead > 0) {
readBuffer.flip();
readBuffer.limit(nRead);
readBuffer.get(buf, pos, nRead);
return nRead;
} else if (nRead == -1) {
//return false;
throw new EOFException(sm.getString("iib.eof.error"));
} else {
return 0;
}
}
}
|
55,500
|
Bug 55500 AsyncListener.onTimeout is not called via AJP AjpNioProtocol connector
|
The AsyncListener.onTimeout is not called, when timeout occurs, when traffic routed via AJP connector configured with AjpNioProtocol protocol.
|
resolved fixed
|
cf1e104
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-03T09:24:08Z
| 2013-08-29T15:26:40Z
|
java/org/apache/coyote/ajp/AjpProcessor.java
|
/*
* 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.coyote.ajp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.apache.coyote.ActionCode;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.net.JIoEndpoint;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapper;
/**
* Processes AJP requests.
*
* @author Remy Maucherat
* @author Henri Gomez
* @author Dan Milstein
* @author Keith Wannamaker
* @author Kevin Seguin
* @author Costin Manolache
* @author Bill Barker
*/
public class AjpProcessor extends AbstractAjpProcessor<Socket> {
private static final Log log = LogFactory.getLog(AjpProcessor.class);
@Override
protected Log getLog() {
return log;
}
public AjpProcessor(int packetSize, JIoEndpoint endpoint) {
super(packetSize, endpoint);
response.setOutputBuffer(new SocketOutputBuffer());
}
protected InputStream input;
protected OutputStream output;
@Override
public void recycle(boolean socketClosing) {
super.recycle(socketClosing);
if (socketClosing) {
input = null;
output = null;
}
}
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
protected void actionInternal(ActionCode actionCode, Object param) {
if (actionCode == ActionCode.ASYNC_COMPLETE) {
socketWrapper.clearDispatches();
if (asyncStateMachine.asyncComplete()) {
((JIoEndpoint)endpoint).processSocketAsync(this.socketWrapper,
SocketStatus.OPEN_READ);
}
} else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) {
if (param == null) return;
long timeout = ((Long)param).longValue();
// if we are not piggy backing on a worker thread, set the timeout
socketWrapper.setTimeout(timeout);
} else if (actionCode == ActionCode.ASYNC_DISPATCH) {
if (asyncStateMachine.asyncDispatch()) {
((JIoEndpoint)endpoint).processSocketAsync(this.socketWrapper,
SocketStatus.OPEN_READ);
}
}
}
@Override
protected void setupSocket(SocketWrapper<Socket> socketWrapper)
throws IOException {
input = socketWrapper.getSocket().getInputStream();
output = socketWrapper.getSocket().getOutputStream();
}
@Override
protected void setTimeout(SocketWrapper<Socket> socketWrapper,
int timeout) throws IOException {
socketWrapper.getSocket().setSoTimeout(timeout);
}
@Override
protected void output(byte[] src, int offset, int length)
throws IOException {
output.write(src, offset, length);
}
@Override
protected boolean read(byte[] buf, int pos, int n, boolean blockFirstRead)
throws IOException {
int read = 0;
int res = 0;
while (read < n) {
res = input.read(buf, read + pos, n - read);
if (res > 0) {
read += res;
} else {
throw new IOException(sm.getString("ajpprocessor.failedread"));
}
}
return true;
}
}
|
55,342
|
Bug 55342 Lost interruption
|
org.apache.tomcat.jdbc.pool.ConnectionPool#close should not call Thread.interrupted() because interrupt was already reset by code that thrown InterruptedException. } catch (InterruptedException ex) { if (getPoolProperties().getPropagateInterruptState()) { Thread.currentThread().interrupt(); - } else { - Thread.interrupted(); } }
|
resolved fixed
|
41225cd
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T02:17:25Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
|
/*
* 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.jdbc.pool;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* Implementation of simple connection pool.
* The ConnectionPool uses a {@link PoolProperties} object for storing all the meta information about the connection pool.
* As the underlying implementation, the connection pool uses {@link java.util.concurrent.BlockingQueue} to store active and idle connections.
* A custom implementation of a fair {@link FairBlockingQueue} blocking queue is provided with the connection pool itself.
* @author Filip Hanik
* @version 1.0
*/
public class ConnectionPool {
/**
* Default domain for objects registering with an mbean server
*/
public static final String POOL_JMX_DOMAIN = "tomcat.jdbc";
/**
* Prefix type for JMX registration
*/
public static final String POOL_JMX_TYPE_PREFIX = POOL_JMX_DOMAIN+":type=";
/**
* Logger
*/
private static final Log log = LogFactory.getLog(ConnectionPool.class);
//===============================================================================
// INSTANCE/QUICK ACCESS VARIABLE
//===============================================================================
/**
* Carries the size of the pool, instead of relying on a queue implementation
* that usually iterates over to get an exact count
*/
private AtomicInteger size = new AtomicInteger(0);
/**
* All the information about the connection pool
* These are the properties the pool got instantiated with
*/
private PoolConfiguration poolProperties;
/**
* Contains all the connections that are in use
* TODO - this shouldn't be a blocking queue, simply a list to hold our objects
*/
private BlockingQueue<PooledConnection> busy;
/**
* Contains all the idle connections
*/
private BlockingQueue<PooledConnection> idle;
/**
* The thread that is responsible for checking abandoned and idle threads
*/
private volatile PoolCleaner poolCleaner;
/**
* Pool closed flag
*/
private volatile boolean closed = false;
/**
* Since newProxyInstance performs the same operation, over and over
* again, it is much more optimized if we simply store the constructor ourselves.
*/
private Constructor<?> proxyClassConstructor;
/**
* Executor service used to cancel Futures
*/
private ThreadPoolExecutor cancellator = new ThreadPoolExecutor(0,1,1000,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
/**
* reference to the JMX mbean
*/
protected org.apache.tomcat.jdbc.pool.jmx.ConnectionPool jmxPool = null;
/**
* counter to track how many threads are waiting for a connection
*/
private AtomicInteger waitcount = new AtomicInteger(0);
private AtomicLong poolVersion = new AtomicLong(Long.MIN_VALUE);
//===============================================================================
// PUBLIC METHODS
//===============================================================================
/**
* Instantiate a connection pool. This will create connections if initialSize is larger than 0.
* The {@link PoolProperties} should not be reused for another connection pool.
* @param prop PoolProperties - all the properties for this connection pool
* @throws SQLException
*/
public ConnectionPool(PoolConfiguration prop) throws SQLException {
//setup quick access variables and pools
init(prop);
}
/**
* Retrieves a Connection future. If a connection is not available, one can block using future.get()
* until a connection has become available.
* If a connection is not retrieved, the Future must be cancelled in order for the connection to be returned
* to the pool.
* @return a Future containing a reference to the connection or the future connection
* @throws SQLException
*/
public Future<Connection> getConnectionAsync() throws SQLException {
try {
PooledConnection pc = borrowConnection(0, null, null);
if (pc!=null) {
return new ConnectionFuture(pc);
}
}catch (SQLException x) {
if (x.getMessage().indexOf("NoWait")<0) {
throw x;
}
}
//we can only retrieve a future if the underlying queue supports it.
if (idle instanceof FairBlockingQueue<?>) {
Future<PooledConnection> pcf = ((FairBlockingQueue<PooledConnection>)idle).pollAsync();
return new ConnectionFuture(pcf);
} else if (idle instanceof MultiLockFairBlockingQueue<?>) {
Future<PooledConnection> pcf = ((MultiLockFairBlockingQueue<PooledConnection>)idle).pollAsync();
return new ConnectionFuture(pcf);
} else {
throw new SQLException("Connection pool is misconfigured, doesn't support async retrieval. Set the 'fair' property to 'true'");
}
}
/**
* Borrows a connection from the pool. If a connection is available (in the idle queue) or the pool has not reached
* {@link PoolProperties#maxActive maxActive} connections a connection is returned immediately.
* If no connection is available, the pool will attempt to fetch a connection for {@link PoolProperties#maxWait maxWait} milliseconds.
* @return Connection - a java.sql.Connection/javax.sql.PooledConnection reflection proxy, wrapping the underlying object.
* @throws SQLException - if the wait times out or a failure occurs creating a connection
*/
public Connection getConnection() throws SQLException {
//check out a connection
PooledConnection con = borrowConnection(-1,null,null);
return setupConnection(con);
}
/**
* Borrows a connection from the pool. If a connection is available (in the
* idle queue) or the pool has not reached {@link PoolProperties#maxActive
* maxActive} connections a connection is returned immediately. If no
* connection is available, the pool will attempt to fetch a connection for
* {@link PoolProperties#maxWait maxWait} milliseconds.
*
* @return Connection - a java.sql.Connection/javax.sql.PooledConnection
* reflection proxy, wrapping the underlying object.
* @throws SQLException
* - if the wait times out or a failure occurs creating a
* connection
*/
public Connection getConnection(String username, String password) throws SQLException {
// check out a connection
PooledConnection con = borrowConnection(-1, username, password);
return setupConnection(con);
}
/**
* Returns the name of this pool
* @return String - the name of the pool
*/
public String getName() {
return getPoolProperties().getPoolName();
}
/**
* Return the number of threads waiting for a connection
* @return number of threads waiting for a connection
*/
public int getWaitCount() {
return waitcount.get();
}
/**
* Returns the pool properties associated with this connection pool
* @return PoolProperties
*
*/
public PoolConfiguration getPoolProperties() {
return this.poolProperties;
}
/**
* Returns the total size of this pool, this includes both busy and idle connections
* @return int - number of established connections to the database
*/
public int getSize() {
return size.get();
}
/**
* Returns the number of connections that are in use
* @return int - number of established connections that are being used by the application
*/
public int getActive() {
return busy.size();
}
/**
* Returns the number of idle connections
* @return int - number of established connections not being used
*/
public int getIdle() {
return idle.size();
}
/**
* Returns true if {@link #close close} has been called, and the connection pool is unusable
* @return boolean
*/
public boolean isClosed() {
return this.closed;
}
//===============================================================================
// PROTECTED METHODS
//===============================================================================
/**
* configures a pooled connection as a proxy.
* This Proxy implements {@link java.sql.Connection} and {@link javax.sql.PooledConnection} interfaces.
* All calls on {@link java.sql.Connection} methods will be propagated down to the actual JDBC connection except for the
* {@link java.sql.Connection#close()} method.
* @param con a {@link PooledConnection} to wrap in a Proxy
* @return a {@link java.sql.Connection} object wrapping a pooled connection.
* @throws SQLException if an interceptor can't be configured, if the proxy can't be instantiated
*/
protected Connection setupConnection(PooledConnection con) throws SQLException {
//fetch previously cached interceptor proxy - one per connection
JdbcInterceptor handler = con.getHandler();
if (handler==null) {
//build the proxy handler
handler = new ProxyConnection(this,con,getPoolProperties().isUseEquals());
//set up the interceptor chain
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=proxies.length-1; i>=0; i--) {
try {
//create a new instance
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
//configure properties
interceptor.setProperties(proxies[i].getProperties());
//setup the chain
interceptor.setNext(handler);
//call reset
interceptor.reset(this, con);
//configure the last one to be held by the connection
handler = interceptor;
}catch(Exception x) {
SQLException sx = new SQLException("Unable to instantiate interceptor chain.");
sx.initCause(x);
throw sx;
}
}
//cache handler for the next iteration
con.setHandler(handler);
} else {
JdbcInterceptor next = handler;
//we have a cached handler, reset it
while (next!=null) {
next.reset(this, con);
next = next.getNext();
}
}
try {
getProxyConstructor(con.getXAConnection() != null);
//create the proxy
//TODO possible optimization, keep track if this connection was returned properly, and don't generate a new facade
Connection connection = null;
if (getPoolProperties().getUseDisposableConnectionFacade() ) {
connection = (Connection)proxyClassConstructor.newInstance(new Object[] { new DisposableConnectionFacade(handler) });
} else {
connection = (Connection)proxyClassConstructor.newInstance(new Object[] {handler});
}
//return the connection
return connection;
}catch (Exception x) {
SQLException s = new SQLException();
s.initCause(x);
throw s;
}
}
/**
* Creates and caches a {@link java.lang.reflect.Constructor} used to instantiate the proxy object.
* We cache this, since the creation of a constructor is fairly slow.
* @return constructor used to instantiate the wrapper object
* @throws NoSuchMethodException
*/
public Constructor<?> getProxyConstructor(boolean xa) throws NoSuchMethodException {
//cache the constructor
if (proxyClassConstructor == null ) {
Class<?> proxyClass = xa ?
Proxy.getProxyClass(ConnectionPool.class.getClassLoader(), new Class[] {java.sql.Connection.class,javax.sql.PooledConnection.class, javax.sql.XAConnection.class}) :
Proxy.getProxyClass(ConnectionPool.class.getClassLoader(), new Class[] {java.sql.Connection.class,javax.sql.PooledConnection.class});
proxyClassConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
}
return proxyClassConstructor;
}
/**
* Closes the pool and all disconnects all idle connections
* Active connections will be closed upon the {@link java.sql.Connection#close close} method is called
* on the underlying connection instead of being returned to the pool
* @param force - true to even close the active connections
*/
protected void close(boolean force) {
//are we already closed
if (this.closed) return;
//prevent other threads from entering
this.closed = true;
//stop background thread
if (poolCleaner!=null) {
poolCleaner.stopRunning();
}
/* release all idle connections */
BlockingQueue<PooledConnection> pool = (idle.size()>0)?idle:(force?busy:idle);
while (pool.size()>0) {
try {
//retrieve the next connection
PooledConnection con = pool.poll(1000, TimeUnit.MILLISECONDS);
//close it and retrieve the next one, if one is available
while (con != null) {
//close the connection
if (pool==idle)
release(con);
else
abandon(con);
if (pool.size()>0) {
con = pool.poll(1000, TimeUnit.MILLISECONDS);
} else {
break;
}
} //while
} catch (InterruptedException ex) {
if (getPoolProperties().getPropagateInterruptState()) {
Thread.currentThread().interrupt();
} else {
Thread.interrupted();
}
}
if (pool.size()==0 && force && pool!=busy) pool = busy;
}
if (this.getPoolProperties().isJmxEnabled()) this.jmxPool = null;
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=0; i<proxies.length; i++) {
try {
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
interceptor.setProperties(proxies[i].getProperties());
interceptor.poolClosed(this);
}catch (Exception x) {
log.debug("Unable to inform interceptor of pool closure.",x);
}
}
} //closePool
/**
* Initialize the connection pool - called from the constructor
* @param properties PoolProperties - properties used to initialize the pool with
* @throws SQLException if initialization fails
*/
protected void init(PoolConfiguration properties) throws SQLException {
poolProperties = properties;
//make sure the pool is properly configured
if (properties.getMaxActive()<1) {
log.warn("maxActive is smaller than 1, setting maxActive to: "+PoolProperties.DEFAULT_MAX_ACTIVE);
properties.setMaxActive(PoolProperties.DEFAULT_MAX_ACTIVE);
}
if (properties.getMaxActive()<properties.getInitialSize()) {
log.warn("initialSize is larger than maxActive, setting initialSize to: "+properties.getMaxActive());
properties.setInitialSize(properties.getMaxActive());
}
if (properties.getMinIdle()>properties.getMaxActive()) {
log.warn("minIdle is larger than maxActive, setting minIdle to: "+properties.getMaxActive());
properties.setMinIdle(properties.getMaxActive());
}
if (properties.getMaxIdle()>properties.getMaxActive()) {
log.warn("maxIdle is larger than maxActive, setting maxIdle to: "+properties.getMaxActive());
properties.setMaxIdle(properties.getMaxActive());
}
if (properties.getMaxIdle()<properties.getMinIdle()) {
log.warn("maxIdle is smaller than minIdle, setting maxIdle to: "+properties.getMinIdle());
properties.setMaxIdle(properties.getMinIdle());
}
//make space for 10 extra in case we flow over a bit
busy = new ArrayBlockingQueue<>(properties.getMaxActive(),false);
//busy = new FairBlockingQueue<PooledConnection>();
//make space for 10 extra in case we flow over a bit
if (properties.isFairQueue()) {
idle = new FairBlockingQueue<>();
//idle = new MultiLockFairBlockingQueue<PooledConnection>();
//idle = new LinkedTransferQueue<PooledConnection>();
//idle = new ArrayBlockingQueue<PooledConnection>(properties.getMaxActive(),false);
} else {
idle = new ArrayBlockingQueue<>(properties.getMaxActive(),properties.isFairQueue());
}
initializePoolCleaner(properties);
//create JMX MBean
if (this.getPoolProperties().isJmxEnabled()) createMBean();
//Parse and create an initial set of interceptors. Letting them know the pool has started.
//These interceptors will not get any connection.
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=0; i<proxies.length; i++) {
try {
if (log.isDebugEnabled()) {
log.debug("Creating interceptor instance of class:"+proxies[i].getInterceptorClass());
}
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
interceptor.setProperties(proxies[i].getProperties());
interceptor.poolStarted(this);
}catch (Exception x) {
log.error("Unable to inform interceptor of pool start.",x);
if (jmxPool!=null) jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_INIT, getStackTrace(x));
close(true);
SQLException ex = new SQLException();
ex.initCause(x);
throw ex;
}
}
//initialize the pool with its initial set of members
PooledConnection[] initialPool = new PooledConnection[poolProperties.getInitialSize()];
try {
for (int i = 0; i < initialPool.length; i++) {
initialPool[i] = this.borrowConnection(0, null, null); //don't wait, should be no contention
} //for
} catch (SQLException x) {
if (jmxPool!=null) jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_INIT, getStackTrace(x));
close(true);
throw x;
} finally {
//return the members as idle to the pool
for (int i = 0; i < initialPool.length; i++) {
if (initialPool[i] != null) {
try {this.returnConnection(initialPool[i]);}catch(Exception x){/*NOOP*/}
} //end if
} //for
} //catch
closed = false;
}
public void initializePoolCleaner(PoolConfiguration properties) {
//if the evictor thread is supposed to run, start it now
if (properties.isPoolSweeperEnabled()) {
poolCleaner = new PoolCleaner(this, properties.getTimeBetweenEvictionRunsMillis());
poolCleaner.start();
} //end if
}
//===============================================================================
// CONNECTION POOLING IMPL LOGIC
//===============================================================================
/**
* thread safe way to abandon a connection
* signals a connection to be abandoned.
* this will disconnect the connection, and log the stack trace if logAbanded=true
* @param con PooledConnection
*/
protected void abandon(PooledConnection con) {
if (con == null)
return;
try {
con.lock();
String trace = con.getStackTrace();
if (getPoolProperties().isLogAbandoned()) {
log.warn("Connection has been abandoned " + con + ":" + trace);
}
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_ABANDON, trace);
}
//release the connection
release(con);
} finally {
con.unlock();
}
}
/**
* thread safe way to abandon a connection
* signals a connection to be abandoned.
* this will disconnect the connection, and log the stack trace if logAbanded=true
* @param con PooledConnection
*/
protected void suspect(PooledConnection con) {
if (con == null)
return;
if (con.isSuspect())
return;
try {
con.lock();
String trace = con.getStackTrace();
if (getPoolProperties().isLogAbandoned()) {
log.warn("Connection has been marked suspect, possibly abandoned " + con + "["+(System.currentTimeMillis()-con.getTimestamp())+" ms.]:" + trace);
}
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.SUSPECT_ABANDONED_NOTIFICATION, trace);
}
con.setSuspect(true);
} finally {
con.unlock();
}
}
/**
* thread safe way to release a connection
* @param con PooledConnection
*/
protected void release(PooledConnection con) {
if (con == null)
return;
try {
con.lock();
if (con.release()) {
//counter only decremented once
size.addAndGet(-1);
con.setHandler(null);
}
} finally {
con.unlock();
}
// we've asynchronously reduced the number of connections
// we could have threads stuck in idle.poll(timeout) that will never be
// notified
if (waitcount.get() > 0) {
idle.offer(create(true));
}
}
/**
* Thread safe way to retrieve a connection from the pool
* @param wait - time to wait, overrides the maxWait from the properties,
* set to -1 if you wish to use maxWait, 0 if you wish no wait time.
* @return PooledConnection
* @throws SQLException
*/
private PooledConnection borrowConnection(int wait, String username, String password) throws SQLException {
if (isClosed()) {
throw new SQLException("Connection pool closed.");
} //end if
//get the current time stamp
long now = System.currentTimeMillis();
//see if there is one available immediately
PooledConnection con = idle.poll();
while (true) {
if (con!=null) {
//configure the connection and return it
PooledConnection result = borrowConnection(now, con, username, password);
//null should never be returned, but was in a previous impl.
if (result!=null) return result;
}
//if we get here, see if we need to create one
//this is not 100% accurate since it doesn't use a shared
//atomic variable - a connection can become idle while we are creating
//a new connection
if (size.get() < getPoolProperties().getMaxActive()) {
//atomic duplicate check
if (size.addAndGet(1) > getPoolProperties().getMaxActive()) {
//if we got here, two threads passed through the first if
size.decrementAndGet();
} else {
//create a connection, we're below the limit
return createConnection(now, con, username, password);
}
} //end if
//calculate wait time for this iteration
long maxWait = wait;
//if the passed in wait time is -1, means we should use the pool property value
if (wait==-1) {
maxWait = (getPoolProperties().getMaxWait()<=0)?Long.MAX_VALUE:getPoolProperties().getMaxWait();
}
long timetowait = Math.max(0, maxWait - (System.currentTimeMillis() - now));
waitcount.incrementAndGet();
try {
//retrieve an existing connection
con = idle.poll(timetowait, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
if (getPoolProperties().getPropagateInterruptState()) {
Thread.currentThread().interrupt();
} else {
Thread.interrupted();
}
SQLException sx = new SQLException("Pool wait interrupted.");
sx.initCause(ex);
throw sx;
} finally {
waitcount.decrementAndGet();
}
if (maxWait==0 && con == null) { //no wait, return one if we have one
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.POOL_EMPTY, "Pool empty - no wait.");
}
throw new PoolExhaustedException("[" + Thread.currentThread().getName()+"] " +
"NoWait: Pool empty. Unable to fetch a connection, none available["+busy.size()+" in use].");
}
//we didn't get a connection, lets see if we timed out
if (con == null) {
if ((System.currentTimeMillis() - now) >= maxWait) {
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.POOL_EMPTY, "Pool empty - timeout.");
}
throw new PoolExhaustedException("[" + Thread.currentThread().getName()+"] " +
"Timeout: Pool empty. Unable to fetch a connection in " + (maxWait / 1000) +
" seconds, none available[size:"+size.get() +"; busy:"+busy.size()+"; idle:"+idle.size()+"; lastwait:"+timetowait+"].");
} else {
//no timeout, lets try again
continue;
}
}
} //while
}
/**
* Creates a JDBC connection and tries to connect to the database.
* @param now timestamp of when this was called
* @param notUsed Argument not used
* @return a PooledConnection that has been connected
* @throws SQLException
*/
protected PooledConnection createConnection(long now, PooledConnection notUsed, String username, String password) throws SQLException {
//no connections where available we'll create one
PooledConnection con = create(false);
if (username!=null) con.getAttributes().put(PooledConnection.PROP_USER, username);
if (password!=null) con.getAttributes().put(PooledConnection.PROP_PASSWORD, password);
boolean error = false;
try {
//connect and validate the connection
con.lock();
con.connect();
if (con.validate(PooledConnection.VALIDATE_INIT)) {
//no need to lock a new one, its not contented
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
} else {
//validation failed, make sure we disconnect
//and clean up
error =true;
} //end if
} catch (Exception e) {
error = true;
if (log.isDebugEnabled())
log.debug("Unable to create a new JDBC connection.", e);
if (e instanceof SQLException) {
throw (SQLException)e;
} else {
SQLException ex = new SQLException(e.getMessage());
ex.initCause(e);
throw ex;
}
} finally {
// con can never be null here
if (error ) {
release(con);
}
con.unlock();
}//catch
return null;
}
/**
* Validates and configures a previously idle connection
* @param now - timestamp
* @param con - the connection to validate and configure
* @return con
* @throws SQLException if a validation error happens
*/
protected PooledConnection borrowConnection(long now, PooledConnection con, String username, String password) throws SQLException {
//we have a connection, lets set it up
//flag to see if we need to nullify
boolean setToNull = false;
try {
con.lock();
boolean usercheck = con.checkUser(username, password);
if (con.isReleased()) {
return null;
}
if (!con.isDiscarded() && !con.isInitialized()) {
//attempt to connect
try {
con.connect();
} catch (Exception x) {
release(con);
setToNull = true;
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
}
if (usercheck) {
if ((!con.isDiscarded()) && con.validate(PooledConnection.VALIDATE_BORROW)) {
//set the timestamp
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
//set the stack trace for this pool
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
}
}
//if we reached here, that means the connection
//is either has another principal, is discarded or validation failed.
//we will make one more attempt
//in order to guarantee that the thread that just acquired
//the connection shouldn't have to poll again.
try {
con.reconnect();
if (con.validate(PooledConnection.VALIDATE_INIT)) {
//set the timestamp
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
//set the stack trace for this pool
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
} else {
//validation failed.
release(con);
setToNull = true;
throw new SQLException("Failed to validate a newly established connection.");
}
} catch (Exception x) {
release(con);
setToNull = true;
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
} finally {
con.unlock();
if (setToNull) {
con = null;
}
}
}
/**
* Terminate the current transaction for the given connection.
* @param con
* @return <code>true</code> if the connection TX termination succeeded
* otherwise <code>false</code>
*/
protected boolean terminateTransaction(PooledConnection con) {
try {
if (Boolean.FALSE.equals(con.getPoolProperties().getDefaultAutoCommit())) {
if (this.getPoolProperties().getRollbackOnReturn()) {
boolean autocommit = con.getConnection().getAutoCommit();
if (!autocommit) con.getConnection().rollback();
} else if (this.getPoolProperties().getCommitOnReturn()) {
boolean autocommit = con.getConnection().getAutoCommit();
if (!autocommit) con.getConnection().commit();
}
}
return true;
} catch (SQLException x) {
log.warn("Unable to terminate transaction, connection will be closed.",x);
return false;
}
}
/**
* Determines if a connection should be closed upon return to the pool.
* @param con - the connection
* @param action - the validation action that should be performed
* @return true if the connection should be closed
*/
protected boolean shouldClose(PooledConnection con, int action) {
if (con.getConnectionVersion() < getPoolVersion()) return true;
if (con.isDiscarded()) return true;
if (isClosed()) return true;
if (!con.validate(action)) return true;
if (!terminateTransaction(con)) return true;
if (getPoolProperties().getMaxAge()>0 ) {
return (System.currentTimeMillis()-con.getLastConnected()) > getPoolProperties().getMaxAge();
} else {
return false;
}
}
/**
* Returns a connection to the pool
* If the pool is closed, the connection will be released
* If the connection is not part of the busy queue, it will be released.
* If {@link PoolProperties#testOnReturn} is set to true it will be validated
* @param con PooledConnection to be returned to the pool
*/
protected void returnConnection(PooledConnection con) {
if (isClosed()) {
//if the connection pool is closed
//close the connection instead of returning it
release(con);
return;
} //end if
if (con != null) {
try {
con.lock();
if (busy.remove(con)) {
if (!shouldClose(con,PooledConnection.VALIDATE_RETURN)) {
con.setStackTrace(null);
con.setTimestamp(System.currentTimeMillis());
if (((idle.size()>=poolProperties.getMaxIdle()) && !poolProperties.isPoolSweeperEnabled()) || (!idle.offer(con))) {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool, idle["+idle.size()+"]>=maxIdle["+poolProperties.getMaxIdle()+"] idle.offer failed.");
}
release(con);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool.");
}
release(con);
} //end if
} else {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool, busy.remove failed.");
}
release(con);
}
} finally {
con.unlock();
}
} //end if
} //checkIn
/**
* Determines if a connection should be abandoned based on
* {@link PoolProperties#abandonWhenPercentageFull} setting.
* @return true if the connection should be abandoned
*/
protected boolean shouldAbandon() {
if (poolProperties.getAbandonWhenPercentageFull()==0) return true;
float used = busy.size();
float max = poolProperties.getMaxActive();
float perc = poolProperties.getAbandonWhenPercentageFull();
return (used/max*100f)>=perc;
}
/**
* Iterates through all the busy connections and checks for connections that have timed out
*/
public void checkAbandoned() {
try {
if (busy.size()==0) return;
Iterator<PooledConnection> locked = busy.iterator();
int sto = getPoolProperties().getSuspectTimeout();
while (locked.hasNext()) {
PooledConnection con = locked.next();
boolean setToNull = false;
try {
con.lock();
//the con has been returned to the pool
//ignore it
if (idle.contains(con))
continue;
long time = con.getTimestamp();
long now = System.currentTimeMillis();
if (shouldAbandon() && (now - time) > con.getAbandonTimeout()) {
busy.remove(con);
abandon(con);
setToNull = true;
} else if (sto > 0 && (now - time) > (sto*1000)) {
suspect(con);
} else {
//do nothing
} //end if
} finally {
con.unlock();
if (setToNull)
con = null;
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("checkAbandoned failed." ,e);
} catch (Exception e) {
log.warn("checkAbandoned failed, it will be retried.",e);
}
}
/**
* Iterates through the idle connections and resizes the idle pool based on parameters
* {@link PoolProperties#maxIdle}, {@link PoolProperties#minIdle}, {@link PoolProperties#minEvictableIdleTimeMillis}
*/
public void checkIdle() {
checkIdle(false);
}
public void checkIdle(boolean ignoreMinSize) {
try {
if (idle.size()==0) return;
long now = System.currentTimeMillis();
Iterator<PooledConnection> unlocked = idle.iterator();
while ( (ignoreMinSize || (idle.size()>=getPoolProperties().getMinIdle())) && unlocked.hasNext()) {
PooledConnection con = unlocked.next();
boolean setToNull = false;
try {
con.lock();
//the con been taken out, we can't clean it up
if (busy.contains(con))
continue;
long time = con.getTimestamp();
if (shouldReleaseIdle(now, con, time)) {
release(con);
idle.remove(con);
setToNull = true;
} else {
//do nothing
} //end if
} finally {
con.unlock();
if (setToNull)
con = null;
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("checkIdle failed." ,e);
} catch (Exception e) {
log.warn("checkIdle failed, it will be retried.",e);
}
}
protected boolean shouldReleaseIdle(long now, PooledConnection con, long time) {
if (con.getConnectionVersion() < getPoolVersion()) return true;
else return (con.getReleaseTime()>0) && ((now - time) > con.getReleaseTime()) && (getSize()>getPoolProperties().getMinIdle());
}
/**
* Forces a validation of all idle connections if {@link PoolProperties#testWhileIdle} is set.
*/
public void testAllIdle() {
try {
if (idle.size()==0) return;
Iterator<PooledConnection> unlocked = idle.iterator();
while (unlocked.hasNext()) {
PooledConnection con = unlocked.next();
try {
con.lock();
//the con been taken out, we can't clean it up
if (busy.contains(con))
continue;
if (!con.validate(PooledConnection.VALIDATE_IDLE)) {
idle.remove(con);
release(con);
}
} finally {
con.unlock();
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("testAllIdle failed." ,e);
} catch (Exception e) {
log.warn("testAllIdle failed, it will be retried.",e);
}
}
/**
* Creates a stack trace representing the existing thread's current state.
* @return a string object representing the current state.
* TODO investigate if we simply should store {@link java.lang.Thread#getStackTrace()} elements
*/
protected static String getThreadDump() {
Exception x = new Exception();
x.fillInStackTrace();
return getStackTrace(x);
}
/**
* Convert an exception into a String
* @param x - the throwable
* @return a string representing the stack trace
*/
public static String getStackTrace(Throwable x) {
if (x == null) {
return null;
} else {
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.PrintStream writer = new java.io.PrintStream(bout);
x.printStackTrace(writer);
String result = bout.toString();
return (x.getMessage()!=null && x.getMessage().length()>0)? x.getMessage()+";"+result:result;
} //end if
}
/**
* Create a new pooled connection object. Not connected nor validated.
* @return a pooled connection object
*/
protected PooledConnection create(boolean incrementCounter) {
if (incrementCounter) size.incrementAndGet();
PooledConnection con = new PooledConnection(getPoolProperties(), this);
return con;
}
/**
* Purges all connections in the pool.
* For connections currently in use, these connections will be
* purged when returned on the pool. This call also
* purges connections that are idle and in the pool
* To only purge used/active connections see {@link #purgeOnReturn()}
*/
public void purge() {
purgeOnReturn();
checkIdle(true);
}
/**
* Purges connections when they are returned from the pool.
* This call does not purge idle connections until they are used.
* To purge idle connections see {@link #purge()}
*/
public void purgeOnReturn() {
poolVersion.incrementAndGet();
}
/**
* Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded
* @param con
*/
protected void finalize(PooledConnection con) {
JdbcInterceptor handler = con.getHandler();
while (handler!=null) {
handler.reset(null, null);
handler=handler.getNext();
}
}
/**
* Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded
* @param con
*/
protected void disconnectEvent(PooledConnection con, boolean finalizing) {
JdbcInterceptor handler = con.getHandler();
while (handler!=null) {
handler.disconnected(this, con, finalizing);
handler=handler.getNext();
}
}
/**
* Return the object that is potentially registered in JMX for notifications
* @return the object implementing the {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} interface
*/
public org.apache.tomcat.jdbc.pool.jmx.ConnectionPool getJmxPool() {
return jmxPool;
}
/**
* Create MBean object that can be registered.
*/
protected void createMBean() {
try {
jmxPool = new org.apache.tomcat.jdbc.pool.jmx.ConnectionPool(this);
} catch (Exception x) {
log.warn("Unable to start JMX integration for connection pool. Instance["+getName()+"] can't be monitored.",x);
}
}
/**
* Tread safe wrapper around a future for the regular queue
* This one retrieves the pooled connection object
* and performs the initialization according to
* interceptors and validation rules.
* This class is thread safe and is cancellable
* @author fhanik
*
*/
protected class ConnectionFuture implements Future<Connection>, Runnable {
Future<PooledConnection> pcFuture = null;
AtomicBoolean configured = new AtomicBoolean(false);
CountDownLatch latch = new CountDownLatch(1);
volatile Connection result = null;
SQLException cause = null;
AtomicBoolean cancelled = new AtomicBoolean(false);
volatile PooledConnection pc = null;
public ConnectionFuture(Future<PooledConnection> pcf) {
this.pcFuture = pcf;
}
public ConnectionFuture(PooledConnection pc) throws SQLException {
this.pc = pc;
result = ConnectionPool.this.setupConnection(pc);
configured.set(true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (pc!=null) {
return false;
} else if ((!cancelled.get()) && cancelled.compareAndSet(false, true)) {
//cancel by retrieving the connection and returning it to the pool
ConnectionPool.this.cancellator.execute(this);
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Connection get() throws InterruptedException, ExecutionException {
try {
return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}catch (TimeoutException x) {
throw new ExecutionException(x);
}
}
/**
* {@inheritDoc}
*/
@Override
public Connection get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
PooledConnection pc = this.pc!=null?this.pc:pcFuture.get(timeout,unit);
if (pc!=null) {
if (result!=null) return result;
if (configured.compareAndSet(false, true)) {
try {
pc = borrowConnection(System.currentTimeMillis(),pc, null, null);
result = ConnectionPool.this.setupConnection(pc);
} catch (SQLException x) {
cause = x;
} finally {
latch.countDown();
}
} else {
//if we reach here, another thread is configuring the actual connection
latch.await(timeout,unit); //this shouldn't block for long
}
if (result==null) throw new ExecutionException(cause);
return result;
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCancelled() {
return pc==null && (pcFuture.isCancelled() || cancelled.get());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDone() {
return pc!=null || pcFuture.isDone();
}
/**
* run method to be executed when cancelled by an executor
*/
@Override
public void run() {
try {
Connection con = get(); //complete this future
con.close(); //return to the pool
}catch (ExecutionException ex) {
//we can ignore this
}catch (Exception x) {
ConnectionPool.log.error("Unable to cancel ConnectionFuture.",x);
}
}
}
private static volatile Timer poolCleanTimer = null;
private static HashSet<PoolCleaner> cleaners = new HashSet<>();
private static synchronized void registerCleaner(PoolCleaner cleaner) {
unregisterCleaner(cleaner);
cleaners.add(cleaner);
if (poolCleanTimer == null) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(ConnectionPool.class.getClassLoader());
poolCleanTimer = new Timer("PoolCleaner["+ System.identityHashCode(ConnectionPool.class.getClassLoader()) + ":"+
System.currentTimeMillis() + "]", true);
}finally {
Thread.currentThread().setContextClassLoader(loader);
}
}
poolCleanTimer.scheduleAtFixedRate(cleaner, cleaner.sleepTime,cleaner.sleepTime);
}
private static synchronized void unregisterCleaner(PoolCleaner cleaner) {
boolean removed = cleaners.remove(cleaner);
if (removed) {
cleaner.cancel();
if (poolCleanTimer != null) {
poolCleanTimer.purge();
if (cleaners.size() == 0) {
poolCleanTimer.cancel();
poolCleanTimer = null;
}
}
}
}
public static Set<TimerTask> getPoolCleaners() {
return Collections.<TimerTask>unmodifiableSet(cleaners);
}
public long getPoolVersion() {
return poolVersion.get();
}
public static Timer getPoolTimer() {
return poolCleanTimer;
}
protected static class PoolCleaner extends TimerTask {
protected WeakReference<ConnectionPool> pool;
protected long sleepTime;
protected volatile long lastRun = 0;
PoolCleaner(ConnectionPool pool, long sleepTime) {
this.pool = new WeakReference<>(pool);
this.sleepTime = sleepTime;
if (sleepTime <= 0) {
log.warn("Database connection pool evicter thread interval is set to 0, defaulting to 30 seconds");
this.sleepTime = 1000 * 30;
} else if (sleepTime < 1000) {
log.warn("Database connection pool evicter thread interval is set to lower than 1 second.");
}
}
@Override
public void run() {
ConnectionPool pool = this.pool.get();
if (pool == null) {
stopRunning();
} else if (!pool.isClosed() &&
(System.currentTimeMillis() - lastRun) > sleepTime) {
lastRun = System.currentTimeMillis();
try {
if (pool.getPoolProperties().isRemoveAbandoned())
pool.checkAbandoned();
if (pool.getPoolProperties().getMinIdle() < pool.idle
.size())
pool.checkIdle();
if (pool.getPoolProperties().isTestWhileIdle())
pool.testAllIdle();
} catch (Exception x) {
log.error("", x);
}
}
}
public void start() {
registerCleaner(this);
}
public void stopRunning() {
unregisterCleaner(this);
}
}
}
|
55,343
|
Bug 55343 Add flag to ignore exceptions while creating initial pool
|
I want my initial pool to be of some size i.e. not empty AND start even if it fails to create all or some of connections. If pool fails to create initial connections for some reason it just throws exceptions. To workaround that I have to set initial pool size to 0. It can be handy to add a flag to ignore (just log them) exceptions that occur while creating initial connections.
|
resolved fixed
|
4aa42d7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T08:56:24Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
|
/*
* 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.jdbc.pool;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* Implementation of simple connection pool.
* The ConnectionPool uses a {@link PoolProperties} object for storing all the meta information about the connection pool.
* As the underlying implementation, the connection pool uses {@link java.util.concurrent.BlockingQueue} to store active and idle connections.
* A custom implementation of a fair {@link FairBlockingQueue} blocking queue is provided with the connection pool itself.
* @author Filip Hanik
* @version 1.0
*/
public class ConnectionPool {
/**
* Default domain for objects registering with an mbean server
*/
public static final String POOL_JMX_DOMAIN = "tomcat.jdbc";
/**
* Prefix type for JMX registration
*/
public static final String POOL_JMX_TYPE_PREFIX = POOL_JMX_DOMAIN+":type=";
/**
* Logger
*/
private static final Log log = LogFactory.getLog(ConnectionPool.class);
//===============================================================================
// INSTANCE/QUICK ACCESS VARIABLE
//===============================================================================
/**
* Carries the size of the pool, instead of relying on a queue implementation
* that usually iterates over to get an exact count
*/
private AtomicInteger size = new AtomicInteger(0);
/**
* All the information about the connection pool
* These are the properties the pool got instantiated with
*/
private PoolConfiguration poolProperties;
/**
* Contains all the connections that are in use
* TODO - this shouldn't be a blocking queue, simply a list to hold our objects
*/
private BlockingQueue<PooledConnection> busy;
/**
* Contains all the idle connections
*/
private BlockingQueue<PooledConnection> idle;
/**
* The thread that is responsible for checking abandoned and idle threads
*/
private volatile PoolCleaner poolCleaner;
/**
* Pool closed flag
*/
private volatile boolean closed = false;
/**
* Since newProxyInstance performs the same operation, over and over
* again, it is much more optimized if we simply store the constructor ourselves.
*/
private Constructor<?> proxyClassConstructor;
/**
* Executor service used to cancel Futures
*/
private ThreadPoolExecutor cancellator = new ThreadPoolExecutor(0,1,1000,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
/**
* reference to the JMX mbean
*/
protected org.apache.tomcat.jdbc.pool.jmx.ConnectionPool jmxPool = null;
/**
* counter to track how many threads are waiting for a connection
*/
private AtomicInteger waitcount = new AtomicInteger(0);
private AtomicLong poolVersion = new AtomicLong(Long.MIN_VALUE);
//===============================================================================
// PUBLIC METHODS
//===============================================================================
/**
* Instantiate a connection pool. This will create connections if initialSize is larger than 0.
* The {@link PoolProperties} should not be reused for another connection pool.
* @param prop PoolProperties - all the properties for this connection pool
* @throws SQLException
*/
public ConnectionPool(PoolConfiguration prop) throws SQLException {
//setup quick access variables and pools
init(prop);
}
/**
* Retrieves a Connection future. If a connection is not available, one can block using future.get()
* until a connection has become available.
* If a connection is not retrieved, the Future must be cancelled in order for the connection to be returned
* to the pool.
* @return a Future containing a reference to the connection or the future connection
* @throws SQLException
*/
public Future<Connection> getConnectionAsync() throws SQLException {
try {
PooledConnection pc = borrowConnection(0, null, null);
if (pc!=null) {
return new ConnectionFuture(pc);
}
}catch (SQLException x) {
if (x.getMessage().indexOf("NoWait")<0) {
throw x;
}
}
//we can only retrieve a future if the underlying queue supports it.
if (idle instanceof FairBlockingQueue<?>) {
Future<PooledConnection> pcf = ((FairBlockingQueue<PooledConnection>)idle).pollAsync();
return new ConnectionFuture(pcf);
} else if (idle instanceof MultiLockFairBlockingQueue<?>) {
Future<PooledConnection> pcf = ((MultiLockFairBlockingQueue<PooledConnection>)idle).pollAsync();
return new ConnectionFuture(pcf);
} else {
throw new SQLException("Connection pool is misconfigured, doesn't support async retrieval. Set the 'fair' property to 'true'");
}
}
/**
* Borrows a connection from the pool. If a connection is available (in the idle queue) or the pool has not reached
* {@link PoolProperties#maxActive maxActive} connections a connection is returned immediately.
* If no connection is available, the pool will attempt to fetch a connection for {@link PoolProperties#maxWait maxWait} milliseconds.
* @return Connection - a java.sql.Connection/javax.sql.PooledConnection reflection proxy, wrapping the underlying object.
* @throws SQLException - if the wait times out or a failure occurs creating a connection
*/
public Connection getConnection() throws SQLException {
//check out a connection
PooledConnection con = borrowConnection(-1,null,null);
return setupConnection(con);
}
/**
* Borrows a connection from the pool. If a connection is available (in the
* idle queue) or the pool has not reached {@link PoolProperties#maxActive
* maxActive} connections a connection is returned immediately. If no
* connection is available, the pool will attempt to fetch a connection for
* {@link PoolProperties#maxWait maxWait} milliseconds.
*
* @return Connection - a java.sql.Connection/javax.sql.PooledConnection
* reflection proxy, wrapping the underlying object.
* @throws SQLException
* - if the wait times out or a failure occurs creating a
* connection
*/
public Connection getConnection(String username, String password) throws SQLException {
// check out a connection
PooledConnection con = borrowConnection(-1, username, password);
return setupConnection(con);
}
/**
* Returns the name of this pool
* @return String - the name of the pool
*/
public String getName() {
return getPoolProperties().getPoolName();
}
/**
* Return the number of threads waiting for a connection
* @return number of threads waiting for a connection
*/
public int getWaitCount() {
return waitcount.get();
}
/**
* Returns the pool properties associated with this connection pool
* @return PoolProperties
*
*/
public PoolConfiguration getPoolProperties() {
return this.poolProperties;
}
/**
* Returns the total size of this pool, this includes both busy and idle connections
* @return int - number of established connections to the database
*/
public int getSize() {
return size.get();
}
/**
* Returns the number of connections that are in use
* @return int - number of established connections that are being used by the application
*/
public int getActive() {
return busy.size();
}
/**
* Returns the number of idle connections
* @return int - number of established connections not being used
*/
public int getIdle() {
return idle.size();
}
/**
* Returns true if {@link #close close} has been called, and the connection pool is unusable
* @return boolean
*/
public boolean isClosed() {
return this.closed;
}
//===============================================================================
// PROTECTED METHODS
//===============================================================================
/**
* configures a pooled connection as a proxy.
* This Proxy implements {@link java.sql.Connection} and {@link javax.sql.PooledConnection} interfaces.
* All calls on {@link java.sql.Connection} methods will be propagated down to the actual JDBC connection except for the
* {@link java.sql.Connection#close()} method.
* @param con a {@link PooledConnection} to wrap in a Proxy
* @return a {@link java.sql.Connection} object wrapping a pooled connection.
* @throws SQLException if an interceptor can't be configured, if the proxy can't be instantiated
*/
protected Connection setupConnection(PooledConnection con) throws SQLException {
//fetch previously cached interceptor proxy - one per connection
JdbcInterceptor handler = con.getHandler();
if (handler==null) {
//build the proxy handler
handler = new ProxyConnection(this,con,getPoolProperties().isUseEquals());
//set up the interceptor chain
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=proxies.length-1; i>=0; i--) {
try {
//create a new instance
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
//configure properties
interceptor.setProperties(proxies[i].getProperties());
//setup the chain
interceptor.setNext(handler);
//call reset
interceptor.reset(this, con);
//configure the last one to be held by the connection
handler = interceptor;
}catch(Exception x) {
SQLException sx = new SQLException("Unable to instantiate interceptor chain.");
sx.initCause(x);
throw sx;
}
}
//cache handler for the next iteration
con.setHandler(handler);
} else {
JdbcInterceptor next = handler;
//we have a cached handler, reset it
while (next!=null) {
next.reset(this, con);
next = next.getNext();
}
}
try {
getProxyConstructor(con.getXAConnection() != null);
//create the proxy
//TODO possible optimization, keep track if this connection was returned properly, and don't generate a new facade
Connection connection = null;
if (getPoolProperties().getUseDisposableConnectionFacade() ) {
connection = (Connection)proxyClassConstructor.newInstance(new Object[] { new DisposableConnectionFacade(handler) });
} else {
connection = (Connection)proxyClassConstructor.newInstance(new Object[] {handler});
}
//return the connection
return connection;
}catch (Exception x) {
SQLException s = new SQLException();
s.initCause(x);
throw s;
}
}
/**
* Creates and caches a {@link java.lang.reflect.Constructor} used to instantiate the proxy object.
* We cache this, since the creation of a constructor is fairly slow.
* @return constructor used to instantiate the wrapper object
* @throws NoSuchMethodException
*/
public Constructor<?> getProxyConstructor(boolean xa) throws NoSuchMethodException {
//cache the constructor
if (proxyClassConstructor == null ) {
Class<?> proxyClass = xa ?
Proxy.getProxyClass(ConnectionPool.class.getClassLoader(), new Class[] {java.sql.Connection.class,javax.sql.PooledConnection.class, javax.sql.XAConnection.class}) :
Proxy.getProxyClass(ConnectionPool.class.getClassLoader(), new Class[] {java.sql.Connection.class,javax.sql.PooledConnection.class});
proxyClassConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
}
return proxyClassConstructor;
}
/**
* Closes the pool and all disconnects all idle connections
* Active connections will be closed upon the {@link java.sql.Connection#close close} method is called
* on the underlying connection instead of being returned to the pool
* @param force - true to even close the active connections
*/
protected void close(boolean force) {
//are we already closed
if (this.closed) return;
//prevent other threads from entering
this.closed = true;
//stop background thread
if (poolCleaner!=null) {
poolCleaner.stopRunning();
}
/* release all idle connections */
BlockingQueue<PooledConnection> pool = (idle.size()>0)?idle:(force?busy:idle);
while (pool.size()>0) {
try {
//retrieve the next connection
PooledConnection con = pool.poll(1000, TimeUnit.MILLISECONDS);
//close it and retrieve the next one, if one is available
while (con != null) {
//close the connection
if (pool==idle)
release(con);
else
abandon(con);
if (pool.size()>0) {
con = pool.poll(1000, TimeUnit.MILLISECONDS);
} else {
break;
}
} //while
} catch (InterruptedException ex) {
if (getPoolProperties().getPropagateInterruptState()) {
Thread.currentThread().interrupt();
}
}
if (pool.size()==0 && force && pool!=busy) pool = busy;
}
if (this.getPoolProperties().isJmxEnabled()) this.jmxPool = null;
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=0; i<proxies.length; i++) {
try {
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
interceptor.setProperties(proxies[i].getProperties());
interceptor.poolClosed(this);
}catch (Exception x) {
log.debug("Unable to inform interceptor of pool closure.",x);
}
}
} //closePool
/**
* Initialize the connection pool - called from the constructor
* @param properties PoolProperties - properties used to initialize the pool with
* @throws SQLException if initialization fails
*/
protected void init(PoolConfiguration properties) throws SQLException {
poolProperties = properties;
//make sure the pool is properly configured
if (properties.getMaxActive()<1) {
log.warn("maxActive is smaller than 1, setting maxActive to: "+PoolProperties.DEFAULT_MAX_ACTIVE);
properties.setMaxActive(PoolProperties.DEFAULT_MAX_ACTIVE);
}
if (properties.getMaxActive()<properties.getInitialSize()) {
log.warn("initialSize is larger than maxActive, setting initialSize to: "+properties.getMaxActive());
properties.setInitialSize(properties.getMaxActive());
}
if (properties.getMinIdle()>properties.getMaxActive()) {
log.warn("minIdle is larger than maxActive, setting minIdle to: "+properties.getMaxActive());
properties.setMinIdle(properties.getMaxActive());
}
if (properties.getMaxIdle()>properties.getMaxActive()) {
log.warn("maxIdle is larger than maxActive, setting maxIdle to: "+properties.getMaxActive());
properties.setMaxIdle(properties.getMaxActive());
}
if (properties.getMaxIdle()<properties.getMinIdle()) {
log.warn("maxIdle is smaller than minIdle, setting maxIdle to: "+properties.getMinIdle());
properties.setMaxIdle(properties.getMinIdle());
}
//make space for 10 extra in case we flow over a bit
busy = new ArrayBlockingQueue<>(properties.getMaxActive(),false);
//busy = new FairBlockingQueue<PooledConnection>();
//make space for 10 extra in case we flow over a bit
if (properties.isFairQueue()) {
idle = new FairBlockingQueue<>();
//idle = new MultiLockFairBlockingQueue<PooledConnection>();
//idle = new LinkedTransferQueue<PooledConnection>();
//idle = new ArrayBlockingQueue<PooledConnection>(properties.getMaxActive(),false);
} else {
idle = new ArrayBlockingQueue<>(properties.getMaxActive(),properties.isFairQueue());
}
initializePoolCleaner(properties);
//create JMX MBean
if (this.getPoolProperties().isJmxEnabled()) createMBean();
//Parse and create an initial set of interceptors. Letting them know the pool has started.
//These interceptors will not get any connection.
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=0; i<proxies.length; i++) {
try {
if (log.isDebugEnabled()) {
log.debug("Creating interceptor instance of class:"+proxies[i].getInterceptorClass());
}
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
interceptor.setProperties(proxies[i].getProperties());
interceptor.poolStarted(this);
}catch (Exception x) {
log.error("Unable to inform interceptor of pool start.",x);
if (jmxPool!=null) jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_INIT, getStackTrace(x));
close(true);
SQLException ex = new SQLException();
ex.initCause(x);
throw ex;
}
}
//initialize the pool with its initial set of members
PooledConnection[] initialPool = new PooledConnection[poolProperties.getInitialSize()];
try {
for (int i = 0; i < initialPool.length; i++) {
initialPool[i] = this.borrowConnection(0, null, null); //don't wait, should be no contention
} //for
} catch (SQLException x) {
if (jmxPool!=null) jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_INIT, getStackTrace(x));
close(true);
throw x;
} finally {
//return the members as idle to the pool
for (int i = 0; i < initialPool.length; i++) {
if (initialPool[i] != null) {
try {this.returnConnection(initialPool[i]);}catch(Exception x){/*NOOP*/}
} //end if
} //for
} //catch
closed = false;
}
public void initializePoolCleaner(PoolConfiguration properties) {
//if the evictor thread is supposed to run, start it now
if (properties.isPoolSweeperEnabled()) {
poolCleaner = new PoolCleaner(this, properties.getTimeBetweenEvictionRunsMillis());
poolCleaner.start();
} //end if
}
//===============================================================================
// CONNECTION POOLING IMPL LOGIC
//===============================================================================
/**
* thread safe way to abandon a connection
* signals a connection to be abandoned.
* this will disconnect the connection, and log the stack trace if logAbanded=true
* @param con PooledConnection
*/
protected void abandon(PooledConnection con) {
if (con == null)
return;
try {
con.lock();
String trace = con.getStackTrace();
if (getPoolProperties().isLogAbandoned()) {
log.warn("Connection has been abandoned " + con + ":" + trace);
}
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_ABANDON, trace);
}
//release the connection
release(con);
} finally {
con.unlock();
}
}
/**
* thread safe way to abandon a connection
* signals a connection to be abandoned.
* this will disconnect the connection, and log the stack trace if logAbanded=true
* @param con PooledConnection
*/
protected void suspect(PooledConnection con) {
if (con == null)
return;
if (con.isSuspect())
return;
try {
con.lock();
String trace = con.getStackTrace();
if (getPoolProperties().isLogAbandoned()) {
log.warn("Connection has been marked suspect, possibly abandoned " + con + "["+(System.currentTimeMillis()-con.getTimestamp())+" ms.]:" + trace);
}
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.SUSPECT_ABANDONED_NOTIFICATION, trace);
}
con.setSuspect(true);
} finally {
con.unlock();
}
}
/**
* thread safe way to release a connection
* @param con PooledConnection
*/
protected void release(PooledConnection con) {
if (con == null)
return;
try {
con.lock();
if (con.release()) {
//counter only decremented once
size.addAndGet(-1);
con.setHandler(null);
}
} finally {
con.unlock();
}
// we've asynchronously reduced the number of connections
// we could have threads stuck in idle.poll(timeout) that will never be
// notified
if (waitcount.get() > 0) {
idle.offer(create(true));
}
}
/**
* Thread safe way to retrieve a connection from the pool
* @param wait - time to wait, overrides the maxWait from the properties,
* set to -1 if you wish to use maxWait, 0 if you wish no wait time.
* @return PooledConnection
* @throws SQLException
*/
private PooledConnection borrowConnection(int wait, String username, String password) throws SQLException {
if (isClosed()) {
throw new SQLException("Connection pool closed.");
} //end if
//get the current time stamp
long now = System.currentTimeMillis();
//see if there is one available immediately
PooledConnection con = idle.poll();
while (true) {
if (con!=null) {
//configure the connection and return it
PooledConnection result = borrowConnection(now, con, username, password);
//null should never be returned, but was in a previous impl.
if (result!=null) return result;
}
//if we get here, see if we need to create one
//this is not 100% accurate since it doesn't use a shared
//atomic variable - a connection can become idle while we are creating
//a new connection
if (size.get() < getPoolProperties().getMaxActive()) {
//atomic duplicate check
if (size.addAndGet(1) > getPoolProperties().getMaxActive()) {
//if we got here, two threads passed through the first if
size.decrementAndGet();
} else {
//create a connection, we're below the limit
return createConnection(now, con, username, password);
}
} //end if
//calculate wait time for this iteration
long maxWait = wait;
//if the passed in wait time is -1, means we should use the pool property value
if (wait==-1) {
maxWait = (getPoolProperties().getMaxWait()<=0)?Long.MAX_VALUE:getPoolProperties().getMaxWait();
}
long timetowait = Math.max(0, maxWait - (System.currentTimeMillis() - now));
waitcount.incrementAndGet();
try {
//retrieve an existing connection
con = idle.poll(timetowait, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
if (getPoolProperties().getPropagateInterruptState()) {
Thread.currentThread().interrupt();
}
SQLException sx = new SQLException("Pool wait interrupted.");
sx.initCause(ex);
throw sx;
} finally {
waitcount.decrementAndGet();
}
if (maxWait==0 && con == null) { //no wait, return one if we have one
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.POOL_EMPTY, "Pool empty - no wait.");
}
throw new PoolExhaustedException("[" + Thread.currentThread().getName()+"] " +
"NoWait: Pool empty. Unable to fetch a connection, none available["+busy.size()+" in use].");
}
//we didn't get a connection, lets see if we timed out
if (con == null) {
if ((System.currentTimeMillis() - now) >= maxWait) {
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.POOL_EMPTY, "Pool empty - timeout.");
}
throw new PoolExhaustedException("[" + Thread.currentThread().getName()+"] " +
"Timeout: Pool empty. Unable to fetch a connection in " + (maxWait / 1000) +
" seconds, none available[size:"+size.get() +"; busy:"+busy.size()+"; idle:"+idle.size()+"; lastwait:"+timetowait+"].");
} else {
//no timeout, lets try again
continue;
}
}
} //while
}
/**
* Creates a JDBC connection and tries to connect to the database.
* @param now timestamp of when this was called
* @param notUsed Argument not used
* @return a PooledConnection that has been connected
* @throws SQLException
*/
protected PooledConnection createConnection(long now, PooledConnection notUsed, String username, String password) throws SQLException {
//no connections where available we'll create one
PooledConnection con = create(false);
if (username!=null) con.getAttributes().put(PooledConnection.PROP_USER, username);
if (password!=null) con.getAttributes().put(PooledConnection.PROP_PASSWORD, password);
boolean error = false;
try {
//connect and validate the connection
con.lock();
con.connect();
if (con.validate(PooledConnection.VALIDATE_INIT)) {
//no need to lock a new one, its not contented
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
} else {
//validation failed, make sure we disconnect
//and clean up
error =true;
} //end if
} catch (Exception e) {
error = true;
if (log.isDebugEnabled())
log.debug("Unable to create a new JDBC connection.", e);
if (e instanceof SQLException) {
throw (SQLException)e;
} else {
SQLException ex = new SQLException(e.getMessage());
ex.initCause(e);
throw ex;
}
} finally {
// con can never be null here
if (error ) {
release(con);
}
con.unlock();
}//catch
return null;
}
/**
* Validates and configures a previously idle connection
* @param now - timestamp
* @param con - the connection to validate and configure
* @return con
* @throws SQLException if a validation error happens
*/
protected PooledConnection borrowConnection(long now, PooledConnection con, String username, String password) throws SQLException {
//we have a connection, lets set it up
//flag to see if we need to nullify
boolean setToNull = false;
try {
con.lock();
boolean usercheck = con.checkUser(username, password);
if (con.isReleased()) {
return null;
}
if (!con.isDiscarded() && !con.isInitialized()) {
//attempt to connect
try {
con.connect();
} catch (Exception x) {
release(con);
setToNull = true;
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
}
if (usercheck) {
if ((!con.isDiscarded()) && con.validate(PooledConnection.VALIDATE_BORROW)) {
//set the timestamp
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
//set the stack trace for this pool
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
}
}
//if we reached here, that means the connection
//is either has another principal, is discarded or validation failed.
//we will make one more attempt
//in order to guarantee that the thread that just acquired
//the connection shouldn't have to poll again.
try {
con.reconnect();
if (con.validate(PooledConnection.VALIDATE_INIT)) {
//set the timestamp
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
//set the stack trace for this pool
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
} else {
//validation failed.
release(con);
setToNull = true;
throw new SQLException("Failed to validate a newly established connection.");
}
} catch (Exception x) {
release(con);
setToNull = true;
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
} finally {
con.unlock();
if (setToNull) {
con = null;
}
}
}
/**
* Terminate the current transaction for the given connection.
* @param con
* @return <code>true</code> if the connection TX termination succeeded
* otherwise <code>false</code>
*/
protected boolean terminateTransaction(PooledConnection con) {
try {
if (Boolean.FALSE.equals(con.getPoolProperties().getDefaultAutoCommit())) {
if (this.getPoolProperties().getRollbackOnReturn()) {
boolean autocommit = con.getConnection().getAutoCommit();
if (!autocommit) con.getConnection().rollback();
} else if (this.getPoolProperties().getCommitOnReturn()) {
boolean autocommit = con.getConnection().getAutoCommit();
if (!autocommit) con.getConnection().commit();
}
}
return true;
} catch (SQLException x) {
log.warn("Unable to terminate transaction, connection will be closed.",x);
return false;
}
}
/**
* Determines if a connection should be closed upon return to the pool.
* @param con - the connection
* @param action - the validation action that should be performed
* @return true if the connection should be closed
*/
protected boolean shouldClose(PooledConnection con, int action) {
if (con.getConnectionVersion() < getPoolVersion()) return true;
if (con.isDiscarded()) return true;
if (isClosed()) return true;
if (!con.validate(action)) return true;
if (!terminateTransaction(con)) return true;
if (getPoolProperties().getMaxAge()>0 ) {
return (System.currentTimeMillis()-con.getLastConnected()) > getPoolProperties().getMaxAge();
} else {
return false;
}
}
/**
* Returns a connection to the pool
* If the pool is closed, the connection will be released
* If the connection is not part of the busy queue, it will be released.
* If {@link PoolProperties#testOnReturn} is set to true it will be validated
* @param con PooledConnection to be returned to the pool
*/
protected void returnConnection(PooledConnection con) {
if (isClosed()) {
//if the connection pool is closed
//close the connection instead of returning it
release(con);
return;
} //end if
if (con != null) {
try {
con.lock();
if (busy.remove(con)) {
if (!shouldClose(con,PooledConnection.VALIDATE_RETURN)) {
con.setStackTrace(null);
con.setTimestamp(System.currentTimeMillis());
if (((idle.size()>=poolProperties.getMaxIdle()) && !poolProperties.isPoolSweeperEnabled()) || (!idle.offer(con))) {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool, idle["+idle.size()+"]>=maxIdle["+poolProperties.getMaxIdle()+"] idle.offer failed.");
}
release(con);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool.");
}
release(con);
} //end if
} else {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool, busy.remove failed.");
}
release(con);
}
} finally {
con.unlock();
}
} //end if
} //checkIn
/**
* Determines if a connection should be abandoned based on
* {@link PoolProperties#abandonWhenPercentageFull} setting.
* @return true if the connection should be abandoned
*/
protected boolean shouldAbandon() {
if (poolProperties.getAbandonWhenPercentageFull()==0) return true;
float used = busy.size();
float max = poolProperties.getMaxActive();
float perc = poolProperties.getAbandonWhenPercentageFull();
return (used/max*100f)>=perc;
}
/**
* Iterates through all the busy connections and checks for connections that have timed out
*/
public void checkAbandoned() {
try {
if (busy.size()==0) return;
Iterator<PooledConnection> locked = busy.iterator();
int sto = getPoolProperties().getSuspectTimeout();
while (locked.hasNext()) {
PooledConnection con = locked.next();
boolean setToNull = false;
try {
con.lock();
//the con has been returned to the pool
//ignore it
if (idle.contains(con))
continue;
long time = con.getTimestamp();
long now = System.currentTimeMillis();
if (shouldAbandon() && (now - time) > con.getAbandonTimeout()) {
busy.remove(con);
abandon(con);
setToNull = true;
} else if (sto > 0 && (now - time) > (sto*1000)) {
suspect(con);
} else {
//do nothing
} //end if
} finally {
con.unlock();
if (setToNull)
con = null;
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("checkAbandoned failed." ,e);
} catch (Exception e) {
log.warn("checkAbandoned failed, it will be retried.",e);
}
}
/**
* Iterates through the idle connections and resizes the idle pool based on parameters
* {@link PoolProperties#maxIdle}, {@link PoolProperties#minIdle}, {@link PoolProperties#minEvictableIdleTimeMillis}
*/
public void checkIdle() {
checkIdle(false);
}
public void checkIdle(boolean ignoreMinSize) {
try {
if (idle.size()==0) return;
long now = System.currentTimeMillis();
Iterator<PooledConnection> unlocked = idle.iterator();
while ( (ignoreMinSize || (idle.size()>=getPoolProperties().getMinIdle())) && unlocked.hasNext()) {
PooledConnection con = unlocked.next();
boolean setToNull = false;
try {
con.lock();
//the con been taken out, we can't clean it up
if (busy.contains(con))
continue;
long time = con.getTimestamp();
if (shouldReleaseIdle(now, con, time)) {
release(con);
idle.remove(con);
setToNull = true;
} else {
//do nothing
} //end if
} finally {
con.unlock();
if (setToNull)
con = null;
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("checkIdle failed." ,e);
} catch (Exception e) {
log.warn("checkIdle failed, it will be retried.",e);
}
}
protected boolean shouldReleaseIdle(long now, PooledConnection con, long time) {
if (con.getConnectionVersion() < getPoolVersion()) return true;
else return (con.getReleaseTime()>0) && ((now - time) > con.getReleaseTime()) && (getSize()>getPoolProperties().getMinIdle());
}
/**
* Forces a validation of all idle connections if {@link PoolProperties#testWhileIdle} is set.
*/
public void testAllIdle() {
try {
if (idle.size()==0) return;
Iterator<PooledConnection> unlocked = idle.iterator();
while (unlocked.hasNext()) {
PooledConnection con = unlocked.next();
try {
con.lock();
//the con been taken out, we can't clean it up
if (busy.contains(con))
continue;
if (!con.validate(PooledConnection.VALIDATE_IDLE)) {
idle.remove(con);
release(con);
}
} finally {
con.unlock();
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("testAllIdle failed." ,e);
} catch (Exception e) {
log.warn("testAllIdle failed, it will be retried.",e);
}
}
/**
* Creates a stack trace representing the existing thread's current state.
* @return a string object representing the current state.
* TODO investigate if we simply should store {@link java.lang.Thread#getStackTrace()} elements
*/
protected static String getThreadDump() {
Exception x = new Exception();
x.fillInStackTrace();
return getStackTrace(x);
}
/**
* Convert an exception into a String
* @param x - the throwable
* @return a string representing the stack trace
*/
public static String getStackTrace(Throwable x) {
if (x == null) {
return null;
} else {
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.PrintStream writer = new java.io.PrintStream(bout);
x.printStackTrace(writer);
String result = bout.toString();
return (x.getMessage()!=null && x.getMessage().length()>0)? x.getMessage()+";"+result:result;
} //end if
}
/**
* Create a new pooled connection object. Not connected nor validated.
* @return a pooled connection object
*/
protected PooledConnection create(boolean incrementCounter) {
if (incrementCounter) size.incrementAndGet();
PooledConnection con = new PooledConnection(getPoolProperties(), this);
return con;
}
/**
* Purges all connections in the pool.
* For connections currently in use, these connections will be
* purged when returned on the pool. This call also
* purges connections that are idle and in the pool
* To only purge used/active connections see {@link #purgeOnReturn()}
*/
public void purge() {
purgeOnReturn();
checkIdle(true);
}
/**
* Purges connections when they are returned from the pool.
* This call does not purge idle connections until they are used.
* To purge idle connections see {@link #purge()}
*/
public void purgeOnReturn() {
poolVersion.incrementAndGet();
}
/**
* Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded
* @param con
*/
protected void finalize(PooledConnection con) {
JdbcInterceptor handler = con.getHandler();
while (handler!=null) {
handler.reset(null, null);
handler=handler.getNext();
}
}
/**
* Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded
* @param con
*/
protected void disconnectEvent(PooledConnection con, boolean finalizing) {
JdbcInterceptor handler = con.getHandler();
while (handler!=null) {
handler.disconnected(this, con, finalizing);
handler=handler.getNext();
}
}
/**
* Return the object that is potentially registered in JMX for notifications
* @return the object implementing the {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} interface
*/
public org.apache.tomcat.jdbc.pool.jmx.ConnectionPool getJmxPool() {
return jmxPool;
}
/**
* Create MBean object that can be registered.
*/
protected void createMBean() {
try {
jmxPool = new org.apache.tomcat.jdbc.pool.jmx.ConnectionPool(this);
} catch (Exception x) {
log.warn("Unable to start JMX integration for connection pool. Instance["+getName()+"] can't be monitored.",x);
}
}
/**
* Tread safe wrapper around a future for the regular queue
* This one retrieves the pooled connection object
* and performs the initialization according to
* interceptors and validation rules.
* This class is thread safe and is cancellable
* @author fhanik
*
*/
protected class ConnectionFuture implements Future<Connection>, Runnable {
Future<PooledConnection> pcFuture = null;
AtomicBoolean configured = new AtomicBoolean(false);
CountDownLatch latch = new CountDownLatch(1);
volatile Connection result = null;
SQLException cause = null;
AtomicBoolean cancelled = new AtomicBoolean(false);
volatile PooledConnection pc = null;
public ConnectionFuture(Future<PooledConnection> pcf) {
this.pcFuture = pcf;
}
public ConnectionFuture(PooledConnection pc) throws SQLException {
this.pc = pc;
result = ConnectionPool.this.setupConnection(pc);
configured.set(true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (pc!=null) {
return false;
} else if ((!cancelled.get()) && cancelled.compareAndSet(false, true)) {
//cancel by retrieving the connection and returning it to the pool
ConnectionPool.this.cancellator.execute(this);
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Connection get() throws InterruptedException, ExecutionException {
try {
return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}catch (TimeoutException x) {
throw new ExecutionException(x);
}
}
/**
* {@inheritDoc}
*/
@Override
public Connection get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
PooledConnection pc = this.pc!=null?this.pc:pcFuture.get(timeout,unit);
if (pc!=null) {
if (result!=null) return result;
if (configured.compareAndSet(false, true)) {
try {
pc = borrowConnection(System.currentTimeMillis(),pc, null, null);
result = ConnectionPool.this.setupConnection(pc);
} catch (SQLException x) {
cause = x;
} finally {
latch.countDown();
}
} else {
//if we reach here, another thread is configuring the actual connection
latch.await(timeout,unit); //this shouldn't block for long
}
if (result==null) throw new ExecutionException(cause);
return result;
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCancelled() {
return pc==null && (pcFuture.isCancelled() || cancelled.get());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDone() {
return pc!=null || pcFuture.isDone();
}
/**
* run method to be executed when cancelled by an executor
*/
@Override
public void run() {
try {
Connection con = get(); //complete this future
con.close(); //return to the pool
}catch (ExecutionException ex) {
//we can ignore this
}catch (Exception x) {
ConnectionPool.log.error("Unable to cancel ConnectionFuture.",x);
}
}
}
private static volatile Timer poolCleanTimer = null;
private static HashSet<PoolCleaner> cleaners = new HashSet<>();
private static synchronized void registerCleaner(PoolCleaner cleaner) {
unregisterCleaner(cleaner);
cleaners.add(cleaner);
if (poolCleanTimer == null) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(ConnectionPool.class.getClassLoader());
poolCleanTimer = new Timer("PoolCleaner["+ System.identityHashCode(ConnectionPool.class.getClassLoader()) + ":"+
System.currentTimeMillis() + "]", true);
}finally {
Thread.currentThread().setContextClassLoader(loader);
}
}
poolCleanTimer.scheduleAtFixedRate(cleaner, cleaner.sleepTime,cleaner.sleepTime);
}
private static synchronized void unregisterCleaner(PoolCleaner cleaner) {
boolean removed = cleaners.remove(cleaner);
if (removed) {
cleaner.cancel();
if (poolCleanTimer != null) {
poolCleanTimer.purge();
if (cleaners.size() == 0) {
poolCleanTimer.cancel();
poolCleanTimer = null;
}
}
}
}
public static Set<TimerTask> getPoolCleaners() {
return Collections.<TimerTask>unmodifiableSet(cleaners);
}
public long getPoolVersion() {
return poolVersion.get();
}
public static Timer getPoolTimer() {
return poolCleanTimer;
}
protected static class PoolCleaner extends TimerTask {
protected WeakReference<ConnectionPool> pool;
protected long sleepTime;
protected volatile long lastRun = 0;
PoolCleaner(ConnectionPool pool, long sleepTime) {
this.pool = new WeakReference<>(pool);
this.sleepTime = sleepTime;
if (sleepTime <= 0) {
log.warn("Database connection pool evicter thread interval is set to 0, defaulting to 30 seconds");
this.sleepTime = 1000 * 30;
} else if (sleepTime < 1000) {
log.warn("Database connection pool evicter thread interval is set to lower than 1 second.");
}
}
@Override
public void run() {
ConnectionPool pool = this.pool.get();
if (pool == null) {
stopRunning();
} else if (!pool.isClosed() &&
(System.currentTimeMillis() - lastRun) > sleepTime) {
lastRun = System.currentTimeMillis();
try {
if (pool.getPoolProperties().isRemoveAbandoned())
pool.checkAbandoned();
if (pool.getPoolProperties().getMinIdle() < pool.idle
.size())
pool.checkIdle();
if (pool.getPoolProperties().isTestWhileIdle())
pool.testAllIdle();
} catch (Exception x) {
log.error("", x);
}
}
}
public void start() {
registerCleaner(this);
}
public void stopRunning() {
unregisterCleaner(this);
}
}
}
|
55,343
|
Bug 55343 Add flag to ignore exceptions while creating initial pool
|
I want my initial pool to be of some size i.e. not empty AND start even if it fails to create all or some of connections. If pool fails to create initial connections for some reason it just throws exceptions. To workaround that I have to set initial pool size to 0. It can be handy to add a flag to ignore (just log them) exceptions that occur while creating initial connections.
|
resolved fixed
|
4aa42d7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T08:56:24Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java
|
/*
* 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.jdbc.pool;
import java.sql.Connection;
import java.util.Hashtable;
import java.util.Properties;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* <p>JNDI object factory that creates an instance of
* <code>BasicDataSource</code> that has been configured based on the
* <code>RefAddr</code> values of the specified <code>Reference</code>,
* which must match the names and data types of the
* <code>BasicDataSource</code> bean properties.</p>
* <br/>
* Properties available for configuration:<br/>
* <a href="http://commons.apache.org/dbcp/configuration.html">Commons DBCP properties</a><br/>
*<ol>
* <li>initSQL - A query that gets executed once, right after the connection is established.</li>
* <li>testOnConnect - run validationQuery after connection has been established.</li>
* <li>validationInterval - avoid excess validation, only run validation at most at this frequency - time in milliseconds.</li>
* <li>jdbcInterceptors - a semicolon separated list of classnames extending {@link JdbcInterceptor} class.</li>
* <li>jmxEnabled - true of false, whether to register the pool with JMX.</li>
* <li>fairQueue - true of false, whether the pool should sacrifice a little bit of performance for true fairness.</li>
*</ol>
* @author Craig R. McClanahan
* @author Dirk Verbeeck
* @author Filip Hanik
*/
public class DataSourceFactory implements ObjectFactory {
private static final Log log = LogFactory.getLog(DataSourceFactory.class);
protected static final String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
protected static final String PROP_DEFAULTREADONLY = "defaultReadOnly";
protected static final String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
protected static final String PROP_DEFAULTCATALOG = "defaultCatalog";
protected static final String PROP_DRIVERCLASSNAME = "driverClassName";
protected static final String PROP_PASSWORD = "password";
protected static final String PROP_URL = "url";
protected static final String PROP_USERNAME = "username";
protected static final String PROP_MAXACTIVE = "maxActive";
protected static final String PROP_MAXIDLE = "maxIdle";
protected static final String PROP_MINIDLE = "minIdle";
protected static final String PROP_INITIALSIZE = "initialSize";
protected static final String PROP_MAXWAIT = "maxWait";
protected static final String PROP_MAXAGE = "maxAge";
protected static final String PROP_TESTONBORROW = "testOnBorrow";
protected static final String PROP_TESTONRETURN = "testOnReturn";
protected static final String PROP_TESTWHILEIDLE = "testWhileIdle";
protected static final String PROP_TESTONCONNECT = "testOnConnect";
protected static final String PROP_VALIDATIONQUERY = "validationQuery";
protected static final String PROP_VALIDATOR_CLASS_NAME = "validatorClassName";
protected static final String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
protected static final String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
protected static final String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
protected static final String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
protected static final String PROP_REMOVEABANDONED = "removeAbandoned";
protected static final String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
protected static final String PROP_LOGABANDONED = "logAbandoned";
protected static final String PROP_ABANDONWHENPERCENTAGEFULL = "abandonWhenPercentageFull";
protected static final String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
protected static final String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
protected static final String PROP_CONNECTIONPROPERTIES = "connectionProperties";
protected static final String PROP_INITSQL = "initSQL";
protected static final String PROP_INTERCEPTORS = "jdbcInterceptors";
protected static final String PROP_VALIDATIONINTERVAL = "validationInterval";
protected static final String PROP_JMX_ENABLED = "jmxEnabled";
protected static final String PROP_FAIR_QUEUE = "fairQueue";
protected static final String PROP_USE_EQUALS = "useEquals";
protected static final String PROP_USE_CON_LOCK = "useLock";
protected static final String PROP_DATASOURCE= "dataSource";
protected static final String PROP_DATASOURCE_JNDI = "dataSourceJNDI";
protected static final String PROP_SUSPECT_TIMEOUT = "suspectTimeout";
protected static final String PROP_ALTERNATE_USERNAME_ALLOWED = "alternateUsernameAllowed";
protected static final String PROP_COMMITONRETURN = "commitOnReturn";
protected static final String PROP_ROLLBACKONRETURN = "rollbackOnReturn";
protected static final String PROP_USEDISPOSABLECONNECTIONFACADE = "useDisposableConnectionFacade";
protected static final String PROP_LOGVALIDATIONERRORS = "logValidationErrors";
protected static final String PROP_PROPAGATEINTERRUPTSTATE = "propagateInterruptState";
public static final int UNKNOWN_TRANSACTIONISOLATION = -1;
public static final String OBJECT_NAME = "object_name";
protected static final String[] ALL_PROPERTIES = {
PROP_DEFAULTAUTOCOMMIT,
PROP_DEFAULTREADONLY,
PROP_DEFAULTTRANSACTIONISOLATION,
PROP_DEFAULTCATALOG,
PROP_DRIVERCLASSNAME,
PROP_MAXACTIVE,
PROP_MAXIDLE,
PROP_MINIDLE,
PROP_INITIALSIZE,
PROP_MAXWAIT,
PROP_TESTONBORROW,
PROP_TESTONRETURN,
PROP_TIMEBETWEENEVICTIONRUNSMILLIS,
PROP_NUMTESTSPEREVICTIONRUN,
PROP_MINEVICTABLEIDLETIMEMILLIS,
PROP_TESTWHILEIDLE,
PROP_TESTONCONNECT,
PROP_PASSWORD,
PROP_URL,
PROP_USERNAME,
PROP_VALIDATIONQUERY,
PROP_VALIDATOR_CLASS_NAME,
PROP_VALIDATIONINTERVAL,
PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED,
PROP_REMOVEABANDONED,
PROP_REMOVEABANDONEDTIMEOUT,
PROP_LOGABANDONED,
PROP_POOLPREPAREDSTATEMENTS,
PROP_MAXOPENPREPAREDSTATEMENTS,
PROP_CONNECTIONPROPERTIES,
PROP_INITSQL,
PROP_INTERCEPTORS,
PROP_JMX_ENABLED,
PROP_FAIR_QUEUE,
PROP_USE_EQUALS,
OBJECT_NAME,
PROP_ABANDONWHENPERCENTAGEFULL,
PROP_MAXAGE,
PROP_USE_CON_LOCK,
PROP_DATASOURCE,
PROP_DATASOURCE_JNDI,
PROP_SUSPECT_TIMEOUT,
PROP_ALTERNATE_USERNAME_ALLOWED,
PROP_COMMITONRETURN,
PROP_ROLLBACKONRETURN,
PROP_USEDISPOSABLECONNECTIONFACADE,
PROP_LOGVALIDATIONERRORS,
PROP_PROPAGATEINTERRUPTSTATE
};
// -------------------------------------------------- ObjectFactory Methods
/**
* <p>Create and return a new <code>BasicDataSource</code> instance. If no
* instance can be created, return <code>null</code> instead.</p>
*
* @param obj The possibly null object containing location or
* reference information that can be used in creating an object
* @param name The name of this object relative to <code>nameCtx</code>
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or <code>null</code> if <code>name</code>
* is relative to the default initial context
* @param environment The possibly null environment that is used in
* creating this object
*
* @exception Exception if an exception occurs creating the instance
*/
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment) throws Exception {
// We only know how to deal with <code>javax.naming.Reference</code>s
// that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference)) {
return null;
}
Reference ref = (Reference) obj;
boolean XA = false;
boolean ok = false;
if ("javax.sql.DataSource".equals(ref.getClassName())) {
ok = true;
}
if ("javax.sql.XADataSource".equals(ref.getClassName())) {
ok = true;
XA = true;
}
if (org.apache.tomcat.jdbc.pool.DataSource.class.getName().equals(ref.getClassName())) {
ok = true;
}
if (!ok) {
log.warn(ref.getClassName()+" is not a valid class name/type for this JNDI factory.");
return null;
}
Properties properties = new Properties();
for (int i = 0; i < ALL_PROPERTIES.length; i++) {
String propertyName = ALL_PROPERTIES[i];
RefAddr ra = ref.get(propertyName);
if (ra != null) {
String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue);
}
}
return createDataSource(properties,nameCtx,XA);
}
public static PoolConfiguration parsePoolProperties(Properties properties) {
PoolConfiguration poolProperties = new PoolProperties();
String value = null;
value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
poolProperties.setDefaultAutoCommit(Boolean.valueOf(value));
}
value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
poolProperties.setDefaultReadOnly(Boolean.valueOf(value));
}
value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = UNKNOWN_TRANSACTIONISOLATION;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
} else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
} else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
} else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
} else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
} else {
try {
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation: " + value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = UNKNOWN_TRANSACTIONISOLATION;
}
}
poolProperties.setDefaultTransactionIsolation(level);
}
value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
poolProperties.setDefaultCatalog(value);
}
value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
poolProperties.setDriverClassName(value);
}
value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
poolProperties.setMaxActive(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
poolProperties.setMaxIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
poolProperties.setMinIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
poolProperties.setInitialSize(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
poolProperties.setMaxWait(Integer.parseInt(value));
}
value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
poolProperties.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
poolProperties.setTestOnReturn(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONCONNECT);
if (value != null) {
poolProperties.setTestOnConnect(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
poolProperties.setTimeBetweenEvictionRunsMillis(Integer.parseInt(value));
}
value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
poolProperties.setNumTestsPerEvictionRun(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
poolProperties.setMinEvictableIdleTimeMillis(Integer.parseInt(value));
}
value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
poolProperties.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
poolProperties.setPassword(value);
}
value = properties.getProperty(PROP_URL);
if (value != null) {
poolProperties.setUrl(value);
}
value = properties.getProperty(PROP_USERNAME);
if (value != null) {
poolProperties.setUsername(value);
}
value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
poolProperties.setValidationQuery(value);
}
value = properties.getProperty(PROP_VALIDATOR_CLASS_NAME);
if (value != null) {
poolProperties.setValidatorClassName(value);
}
value = properties.getProperty(PROP_VALIDATIONINTERVAL);
if (value != null) {
poolProperties.setValidationInterval(Long.parseLong(value));
}
value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
poolProperties.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONED);
if (value != null) {
poolProperties.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
if (value != null) {
poolProperties.setRemoveAbandonedTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_LOGABANDONED);
if (value != null) {
poolProperties.setLogAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
log.warn(PROP_POOLPREPAREDSTATEMENTS + " is not a valid setting, it will have no effect.");
}
value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
log.warn(PROP_MAXOPENPREPAREDSTATEMENTS + " is not a valid setting, it will have no effect.");
}
value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
poolProperties.setDbProperties(p);
} else {
poolProperties.setDbProperties(new Properties());
}
if (poolProperties.getUsername()!=null) {
poolProperties.getDbProperties().setProperty("user",poolProperties.getUsername());
}
if (poolProperties.getPassword()!=null) {
poolProperties.getDbProperties().setProperty("password",poolProperties.getPassword());
}
value = properties.getProperty(PROP_INITSQL);
if (value != null) {
poolProperties.setInitSQL(value);
}
value = properties.getProperty(PROP_INTERCEPTORS);
if (value != null) {
poolProperties.setJdbcInterceptors(value);
}
value = properties.getProperty(PROP_JMX_ENABLED);
if (value != null) {
poolProperties.setJmxEnabled(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_FAIR_QUEUE);
if (value != null) {
poolProperties.setFairQueue(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_USE_EQUALS);
if (value != null) {
poolProperties.setUseEquals(Boolean.parseBoolean(value));
}
value = properties.getProperty(OBJECT_NAME);
if (value != null) {
poolProperties.setName(ObjectName.quote(value));
}
value = properties.getProperty(PROP_ABANDONWHENPERCENTAGEFULL);
if (value != null) {
poolProperties.setAbandonWhenPercentageFull(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXAGE);
if (value != null) {
poolProperties.setMaxAge(Long.parseLong(value));
}
value = properties.getProperty(PROP_USE_CON_LOCK);
if (value != null) {
poolProperties.setUseLock(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_DATASOURCE);
if (value != null) {
//this should never happen
throw new IllegalArgumentException("Can't set dataSource property as a string, this must be a javax.sql.DataSource object.");
}
value = properties.getProperty(PROP_DATASOURCE_JNDI);
if (value != null) {
poolProperties.setDataSourceJNDI(value);
}
value = properties.getProperty(PROP_SUSPECT_TIMEOUT);
if (value != null) {
poolProperties.setSuspectTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_ALTERNATE_USERNAME_ALLOWED);
if (value != null) {
poolProperties.setAlternateUsernameAllowed(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_COMMITONRETURN);
if (value != null) {
poolProperties.setCommitOnReturn(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_ROLLBACKONRETURN);
if (value != null) {
poolProperties.setRollbackOnReturn(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_USEDISPOSABLECONNECTIONFACADE);
if (value != null) {
poolProperties.setUseDisposableConnectionFacade(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_LOGVALIDATIONERRORS);
if (value != null) {
poolProperties.setLogValidationErrors(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_PROPAGATEINTERRUPTSTATE);
if (value != null) {
poolProperties.setPropagateInterruptState(Boolean.parseBoolean(value));
}
return poolProperties;
}
/**
* Creates and configures a {@link DataSource} instance based on the
* given properties.
*
* @param properties the datasource configuration properties
* @throws Exception if an error occurs creating the data source
*/
public DataSource createDataSource(Properties properties) throws Exception {
return createDataSource(properties,null,false);
}
public DataSource createDataSource(Properties properties,Context context, boolean XA) throws Exception {
PoolConfiguration poolProperties = DataSourceFactory.parsePoolProperties(properties);
if (poolProperties.getDataSourceJNDI()!=null && poolProperties.getDataSource()==null) {
performJNDILookup(context, poolProperties);
}
org.apache.tomcat.jdbc.pool.DataSource dataSource = XA?
new org.apache.tomcat.jdbc.pool.XADataSource(poolProperties) :
new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
//initialise the pool itself
dataSource.createPool();
// Return the configured DataSource instance
return dataSource;
}
public void performJNDILookup(Context context, PoolConfiguration poolProperties) {
Object jndiDS = null;
try {
if (context!=null) {
jndiDS = context.lookup(poolProperties.getDataSourceJNDI());
} else {
log.warn("dataSourceJNDI property is configued, but local JNDI context is null.");
}
} catch (NamingException e) {
log.debug("The name \""+poolProperties.getDataSourceJNDI()+"\" can not be found in the local context.");
}
if (jndiDS==null) {
try {
context = new InitialContext();
jndiDS = context.lookup(poolProperties.getDataSourceJNDI());
} catch (NamingException e) {
log.warn("The name \""+poolProperties.getDataSourceJNDI()+"\" can not be found in the InitialContext.");
}
}
if (jndiDS!=null) {
poolProperties.setDataSource(jndiDS);
}
}
/**
* <p>Parse properties from the string. Format of the string must be [propertyName=property;]*<p>
* @param propText
* @return Properties
* @throws Exception
*/
protected static Properties getProperties(String propText) {
return PoolProperties.getProperties(propText,null);
}
}
|
55,343
|
Bug 55343 Add flag to ignore exceptions while creating initial pool
|
I want my initial pool to be of some size i.e. not empty AND start even if it fails to create all or some of connections. If pool fails to create initial connections for some reason it just throws exceptions. To workaround that I have to set initial pool size to 0. It can be handy to add a flag to ignore (just log them) exceptions that occur while creating initial connections.
|
resolved fixed
|
4aa42d7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T08:56:24Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java
|
/*
* 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.jdbc.pool;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.sql.XAConnection;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition;
/**
*
* The DataSource proxy lets us implements methods that don't exist in the current
* compiler JDK but might be methods that are part of a future JDK DataSource interface.
* <br/>
* It's a trick to work around compiler issues when implementing interfaces. For example,
* I could put in Java 6 methods of javax.sql.DataSource here, and compile it with JDK 1.5
* and still be able to run under Java 6 without getting NoSuchMethodException.
*
* @author Filip Hanik
* @version 1.0
*/
public class DataSourceProxy implements PoolConfiguration {
private static final Log log = LogFactory.getLog(DataSourceProxy.class);
protected volatile ConnectionPool pool = null;
protected volatile PoolConfiguration poolProperties = null;
public DataSourceProxy() {
this(new PoolProperties());
}
public DataSourceProxy(PoolConfiguration poolProperties) {
if (poolProperties == null) throw new NullPointerException("PoolConfiguration can not be null.");
this.poolProperties = poolProperties;
}
@SuppressWarnings("unused") // Has to match signature in DataSource
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// we are not a wrapper of anything
return false;
}
@SuppressWarnings("unused") // Has to match signature in DataSource
public <T> T unwrap(Class<T> iface) throws SQLException {
//we can't unwrap anything
return null;
}
/**
* {@link javax.sql.DataSource#getConnection()}
*/
public Connection getConnection(String username, String password) throws SQLException {
if (this.getPoolProperties().isAlternateUsernameAllowed()) {
if (pool == null)
return createPool().getConnection(username,password);
return pool.getConnection(username,password);
} else {
return getConnection();
}
}
public PoolConfiguration getPoolProperties() {
return poolProperties;
}
/**
* Sets up the connection pool, by creating a pooling driver.
* @return Driver
* @throws SQLException
*/
public ConnectionPool createPool() throws SQLException {
if (pool != null) {
return pool;
} else {
return pCreatePool();
}
}
/**
* Sets up the connection pool, by creating a pooling driver.
* @return Driver
* @throws SQLException
*/
private synchronized ConnectionPool pCreatePool() throws SQLException {
if (pool != null) {
return pool;
} else {
pool = new ConnectionPool(poolProperties);
return pool;
}
}
/**
* {@link javax.sql.DataSource#getConnection()}
*/
public Connection getConnection() throws SQLException {
if (pool == null)
return createPool().getConnection();
return pool.getConnection();
}
/**
* Invokes an sync operation to retrieve the connection.
* @return a Future containing a reference to the connection when it becomes available
* @throws SQLException
*/
public Future<Connection> getConnectionAsync() throws SQLException {
if (pool == null)
return createPool().getConnectionAsync();
return pool.getConnectionAsync();
}
/**
* {@link javax.sql.XADataSource#getXAConnection()}
*/
public XAConnection getXAConnection() throws SQLException {
Connection con = getConnection();
if (con instanceof XAConnection) {
return (XAConnection)con;
} else {
try {
con.close();
} catch (Exception ignore) {
// Ignore
}
throw new SQLException("Connection from pool does not implement javax.sql.XAConnection");
}
}
/**
* {@link javax.sql.XADataSource#getXAConnection(String, String)}
*/
public XAConnection getXAConnection(String username, String password) throws SQLException {
Connection con = getConnection(username, password);
if (con instanceof XAConnection) {
return (XAConnection)con;
} else {
try {
con.close();
} catch (Exception ignore) {
// Ignore
}
throw new SQLException("Connection from pool does not implement javax.sql.XAConnection");
}
}
/**
* {@link javax.sql.DataSource#getConnection()}
*/
public javax.sql.PooledConnection getPooledConnection() throws SQLException {
return (javax.sql.PooledConnection) getConnection();
}
/**
* {@link javax.sql.DataSource#getConnection()}
* @param username unused
* @param password unused
*/
public javax.sql.PooledConnection getPooledConnection(String username,
String password) throws SQLException {
return (javax.sql.PooledConnection) getConnection();
}
public ConnectionPool getPool() {
return pool;
}
public void close() {
close(false);
}
public void close(boolean all) {
try {
if (pool != null) {
final ConnectionPool p = pool;
pool = null;
if (p!=null) {
p.close(all);
}
}
}catch (Exception x) {
log.warn("Error duing connection pool closure.", x);
}
}
public int getPoolSize() {
final ConnectionPool p = pool;
if (p == null) return 0;
else return p.getSize();
}
@Override
public String toString() {
return super.toString()+"{"+getPoolProperties()+"}";
}
/*-----------------------------------------------------------------------*/
// PROPERTIES WHEN NOT USED WITH FACTORY
/*------------------------------------------------------------------------*/
/**
* {@inheritDoc}
*/
@Override
public String getPoolName() {
return pool.getName();
}
public void setPoolProperties(PoolConfiguration poolProperties) {
this.poolProperties = poolProperties;
}
/**
* {@inheritDoc}
*/
@Override
public void setDriverClassName(String driverClassName) {
this.poolProperties.setDriverClassName(driverClassName);
}
/**
* {@inheritDoc}
*/
@Override
public void setInitialSize(int initialSize) {
this.poolProperties.setInitialSize(initialSize);
}
/**
* {@inheritDoc}
*/
@Override
public void setInitSQL(String initSQL) {
this.poolProperties.setInitSQL(initSQL);
}
/**
* {@inheritDoc}
*/
@Override
public void setLogAbandoned(boolean logAbandoned) {
this.poolProperties.setLogAbandoned(logAbandoned);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxActive(int maxActive) {
this.poolProperties.setMaxActive(maxActive);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxIdle(int maxIdle) {
this.poolProperties.setMaxIdle(maxIdle);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxWait(int maxWait) {
this.poolProperties.setMaxWait(maxWait);
}
/**
* {@inheritDoc}
*/
@Override
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.poolProperties.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
}
/**
* {@inheritDoc}
*/
@Override
public void setMinIdle(int minIdle) {
this.poolProperties.setMinIdle(minIdle);
}
/**
* {@inheritDoc}
*/
@Override
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.poolProperties.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
}
/**
* {@inheritDoc}
*/
@Override
public void setPassword(String password) {
this.poolProperties.setPassword(password);
this.poolProperties.getDbProperties().setProperty("password",this.poolProperties.getPassword());
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandoned(boolean removeAbandoned) {
this.poolProperties.setRemoveAbandoned(removeAbandoned);
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
this.poolProperties.setRemoveAbandonedTimeout(removeAbandonedTimeout);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnBorrow(boolean testOnBorrow) {
this.poolProperties.setTestOnBorrow(testOnBorrow);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnConnect(boolean testOnConnect) {
this.poolProperties.setTestOnConnect(testOnConnect);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnReturn(boolean testOnReturn) {
this.poolProperties.setTestOnReturn(testOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestWhileIdle(boolean testWhileIdle) {
this.poolProperties.setTestWhileIdle(testWhileIdle);
}
/**
* {@inheritDoc}
*/
@Override
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.poolProperties.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
}
/**
* {@inheritDoc}
*/
@Override
public void setUrl(String url) {
this.poolProperties.setUrl(url);
}
/**
* {@inheritDoc}
*/
@Override
public void setUsername(String username) {
this.poolProperties.setUsername(username);
this.poolProperties.getDbProperties().setProperty("user",getPoolProperties().getUsername());
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationInterval(long validationInterval) {
this.poolProperties.setValidationInterval(validationInterval);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationQuery(String validationQuery) {
this.poolProperties.setValidationQuery(validationQuery);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidatorClassName(String className) {
this.poolProperties.setValidatorClassName(className);
}
/**
* {@inheritDoc}
*/
@Override
public void setJdbcInterceptors(String interceptors) {
this.getPoolProperties().setJdbcInterceptors(interceptors);
}
/**
* {@inheritDoc}
*/
@Override
public void setJmxEnabled(boolean enabled) {
this.getPoolProperties().setJmxEnabled(enabled);
}
/**
* {@inheritDoc}
*/
@Override
public void setFairQueue(boolean fairQueue) {
this.getPoolProperties().setFairQueue(fairQueue);
}
/**
* {@inheritDoc}
*/
@Override
public void setUseLock(boolean useLock) {
this.getPoolProperties().setUseLock(useLock);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultCatalog(String catalog) {
this.getPoolProperties().setDefaultCatalog(catalog);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultAutoCommit(Boolean autocommit) {
this.getPoolProperties().setDefaultAutoCommit(autocommit);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
this.getPoolProperties().setDefaultTransactionIsolation(defaultTransactionIsolation);
}
/**
* {@inheritDoc}
*/
@Override
public void setConnectionProperties(String properties) {
try {
java.util.Properties prop = DataSourceFactory
.getProperties(properties);
Iterator<?> i = prop.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
String value = prop.getProperty(key);
getPoolProperties().getDbProperties().setProperty(key, value);
}
} catch (Exception x) {
log.error("Unable to parse connection properties.", x);
throw new RuntimeException(x);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setUseEquals(boolean useEquals) {
this.getPoolProperties().setUseEquals(useEquals);
}
/**
* no-op
* {@link javax.sql.DataSource#getParentLogger}
*/
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
/**
* no-op
* {@link javax.sql.DataSource#getLogWriter}
*/
@SuppressWarnings("unused") // Has to match signature in DataSource
public PrintWriter getLogWriter() throws SQLException {
return null;
}
/**
* no-op
* {@link javax.sql.DataSource#setLogWriter(PrintWriter)}
*/
@SuppressWarnings("unused") // Has to match signature in DataSource
public void setLogWriter(PrintWriter out) throws SQLException {
// NOOP
}
/**
* no-op
* {@link javax.sql.DataSource#getLoginTimeout}
*/
public int getLoginTimeout() {
if (poolProperties == null) {
return 0;
} else {
return poolProperties.getMaxWait() / 1000;
}
}
/**
* {@link javax.sql.DataSource#setLoginTimeout(int)}
*/
public void setLoginTimeout(int i) {
if (poolProperties == null) {
return;
} else {
poolProperties.setMaxWait(1000 * i);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getSuspectTimeout() {
return getPoolProperties().getSuspectTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public void setSuspectTimeout(int seconds) {
getPoolProperties().setSuspectTimeout(seconds);
}
//===============================================================================
// Expose JMX attributes through Tomcat's dynamic reflection
//===============================================================================
/**
* If the pool has not been created, it will be created during this call.
* @return the number of established but idle connections
*/
public int getIdle() {
try {
return createPool().getIdle();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* {@link #getIdle()}
*/
public int getNumIdle() {
return getIdle();
}
/**
* Forces an abandon check on the connection pool.
* If connections that have been abandoned exists, they will be closed during this run
*/
public void checkAbandoned() {
try {
createPool().checkAbandoned();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* Forces a check for resizing of the idle connections
*/
public void checkIdle() {
try {
createPool().checkIdle();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* @return number of connections in use by the application
*/
public int getActive() {
try {
return createPool().getActive();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* @return number of connections in use by the application
* {@link DataSource#getActive()}
*/
public int getNumActive() {
return getActive();
}
/**
* @return number of threads waiting for a connection
*/
public int getWaitCount() {
try {
return createPool().getWaitCount();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* @return the current size of the pool
*/
public int getSize() {
try {
return createPool().getSize();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* Performs a validation on idle connections
*/
public void testIdle() {
try {
createPool().testAllIdle();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
//=========================================================
// PROPERTIES / CONFIGURATION
//=========================================================
/**
* {@inheritDoc}
*/
@Override
public String getConnectionProperties() {
return getPoolProperties().getConnectionProperties();
}
/**
* {@inheritDoc}
*/
@Override
public Properties getDbProperties() {
return getPoolProperties().getDbProperties();
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultCatalog() {
return getPoolProperties().getDefaultCatalog();
}
/**
* {@inheritDoc}
*/
@Override
public int getDefaultTransactionIsolation() {
return getPoolProperties().getDefaultTransactionIsolation();
}
/**
* {@inheritDoc}
*/
@Override
public String getDriverClassName() {
return getPoolProperties().getDriverClassName();
}
/**
* {@inheritDoc}
*/
@Override
public int getInitialSize() {
return getPoolProperties().getInitialSize();
}
/**
* {@inheritDoc}
*/
@Override
public String getInitSQL() {
return getPoolProperties().getInitSQL();
}
/**
* {@inheritDoc}
*/
@Override
public String getJdbcInterceptors() {
return getPoolProperties().getJdbcInterceptors();
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxActive() {
return getPoolProperties().getMaxActive();
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxIdle() {
return getPoolProperties().getMaxIdle();
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxWait() {
return getPoolProperties().getMaxWait();
}
/**
* {@inheritDoc}
*/
@Override
public int getMinEvictableIdleTimeMillis() {
return getPoolProperties().getMinEvictableIdleTimeMillis();
}
/**
* {@inheritDoc}
*/
@Override
public int getMinIdle() {
return getPoolProperties().getMinIdle();
}
/**
* {@inheritDoc}
*/
@Override
public long getMaxAge() {
return getPoolProperties().getMaxAge();
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return getPoolProperties().getName();
}
/**
* {@inheritDoc}
*/
@Override
public int getNumTestsPerEvictionRun() {
return getPoolProperties().getNumTestsPerEvictionRun();
}
/**
* @return DOES NOT RETURN THE PASSWORD, IT WOULD SHOW UP IN JMX
*/
@Override
public String getPassword() {
return "Password not available as DataSource/JMX operation.";
}
/**
* {@inheritDoc}
*/
@Override
public int getRemoveAbandonedTimeout() {
return getPoolProperties().getRemoveAbandonedTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public int getTimeBetweenEvictionRunsMillis() {
return getPoolProperties().getTimeBetweenEvictionRunsMillis();
}
/**
* {@inheritDoc}
*/
@Override
public String getUrl() {
return getPoolProperties().getUrl();
}
/**
* {@inheritDoc}
*/
@Override
public String getUsername() {
return getPoolProperties().getUsername();
}
/**
* {@inheritDoc}
*/
@Override
public long getValidationInterval() {
return getPoolProperties().getValidationInterval();
}
/**
* {@inheritDoc}
*/
@Override
public String getValidationQuery() {
return getPoolProperties().getValidationQuery();
}
/**
* {@inheritDoc}
*/
@Override
public String getValidatorClassName() {
return getPoolProperties().getValidatorClassName();
}
/**
* {@inheritDoc}
*/
@Override
public Validator getValidator() {
return getPoolProperties().getValidator();
}
/**
* {@inheritDoc}
*/
@Override
public void setValidator(Validator validator) {
getPoolProperties().setValidator(validator);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAccessToUnderlyingConnectionAllowed() {
return getPoolProperties().isAccessToUnderlyingConnectionAllowed();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultAutoCommit() {
return getPoolProperties().isDefaultAutoCommit();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultReadOnly() {
return getPoolProperties().isDefaultReadOnly();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLogAbandoned() {
return getPoolProperties().isLogAbandoned();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPoolSweeperEnabled() {
return getPoolProperties().isPoolSweeperEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRemoveAbandoned() {
return getPoolProperties().isRemoveAbandoned();
}
/**
* {@inheritDoc}
*/
@Override
public int getAbandonWhenPercentageFull() {
return getPoolProperties().getAbandonWhenPercentageFull();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnBorrow() {
return getPoolProperties().isTestOnBorrow();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnConnect() {
return getPoolProperties().isTestOnConnect();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnReturn() {
return getPoolProperties().isTestOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestWhileIdle() {
return getPoolProperties().isTestWhileIdle();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultAutoCommit() {
return getPoolProperties().getDefaultAutoCommit();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultReadOnly() {
return getPoolProperties().getDefaultReadOnly();
}
/**
* {@inheritDoc}
*/
@Override
public InterceptorDefinition[] getJdbcInterceptorsAsArray() {
return getPoolProperties().getJdbcInterceptorsAsArray();
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseLock() {
return getPoolProperties().getUseLock();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFairQueue() {
return getPoolProperties().isFairQueue();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isJmxEnabled() {
return getPoolProperties().isJmxEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUseEquals() {
return getPoolProperties().isUseEquals();
}
/**
* {@inheritDoc}
*/
@Override
public void setAbandonWhenPercentageFull(int percentage) {
getPoolProperties().setAbandonWhenPercentageFull(percentage);
}
/**
* {@inheritDoc}
*/
@Override
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) {
getPoolProperties().setAccessToUnderlyingConnectionAllowed(accessToUnderlyingConnectionAllowed);
}
/**
* {@inheritDoc}
*/
@Override
public void setDbProperties(Properties dbProperties) {
getPoolProperties().setDbProperties(dbProperties);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultReadOnly(Boolean defaultReadOnly) {
getPoolProperties().setDefaultReadOnly(defaultReadOnly);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxAge(long maxAge) {
getPoolProperties().setMaxAge(maxAge);
}
/**
* {@inheritDoc}
*/
@Override
public void setName(String name) {
getPoolProperties().setName(name);
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSource(Object ds) {
getPoolProperties().setDataSource(ds);
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataSource() {
return getPoolProperties().getDataSource();
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSourceJNDI(String jndiDS) {
getPoolProperties().setDataSourceJNDI(jndiDS);
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSourceJNDI() {
return getPoolProperties().getDataSourceJNDI();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlternateUsernameAllowed() {
return getPoolProperties().isAlternateUsernameAllowed();
}
/**
* {@inheritDoc}
*/
@Override
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) {
getPoolProperties().setAlternateUsernameAllowed(alternateUsernameAllowed);
}
/**
* {@inheritDoc}
*/
@Override
public void setCommitOnReturn(boolean commitOnReturn) {
getPoolProperties().setCommitOnReturn(commitOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCommitOnReturn() {
return getPoolProperties().getCommitOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setRollbackOnReturn(boolean rollbackOnReturn) {
getPoolProperties().setRollbackOnReturn(rollbackOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getRollbackOnReturn() {
return getPoolProperties().getRollbackOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) {
getPoolProperties().setUseDisposableConnectionFacade(useDisposableConnectionFacade);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseDisposableConnectionFacade() {
return getPoolProperties().getUseDisposableConnectionFacade();
}
/**
* {@inheritDoc}
*/
@Override
public void setLogValidationErrors(boolean logValidationErrors) {
getPoolProperties().setLogValidationErrors(logValidationErrors);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getLogValidationErrors() {
return getPoolProperties().getLogValidationErrors();
}
/**
* {@inheritDoc}
*/
@Override
public boolean getPropagateInterruptState() {
return getPoolProperties().getPropagateInterruptState();
}
/**
* {@inheritDoc}
*/
@Override
public void setPropagateInterruptState(boolean propagateInterruptState) {
getPoolProperties().setPropagateInterruptState(propagateInterruptState);
}
public void purge() {
try {
createPool().purge();
}catch (SQLException x) {
log.error("Unable to purge pool.",x);
}
}
public void purgeOnReturn() {
try {
createPool().purgeOnReturn();
}catch (SQLException x) {
log.error("Unable to purge pool.",x);
}
}
}
|
55,343
|
Bug 55343 Add flag to ignore exceptions while creating initial pool
|
I want my initial pool to be of some size i.e. not empty AND start even if it fails to create all or some of connections. If pool fails to create initial connections for some reason it just throws exceptions. To workaround that I have to set initial pool size to 0. It can be handy to add a flag to ignore (just log them) exceptions that occur while creating initial connections.
|
resolved fixed
|
4aa42d7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T08:56:24Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java
|
/*
* 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.jdbc.pool;
import java.util.Properties;
import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition;
/**
* A list of properties that are configurable for a connection pool.
* The {@link DataSource} object also implements this interface so that it can be easily configured through
* an IoC container without having to specify a secondary object with a setter method.
* @author fhanik
*
*/
public interface PoolConfiguration {
/**
* JMX prefix for interceptors that register themselves with JMX
*/
public static final String PKG_PREFIX = "org.apache.tomcat.jdbc.pool.interceptor.";
/**
* Connections that have been abandoned (timed out) wont get closed and reported up unless the number of connections in use are
* above the percentage defined by abandonWhenPercentageFull.
* The value should be between 0-100.
* The default value is 0, which implies that connections are eligible for
* closure as soon as removeAbandonedTimeout has been reached.
* @param percentage a value between 0 and 100 to indicate when connections that have been abandoned/timed out are considered abandoned
*/
public void setAbandonWhenPercentageFull(int percentage);
/**
* Connections that have been abandoned (timed out) wont get closed and reported up unless the number of connections in use are
* above the percentage defined by abandonWhenPercentageFull.
* The value should be between 0-100.
* The default value is 0, which implies that connections are eligible for
* closure as soon as removeAbandonedTimeout has been reached.
* @return percentage - a value between 0 and 100 to indicate when connections that have been abandoned/timed out are considered abandoned
*/
public int getAbandonWhenPercentageFull();
/**
* Returns true if a fair queue is being used by the connection pool
* @return true if a fair waiting queue is being used
*/
public boolean isFairQueue();
/**
* Set to true if you wish that calls to getConnection
* should be treated fairly in a true FIFO fashion.
* This uses the {@link FairBlockingQueue} implementation for the list of the idle connections.
* The default value is true.
* This flag is required when you want to use asynchronous connection retrieval.
* @param fairQueue
*/
public void setFairQueue(boolean fairQueue);
/**
* Property not used. Access is always allowed.
* Access can be achieved by calling unwrap on the pooled connection. see {@link javax.sql.DataSource} interface
* or call getConnection through reflection or cast the object as {@link javax.sql.PooledConnection}
* @return true
*/
public boolean isAccessToUnderlyingConnectionAllowed();
/**
* No-op
* @param accessToUnderlyingConnectionAllowed parameter ignored
*/
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed);
/**
* The connection properties that will be sent to the JDBC driver when establishing new connections.
* Format of the string is [propertyName=property;] <br/>
* NOTE - The "user" and "password" properties will be passed explicitly, so they do not need to be included here.
* The default value is null.
*/
public String getConnectionProperties();
/**
* The properties that will be passed into {@link java.sql.Driver#connect(String, Properties)} method.
* Username and password do not need to be stored here, they will be passed into the properties right before the connection is established.
* @param connectionProperties properties - Format of the string is [propertyName=property;]*
* Example: prop1=value1;prop2=value2
*/
public void setConnectionProperties(String connectionProperties);
/**
* Returns the database properties that are passed into the {@link java.sql.Driver#connect(String, Properties)} method.
* @return database properties that are passed into the {@link java.sql.Driver#connect(String, Properties)} method.
*/
public Properties getDbProperties();
/**
* Overrides the database properties passed into the {@link java.sql.Driver#connect(String, Properties)} method.
* @param dbProperties
*/
public void setDbProperties(Properties dbProperties);
/**
* The default auto-commit state of connections created by this pool.
* If not set (null), default is JDBC driver default (If set to null then the {@link java.sql.Connection#setAutoCommit(boolean)} method will not be called.)
* @return the default auto commit setting, null is Driver default.
*/
public Boolean isDefaultAutoCommit();
/**
* The default auto-commit state of connections created by this pool.
* If not set (null), default is JDBC driver default (If set to null then the {@link java.sql.Connection#setAutoCommit(boolean)} method will not be called.)
* @return the default auto commit setting, null is Driver default.
*/
public Boolean getDefaultAutoCommit();
/**
* The default auto-commit state of connections created by this pool.
* If not set (null), default is JDBC driver default (If set to null then the {@link java.sql.Connection#setAutoCommit(boolean)} method will not be called.)
* @param defaultAutoCommit default auto commit setting, null is Driver default.
*/
public void setDefaultAutoCommit(Boolean defaultAutoCommit);
/**
* If non null, during connection creation the method {@link java.sql.Connection#setCatalog(String)} will be called with the set value.
* @return the default catalog, null if not set and accepting the driver default.
*/
public String getDefaultCatalog();
/**
* If non null, during connection creation the method {@link java.sql.Connection#setCatalog(String)} will be called with the set value.
* @param defaultCatalog null if not set and accepting the driver default.
*/
public void setDefaultCatalog(String defaultCatalog);
/**
* If non null, during connection creation the method {@link java.sql.Connection#setReadOnly(boolean)} will be called with the set value.
* @return null if not set and accepting the driver default otherwise the read only value
*/
public Boolean isDefaultReadOnly();
/**
* If non null, during connection creation the method {@link java.sql.Connection#setReadOnly(boolean)} will be called with the set value.
* @return null if not set and accepting the driver default otherwise the read only value
*/
public Boolean getDefaultReadOnly();
/**
* If non null, during connection creation the method {@link java.sql.Connection#setReadOnly(boolean)} will be called with the set value.
* @param defaultReadOnly null if not set and accepting the driver default.
*/
public void setDefaultReadOnly(Boolean defaultReadOnly);
/**
* Returns the default transaction isolation level. If set to {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION} the method
* {@link java.sql.Connection#setTransactionIsolation(int)} will not be called during connection creation.
* @return driver transaction isolation level, or -1 {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION} if not set.
*/
public int getDefaultTransactionIsolation();
/**
* If set to {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION} the method
* {@link java.sql.Connection#setTransactionIsolation(int)} will not be called during connection creation. Otherwise the method
* will be called with the isolation level set by this property.
* @param defaultTransactionIsolation a value of {@link java.sql.Connection#TRANSACTION_NONE}, {@link java.sql.Connection#TRANSACTION_READ_COMMITTED},
* {@link java.sql.Connection#TRANSACTION_READ_UNCOMMITTED}, {@link java.sql.Connection#TRANSACTION_REPEATABLE_READ},
* {@link java.sql.Connection#TRANSACTION_SERIALIZABLE} or {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION}
* The last value will not be set on the connection.
*/
public void setDefaultTransactionIsolation(int defaultTransactionIsolation);
/**
* The fully qualified Java class name of the JDBC driver to be used. The driver has to be accessible from the same classloader as tomcat-jdbc.jar
* @return fully qualified JDBC driver name.
*/
public String getDriverClassName();
/**
* The fully qualified Java class name of the JDBC driver to be used. The driver has to be accessible from the same classloader as tomcat-jdbc.jar
* @param driverClassName a fully qualified Java class name of a {@link java.sql.Driver} implementation.
*/
public void setDriverClassName(String driverClassName);
/**
* Returns the number of connections that will be established when the connection pool is started.
* Default value is 10
* @return number of connections to be started when pool is started
*/
public int getInitialSize();
/**
* Set the number of connections that will be established when the connection pool is started.
* Default value is 10.
* If this value exceeds {@link #setMaxActive(int)} it will automatically be lowered.
* @param initialSize the number of connections to be established.
*
*/
public void setInitialSize(int initialSize);
/**
* boolean flag to set if stack traces should be logged for application code which abandoned a Connection.
* Logging of abandoned Connections adds overhead for every Connection borrow because a stack trace has to be generated.
* The default value is false.
* @return true if the connection pool logs stack traces when connections are borrowed from the pool.
*/
public boolean isLogAbandoned();
/**
* boolean flag to set if stack traces should be logged for application code which abandoned a Connection.
* Logging of abandoned Connections adds overhead for every Connection borrow because a stack trace has to be generated.
* The default value is false.
* @param logAbandoned set to true if stack traces should be recorded when {@link DataSource#getConnection()} is called.
*/
public void setLogAbandoned(boolean logAbandoned);
/**
* The maximum number of active connections that can be allocated from this pool at the same time. The default value is 100
* @return the maximum number of connections used by this pool
*/
public int getMaxActive();
/**
* The maximum number of active connections that can be allocated from this pool at the same time. The default value is 100
* @param maxActive hard limit for number of managed connections by this pool
*/
public void setMaxActive(int maxActive);
/**
* The maximum number of connections that should be kept in the idle pool if {@link #isPoolSweeperEnabled()} returns false.
* If the If {@link #isPoolSweeperEnabled()} returns true, then the idle pool can grow up to {@link #getMaxActive}
* and will be shrunk according to {@link #getMinEvictableIdleTimeMillis()} setting.
* Default value is maxActive:100
* @return the maximum number of idle connections.
*/
public int getMaxIdle();
/**
* The maximum number of connections that should be kept in the idle pool if {@link #isPoolSweeperEnabled()} returns false.
* If the If {@link #isPoolSweeperEnabled()} returns true, then the idle pool can grow up to {@link #getMaxActive}
* and will be shrunk according to {@link #getMinEvictableIdleTimeMillis()} setting.
* Default value is maxActive:100
* @param maxIdle the maximum size of the idle pool
*/
public void setMaxIdle(int maxIdle);
/**
* The maximum number of milliseconds that the pool will wait (when there are no available connections and the
* {@link #getMaxActive} has been reached) for a connection to be returned
* before throwing an exception. Default value is 30000 (30 seconds)
* @return the number of milliseconds to wait for a connection to become available if the pool is maxed out.
*/
public int getMaxWait();
/**
* The maximum number of milliseconds that the pool will wait (when there are no available connections and the
* {@link #getMaxActive} has been reached) for a connection to be returned
* before throwing an exception. Default value is 30000 (30 seconds)
* @param maxWait the maximum number of milliseconds to wait.
*/
public void setMaxWait(int maxWait);
/**
* The minimum amount of time an object must sit idle in the pool before it is eligible for eviction.
* The default value is 60000 (60 seconds).
* @return the minimum amount of idle time in milliseconds before a connection is considered idle and eligible for eviction.
*/
public int getMinEvictableIdleTimeMillis();
/**
* The minimum amount of time an object must sit idle in the pool before it is eligible for eviction.
* The default value is 60000 (60 seconds).
* @param minEvictableIdleTimeMillis the number of milliseconds a connection must be idle to be eligible for eviction.
*/
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis);
/**
* The minimum number of established connections that should be kept in the pool at all times.
* The connection pool can shrink below this number if validation queries fail and connections get closed.
* Default value is derived from {@link #getInitialSize()} (also see {@link #setTestWhileIdle(boolean)}
* The idle pool will not shrink below this value during an eviction run, hence the number of actual connections
* can be between {@link #getMinIdle()} and somewhere between {@link #getMaxIdle()} and {@link #getMaxActive()}
* @return the minimum number of idle or established connections
*/
public int getMinIdle();
/**
* The minimum number of established connections that should be kept in the pool at all times.
* The connection pool can shrink below this number if validation queries fail and connections get closed.
* Default value is derived from {@link #getInitialSize()} (also see {@link #setTestWhileIdle(boolean)}
* The idle pool will not shrink below this value during an eviction run, hence the number of actual connections
* can be between {@link #getMinIdle()} and somewhere between {@link #getMaxIdle()} and {@link #getMaxActive()}
*
* @param minIdle the minimum number of idle or established connections
*/
public void setMinIdle(int minIdle);
/**
* Returns the name of the connection pool. By default a JVM unique random name is assigned.
* @return the name of the pool, should be unique in a JVM
*/
public String getName();
/**
* Sets the name of the connection pool
* @param name the name of the pool, should be unique in a runtime JVM
*/
public void setName(String name);
/**
* Property not used
* @return unknown value
*/
public int getNumTestsPerEvictionRun();
/**
* Property not used
* @param numTestsPerEvictionRun parameter ignored.
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun);
/**
* Returns the password used when establishing connections to the database.
* @return the password in string format
*/
public String getPassword();
/**
* Sets the password to establish the connection with.
* The password will be included as a database property with the name 'password'.
* @param password
* @see #getDbProperties()
*/
public void setPassword(String password);
/**
* @see #getName()
* @return name
*/
public String getPoolName();
/**
* Returns the username used to establish the connection with
* @return the username used to establish the connection with
*/
public String getUsername();
/**
* Sets the username used to establish the connection with
* It will also be a property called 'user' in the database properties.
* @param username
* @see #getDbProperties()
*/
public void setUsername(String username);
/**
* boolean flag to remove abandoned connections if they exceed the removeAbandonedTimout.
* If set to true a connection is considered abandoned and eligible for removal if it has
* been in use longer than the {@link #getRemoveAbandonedTimeout()} and the condition for
* {@link #getAbandonWhenPercentageFull()} is met.
* Setting this to true can recover db connections from applications that fail to close a connection.
* See also {@link #isLogAbandoned()} The default value is false.
* @return true if abandoned connections can be closed and expelled out of the pool
*/
public boolean isRemoveAbandoned();
/**
* boolean flag to remove abandoned connections if they exceed the removeAbandonedTimout.
* If set to true a connection is considered abandoned and eligible for removal if it has
* been in use longer than the {@link #getRemoveAbandonedTimeout()} and the condition for
* {@link #getAbandonWhenPercentageFull()} is met.
* Setting this to true can recover db connections from applications that fail to close a connection.
* See also {@link #isLogAbandoned()} The default value is false.
* @param removeAbandoned set to true if abandoned connections can be closed and expelled out of the pool
*/
public void setRemoveAbandoned(boolean removeAbandoned);
/**
* The time in seconds before a connection can be considered abandoned.
* The timer can be reset upon queries using an interceptor.
* @param removeAbandonedTimeout the time in seconds before a used connection can be considered abandoned
* @see org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer
*/
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout);
/**
* The time in seconds before a connection can be considered abandoned.
* The timer can be reset upon queries using an interceptor.
* @see org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer
* @return the time in seconds before a used connection can be considered abandoned
*/
public int getRemoveAbandonedTimeout();
/**
* The indication of whether objects will be validated before being borrowed from the pool.
* If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @return true if the connection is to be validated upon borrowing a connection from the pool
* @see #getValidationInterval()
*/
public boolean isTestOnBorrow();
/**
* The indication of whether objects will be validated before being borrowed from the pool.
* If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @param testOnBorrow set to true if validation should take place before a connection is handed out to the application
* @see #getValidationInterval()
*/
public void setTestOnBorrow(boolean testOnBorrow);
/**
* The indication of whether objects will be validated after being returned to the pool.
* If the object fails to validate, it will be dropped from the pool.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @return true if validation should take place after a connection is returned to the pool
* @see #getValidationInterval()
*/
public boolean isTestOnReturn();
/**
* The indication of whether objects will be validated after being returned to the pool.
* If the object fails to validate, it will be dropped from the pool.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @param testOnReturn true if validation should take place after a connection is returned to the pool
* @see #getValidationInterval()
*/
public void setTestOnReturn(boolean testOnReturn);
/**
* Set to true if query validation should take place while the connection is idle.
* @return true if validation should take place during idle checks
* @see #setTimeBetweenEvictionRunsMillis(int)
*/
public boolean isTestWhileIdle();
/**
* Set to true if query validation should take place while the connection is idle.
* @param testWhileIdle true if validation should take place during idle checks
* @see #setTimeBetweenEvictionRunsMillis(int)
*/
public void setTestWhileIdle(boolean testWhileIdle);
/**
* The number of milliseconds to sleep between runs of the idle connection validation, abandoned cleaner
* and idle pool resizing. This value should not be set under 1 second.
* It dictates how often we check for idle, abandoned connections, and how often we validate idle connection and resize the idle pool.
* The default value is 5000 (5 seconds)
* @return the sleep time in between validations in milliseconds
*/
public int getTimeBetweenEvictionRunsMillis();
/**
* The number of milliseconds to sleep between runs of the idle connection validation, abandoned cleaner
* and idle pool resizing. This value should not be set under 1 second.
* It dictates how often we check for idle, abandoned connections, and how often we validate idle connection and resize the idle pool.
* The default value is 5000 (5 seconds)
* @param timeBetweenEvictionRunsMillis the sleep time in between validations in milliseconds
*/
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis);
/**
* The URL used to connect to the database
* @return the configured URL for this connection pool
* @see java.sql.Driver#connect(String, Properties)
*/
public String getUrl();
/**
* Sets the URL used to connect to the database
* @param url the configured URL for this connection pool
* @see java.sql.Driver#connect(String, Properties)
*/
public void setUrl(String url);
/**
* The SQL query that will be used to validate connections from this
* pool before returning them to the caller or pool.
* If specified, this query does not have to return any data,
* it just can't throw a SQLException.
* The default value is null.
* Example values are SELECT 1(mysql),
* select 1 from dual(oracle),
* SELECT 1(MS Sql Server)
* @return the query used for validation or null if no validation is performed
*/
public String getValidationQuery();
/**
* The SQL query that will be used to validate connections from this
* pool before returning them to the caller or pool.
* If specified, this query does not have to return any data,
* it just can't throw a SQLException.
* The default value is null.
* Example values are SELECT 1(mysql),
* select 1 from dual(oracle),
* SELECT 1(MS Sql Server)
* @param validationQuery the query used for validation or null if no validation is performed
*/
public void setValidationQuery(String validationQuery);
/**
* Return the name of the optional validator class - may be null.
*
* @return the name of the optional validator class - may be null
*/
public String getValidatorClassName();
/**
* Set the name for an optional validator class which will be used in place of test queries. If set to
* null, standard validation will be used.
*
* @param className the name of the optional validator class
*/
public void setValidatorClassName(String className);
/**
* @return the optional validator object - may be null
*/
public Validator getValidator();
/**
* Sets the validator object
* If this is a non null object, it will be used as a validator instead of the validationQuery
* If this is null, remove the usage of the validator.
*/
public void setValidator(Validator validator);
/**
* avoid excess validation, only run validation at most at this frequency - time in milliseconds.
* If a connection is due for validation, but has been validated previously
* within this interval, it will not be validated again.
* The default value is 30000 (30 seconds).
* @return the validation interval in milliseconds
*/
public long getValidationInterval();
/**
* avoid excess validation, only run validation at most at this frequency - time in milliseconds.
* If a connection is due for validation, but has been validated previously
* within this interval, it will not be validated again.
* The default value is 30000 (30 seconds).
* @param validationInterval the validation interval in milliseconds
*/
public void setValidationInterval(long validationInterval);
/**
* A custom query to be run when a connection is first created. The default value is null.
* This query only runs once per connection, and that is when a new connection is established to the database.
* If this value is non null, it will replace the validation query during connection creation.
* @return the init SQL used to run against the DB or null if not set
*/
public String getInitSQL();
/**
* A custom query to be run when a connection is first created. The default value is null.
* This query only runs once per connection, and that is when a new connection is established to the database.
* If this value is non null, it will replace the validation query during connection creation.
* @param initSQL the init SQL used to run against the DB or null if no query should be executed
*/
public void setInitSQL(String initSQL);
/**
* Returns true if we should run the validation query when connecting to the database for the first time on a connection.
* Normally this is always set to false, unless one wants to use the validationQuery as an init query.
* @return true if we should run the validation query upon connect
*/
public boolean isTestOnConnect();
/**
* Set to true if we should run the validation query when connecting to the database for the first time on a connection.
* Normally this is always set to false, unless one wants to use the validationQuery as an init query.
* Setting an {@link #setInitSQL(String)} will override this setting, as the init SQL will be used instead of the validation query
* @param testOnConnect set to true if we should run the validation query upon connect
*/
public void setTestOnConnect(boolean testOnConnect);
/**
* A semicolon separated list of classnames extending {@link org.apache.tomcat.jdbc.pool.JdbcInterceptor} class.
* These interceptors will be inserted as an interceptor into the chain of operations on a java.sql.Connection object.
* Example interceptors are {@link org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer StatementFinalizer} to close all
* used statements during the session.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer ResetAbandonedTimer} resets the timer upon every operation
* on the connection or a statement.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ConnectionState ConnectionState} caches the auto commit, read only and catalog settings to avoid round trips to the DB.
* The default value is null.
* @return the interceptors that are used for connections.
* Example format: 'ConnectionState(useEquals=true,fast=yes);ResetAbandonedTimer'
*/
public String getJdbcInterceptors();
/**
* A semicolon separated list of classnames extending {@link org.apache.tomcat.jdbc.pool.JdbcInterceptor} class.
* These interceptors will be inserted as an interceptor into the chain of operations on a java.sql.Connection object.
* Example interceptors are {@link org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer StatementFinalizer} to close all
* used statements during the session.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer ResetAbandonedTimer} resets the timer upon every operation
* on the connection or a statement.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ConnectionState ConnectionState} caches the auto commit, read only and catalog settings to avoid round trips to the DB.
* The default value is null.
* @param jdbcInterceptors the interceptors that are used for connections.
* Example format: 'ConnectionState(useEquals=true,fast=yes);ResetAbandonedTimer'
*/
public void setJdbcInterceptors(String jdbcInterceptors);
/**
* Returns the {@link #getJdbcInterceptors()} as an array of objects with properties and the classes.
* @return an array of interceptors that have been configured
*/
public InterceptorDefinition[] getJdbcInterceptorsAsArray();
/**
* If set to true, the connection pool creates a {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} object
* that can be registered with JMX to receive notifications and state about the pool.
* The ConnectionPool object doesn't register itself, as there is no way to keep a static non changing ObjectName across JVM restarts.
* @return true if the mbean object will be created upon startup.
*/
public boolean isJmxEnabled();
/**
* If set to true, the connection pool creates a {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} object
* that can be registered with JMX to receive notifications and state about the pool.
* The ConnectionPool object doesn't register itself, as there is no way to keep a static non changing ObjectName across JVM restarts.
* @param jmxEnabled set to to if the mbean object should be created upon startup.
*/
public void setJmxEnabled(boolean jmxEnabled);
/**
* Returns true if the pool sweeper is enabled for the connection pool.
* The pool sweeper is enabled if any settings that require async intervention in the pool are turned on
* <source>
boolean result = getTimeBetweenEvictionRunsMillis()>0;
result = result && (isRemoveAbandoned() && getRemoveAbandonedTimeout()>0);
result = result || (isTestWhileIdle() && getValidationQuery()!=null);
return result;
</source>
*
* @return true if a background thread is or will be enabled for this pool
*/
public boolean isPoolSweeperEnabled();
/**
* Set to true if you wish the <code>ProxyConnection</code> class to use <code>String.equals</code> instead of
* <code>==</code> when comparing method names.
* This property does not apply to added interceptors as those are configured individually.
* The default value is <code>false</code>.
* @return true if pool uses {@link String#equals(Object)} instead of == when comparing method names on {@link java.sql.Connection} methods
*/
public boolean isUseEquals();
/**
* Set to true if you wish the <code>ProxyConnection</code> class to use <code>String.equals</code> instead of
* <code>==</code> when comparing method names.
* This property does not apply to added interceptors as those are configured individually.
* The default value is <code>false</code>.
* @param useEquals set to true if the pool should use {@link String#equals(Object)} instead of ==
* when comparing method names on {@link java.sql.Connection} methods
*/
public void setUseEquals(boolean useEquals);
/**
* Time in milliseconds to keep this connection alive even when used.
* When a connection is returned to the pool, the pool will check to see if the
* ((now - time-when-connected) > maxAge) has been reached, and if so,
* it closes the connection rather than returning it to the pool.
* The default value is 0, which implies that connections will be left open and no
* age check will be done upon returning the connection to the pool.
* This is a useful setting for database sessions that leak memory as it ensures that the session
* will have a finite life span.
* @return the time in milliseconds a connection will be open for when used
*/
public long getMaxAge();
/**
* Time in milliseconds to keep this connection alive even when used.
* When a connection is returned to the pool, the pool will check to see if the
* ((now - time-when-connected) > maxAge) has been reached, and if so,
* it closes the connection rather than returning it to the pool.
* The default value is 0, which implies that connections will be left open and no
* age check will be done upon returning the connection to the pool.
* This is a useful setting for database sessions that leak memory as it ensures that the session
* will have a finite life span.
* @param maxAge the time in milliseconds a connection will be open for when used
*/
public void setMaxAge(long maxAge);
/**
* Return true if a lock should be used when operations are performed on the connection object.
* Should be set to false unless you plan to have a background thread of your own doing idle and abandon checking
* such as JMX clients. If the pool sweeper is enabled, then the lock will automatically be used regardless of this setting.
* @return true if a lock is used.
*/
public boolean getUseLock();
/**
* Set to true if a lock should be used when operations are performed on the connection object.
* Should be set to false unless you plan to have a background thread of your own doing idle and abandon checking
* such as JMX clients. If the pool sweeper is enabled, then the lock will automatically be used regardless of this setting.
* @param useLock set to true if a lock should be used on connection operations
*/
public void setUseLock(boolean useLock);
/**
* Similar to {@link #setRemoveAbandonedTimeout(int)} but instead of treating the connection
* as abandoned, and potentially closing the connection, this simply logs the warning if
* {@link #isLogAbandoned()} returns true. If this value is equal or less than 0, no suspect
* checking will be performed. Suspect checking only takes place if the timeout value is larger than 0 and
* the connection was not abandoned or if abandon check is disabled. If a connection is suspect a WARN message gets
* logged and a JMX notification gets sent once.
* @param seconds - the amount of time in seconds that has to pass before a connection is marked suspect.
*/
public void setSuspectTimeout(int seconds);
/**
* Returns the time in seconds to pass before a connection is marked an abanoned suspect.
* Any value lesser than or equal to 0 means the check is disabled.
* @return Returns the time in seconds to pass before a connection is marked an abanoned suspect.
*/
public int getSuspectTimeout();
/**
* Injects a datasource that will be used to retrieve/create connections.
* If a data source is set, the {@link PoolConfiguration#getUrl()} and {@link PoolConfiguration#getDriverClassName()} methods are ignored
* and not used by the pool. If the {@link PoolConfiguration#getUsername()} and {@link PoolConfiguration#getPassword()}
* values are set, the method {@link javax.sql.DataSource#getConnection(String, String)} method will be called instead of the
* {@link javax.sql.DataSource#getConnection()} method.
* If the data source implements {@link javax.sql.XADataSource} the methods
* {@link javax.sql.XADataSource#getXAConnection()} and {@link javax.sql.XADataSource#getXAConnection(String,String)}
* will be invoked.
* @param ds the {@link javax.sql.DataSource} to be used for creating connections to be pooled.
*/
public void setDataSource(Object ds);
/**
* Returns a datasource, if one exists that is being used to create connections.
* This method will return null if the pool is using a {@link java.sql.Driver}
* @return the {@link javax.sql.DataSource} to be used for creating connections to be pooled or null if a Driver is used.
*/
public Object getDataSource();
/**
* Configure the connection pool to use a DataSource according to {@link PoolConfiguration#setDataSource(Object)}
* But instead of injecting the object, specify the JNDI location.
* After a successful JNDI look, the {@link PoolConfiguration#getDataSource()} will not return null.
* @param jndiDS -the JNDI string @TODO specify the rules here.
*/
public void setDataSourceJNDI(String jndiDS);
/**
* Returns the JNDI string configured for data source usage.
* @return the JNDI string or null if not set
*/
public String getDataSourceJNDI();
/**
* Returns true if the call {@link DataSource#getConnection(String, String) getConnection(username,password)} is
* allowed. This is used for when the pool is used by an application accessing multiple schemas.
* There is a performance impact turning this option on.
* @return true if {@link DataSource#getConnection(String, String) getConnection(username,password)} is honored, false if it is ignored.
*/
public boolean isAlternateUsernameAllowed();
/**
* Set to true if the call {@link DataSource#getConnection(String, String) getConnection(username,password)} is
* allowed and honored.. This is used for when the pool is used by an application accessing multiple schemas.
* There is a performance impact turning this option on, even when not used due to username checks.
* @param alternateUsernameAllowed - set true if {@link DataSource#getConnection(String, String) getConnection(username,password)} is honored,
* false if it is to be ignored.
*/
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed);
/**
* Set to true if you want the connection pool to commit any pending transaction when a connection is returned.
* The default value is false, as this could result in committing data.
* This parameter is only looked at if the {@link #getDefaultAutoCommit()} returns false
* @param commitOnReturn set to true if the pool should call {@link java.sql.Connection#commit()} when a connection is returned to the pool.
* Default is false
*/
public void setCommitOnReturn(boolean commitOnReturn);
/**
* @see PoolConfiguration#setCommitOnReturn(boolean)
*/
public boolean getCommitOnReturn();
/**
* Set to true if you want the connection pool to rollback any pending transaction when a connection is returned.
* The default value is false, as this could result in committing data.
* This parameter is only looked at if the {@link #getDefaultAutoCommit()} returns false
* @param rollbackOnReturn set to true if the pool should call {@link java.sql.Connection#rollback()} when a connection is returned to the pool.
* Default is false
*/
public void setRollbackOnReturn(boolean rollbackOnReturn);
/**
* @see PoolConfiguration#setRollbackOnReturn(boolean)
*/
public boolean getRollbackOnReturn();
/**
* If set to true, the connection will be wrapped with facade that will disallow the connection to be used after
* {@link java.sql.Connection#close()} is called. If set to true, after {@link java.sql.Connection#close()} all calls except
* {@link java.sql.Connection#close()} and {@link java.sql.Connection#isClosed()} will throw an exception.
* @param useDisposableConnectionFacade
*/
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade);
/**
* Returns true if this connection pool is configured to use a connection facade to prevent re-use of connection after
* {@link java.sql.Connection#close()} has been invoked
* @return true if {@link java.sql.Connection#close()} has been invoked.
*/
public boolean getUseDisposableConnectionFacade();
/**
* Set to true if you wish that errors from validation should be logged as error messages.
* @param logValidationErrors set to true to log validation errors
*/
public void setLogValidationErrors(boolean logValidationErrors);
/**
* Returns true if errors that happen during validation will be logged
* @return true if errors that happen during validation will be logged
*/
public boolean getLogValidationErrors();
/**
* Returns true if the pool is configured to propagate interrupt state of a thread.
* A thread waiting for a connection, can have its wait interrupted, and by default
* will clear the interrupt flag and throw a {@link PoolExhaustedException}
* @return true if the pool is configured to propagate and not clear the thread interrupt state
*/
public boolean getPropagateInterruptState();
/**
* Configure the pool to propagate interrupt state for interrupted threads waiting for a connection
* A thread waiting for a connection, can have its wait interrupted, and by default
* will clear the interrupt flag and throw a {@link PoolExhaustedException}
* If set to true, this behavior will change, while the {@link PoolExhaustedException} is still thrown, the threads interrupted state is still set.
* @param propagateInterruptState - set to true to not clear, but propagate, a threads interrupted state.
*/
public void setPropagateInterruptState(boolean propagateInterruptState);
}
|
55,343
|
Bug 55343 Add flag to ignore exceptions while creating initial pool
|
I want my initial pool to be of some size i.e. not empty AND start even if it fails to create all or some of connections. If pool fails to create initial connections for some reason it just throws exceptions. To workaround that I have to set initial pool size to 0. It can be handy to add a flag to ignore (just log them) exceptions that occur while creating initial connections.
|
resolved fixed
|
4aa42d7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T08:56:24Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java
|
/*
* 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.jdbc.pool;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* @author Filip Hanik
*
*/
public class PoolProperties implements PoolConfiguration, Cloneable, Serializable {
private static final long serialVersionUID = -8519283440854213745L;
private static final Log log = LogFactory.getLog(PoolProperties.class);
public static final int DEFAULT_MAX_ACTIVE = 100;
protected static AtomicInteger poolCounter = new AtomicInteger(0);
private volatile Properties dbProperties = new Properties();
private volatile String url = null;
private volatile String driverClassName = null;
private volatile Boolean defaultAutoCommit = null;
private volatile Boolean defaultReadOnly = null;
private volatile int defaultTransactionIsolation = DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION;
private volatile String defaultCatalog = null;
private volatile String connectionProperties;
private volatile int initialSize = 10;
private volatile int maxActive = DEFAULT_MAX_ACTIVE;
private volatile int maxIdle = maxActive;
private volatile int minIdle = initialSize;
private volatile int maxWait = 30000;
private volatile String validationQuery;
private volatile String validatorClassName;
private volatile Validator validator;
private volatile boolean testOnBorrow = false;
private volatile boolean testOnReturn = false;
private volatile boolean testWhileIdle = false;
private volatile int timeBetweenEvictionRunsMillis = 5000;
private volatile int numTestsPerEvictionRun;
private volatile int minEvictableIdleTimeMillis = 60000;
private volatile boolean accessToUnderlyingConnectionAllowed = true;
private volatile boolean removeAbandoned = false;
private volatile int removeAbandonedTimeout = 60;
private volatile boolean logAbandoned = false;
private volatile String name = "Tomcat Connection Pool["+(poolCounter.addAndGet(1))+"-"+System.identityHashCode(PoolProperties.class)+"]";
private volatile String password;
private volatile String username;
private volatile long validationInterval = 30000;
private volatile boolean jmxEnabled = true;
private volatile String initSQL;
private volatile boolean testOnConnect =false;
private volatile String jdbcInterceptors=null;
private volatile boolean fairQueue = true;
private volatile boolean useEquals = true;
private volatile int abandonWhenPercentageFull = 0;
private volatile long maxAge = 0;
private volatile boolean useLock = false;
private volatile InterceptorDefinition[] interceptors = null;
private volatile int suspectTimeout = 0;
private volatile Object dataSource = null;
private volatile String dataSourceJNDI = null;
private volatile boolean alternateUsernameAllowed = false;
private volatile boolean commitOnReturn = false;
private volatile boolean rollbackOnReturn = false;
private volatile boolean useDisposableConnectionFacade = true;
private volatile boolean logValidationErrors = false;
private volatile boolean propagateInterruptState = false;
/**
* {@inheritDoc}
*/
@Override
public void setAbandonWhenPercentageFull(int percentage) {
if (percentage<0) abandonWhenPercentageFull = 0;
else if (percentage>100) abandonWhenPercentageFull = 100;
else abandonWhenPercentageFull = percentage;
}
/**
* {@inheritDoc}
*/
@Override
public int getAbandonWhenPercentageFull() {
return abandonWhenPercentageFull;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFairQueue() {
return fairQueue;
}
/**
* {@inheritDoc}
*/
@Override
public void setFairQueue(boolean fairQueue) {
this.fairQueue = fairQueue;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAccessToUnderlyingConnectionAllowed() {
return accessToUnderlyingConnectionAllowed;
}
/**
* {@inheritDoc}
*/
@Override
public String getConnectionProperties() {
return connectionProperties;
}
/**
* {@inheritDoc}
*/
@Override
public Properties getDbProperties() {
return dbProperties;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultCatalog() {
return defaultCatalog;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultReadOnly() {
return defaultReadOnly;
}
/**
* {@inheritDoc}
*/
@Override
public int getDefaultTransactionIsolation() {
return defaultTransactionIsolation;
}
/**
* {@inheritDoc}
*/
@Override
public String getDriverClassName() {
return driverClassName;
}
/**
* {@inheritDoc}
*/
@Override
public int getInitialSize() {
return initialSize;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLogAbandoned() {
return logAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxActive() {
return maxActive;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxIdle() {
return maxIdle;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxWait() {
return maxWait;
}
/**
* {@inheritDoc}
*/
@Override
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
/**
* {@inheritDoc}
*/
@Override
public int getMinIdle() {
return minIdle;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return name;
}
/**
* {@inheritDoc}
*/
@Override
public int getNumTestsPerEvictionRun() {
return numTestsPerEvictionRun;
}
/**
* {@inheritDoc}
*/
@Override
public String getPassword() {
return password;
}
/**
* {@inheritDoc}
*/
@Override
public String getPoolName() {
return getName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRemoveAbandoned() {
return removeAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public int getRemoveAbandonedTimeout() {
return removeAbandonedTimeout;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnBorrow() {
return testOnBorrow;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnReturn() {
return testOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestWhileIdle() {
return testWhileIdle;
}
/**
* {@inheritDoc}
*/
@Override
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
/**
* {@inheritDoc}
*/
@Override
public String getUrl() {
return url;
}
/**
* {@inheritDoc}
*/
@Override
public String getUsername() {
return username;
}
/**
* {@inheritDoc}
*/
@Override
public String getValidationQuery() {
return validationQuery;
}
/**
* {@inheritDoc}
*/
@Override
public String getValidatorClassName() {
return validatorClassName;
}
/**
* {@inheritDoc}
*/
@Override
public Validator getValidator() {
return validator;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidator(Validator validator) {
this.validator = validator;
if (validator!=null) {
this.validatorClassName = validator.getClass().getName();
} else {
this.validatorClassName = null;
}
}
/**
* {@inheritDoc}
*/
@Override
public long getValidationInterval() {
return validationInterval;
}
/**
* {@inheritDoc}
*/
@Override
public String getInitSQL() {
return initSQL;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnConnect() {
return testOnConnect;
}
/**
* {@inheritDoc}
*/
@Override
public String getJdbcInterceptors() {
return jdbcInterceptors;
}
/**
* {@inheritDoc}
*/
@Override
public InterceptorDefinition[] getJdbcInterceptorsAsArray() {
if (interceptors == null) {
if (jdbcInterceptors==null) {
interceptors = new InterceptorDefinition[0];
} else {
String[] interceptorValues = jdbcInterceptors.split(";");
InterceptorDefinition[] definitions = new InterceptorDefinition[interceptorValues.length+1];
//always add the trap interceptor to the mix
definitions[0] = new InterceptorDefinition(TrapException.class);
for (int i=0; i<interceptorValues.length; i++) {
int propIndex = interceptorValues[i].indexOf("(");
int endIndex = interceptorValues[i].indexOf(")");
if (propIndex<0 || endIndex<0 || endIndex <= propIndex) {
definitions[i+1] = new InterceptorDefinition(interceptorValues[i].trim());
} else {
String name = interceptorValues[i].substring(0,propIndex).trim();
definitions[i+1] = new InterceptorDefinition(name);
String propsAsString = interceptorValues[i].substring(propIndex+1, interceptorValues[i].length()-1);
String[] props = propsAsString.split(",");
for (int j=0; j<props.length; j++) {
int pidx = props[j].indexOf("=");
String propName = props[j].substring(0,pidx).trim();
String propValue = props[j].substring(pidx+1).trim();
definitions[i+1].addProperty(new InterceptorProperty(propName,propValue));
}
}
}
interceptors = definitions;
}
}
return interceptors;
}
/**
* {@inheritDoc}
*/
@Override
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) {
// NOOP
}
/**
* {@inheritDoc}
*/
@Override
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
getProperties(connectionProperties, getDbProperties());
}
/**
* {@inheritDoc}
*/
@Override
public void setDbProperties(Properties dbProperties) {
this.dbProperties = dbProperties;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultAutoCommit(Boolean defaultAutoCommit) {
this.defaultAutoCommit = defaultAutoCommit;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultCatalog(String defaultCatalog) {
this.defaultCatalog = defaultCatalog;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultReadOnly(Boolean defaultReadOnly) {
this.defaultReadOnly = defaultReadOnly;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
this.defaultTransactionIsolation = defaultTransactionIsolation;
}
/**
* {@inheritDoc}
*/
@Override
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
/**
* {@inheritDoc}
*/
@Override
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
/**
* {@inheritDoc}
*/
@Override
public void setLogAbandoned(boolean logAbandoned) {
this.logAbandoned = logAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
/**
* {@inheritDoc}
*/
@Override
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* {@inheritDoc}
*/
@Override
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* {@inheritDoc}
*/
@Override
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* {@inheritDoc}
*/
@Override
public void setPassword(String password) {
this.password = password;
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandoned(boolean removeAbandoned) {
this.removeAbandoned = removeAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
this.removeAbandonedTimeout = removeAbandonedTimeout;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public void setTimeBetweenEvictionRunsMillis(int
timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* {@inheritDoc}
*/
@Override
public void setUrl(String url) {
this.url = url;
}
/**
* {@inheritDoc}
*/
@Override
public void setUsername(String username) {
this.username = username;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationInterval(long validationInterval) {
this.validationInterval = validationInterval;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidatorClassName(String className) {
this.validatorClassName = className;
validator = null;
if (className == null) {
return;
}
try {
@SuppressWarnings("unchecked")
Class<Validator> validatorClass = (Class<Validator>)Class.forName(className);
validator = validatorClass.newInstance();
} catch (ClassNotFoundException e) {
log.warn("The class "+className+" cannot be found.", e);
} catch (ClassCastException e) {
log.warn("The class "+className+" does not implement the Validator interface.", e);
} catch (InstantiationException e) {
log.warn("An object of class "+className+" cannot be instantiated. Make sure that "+
"it includes an implicit or explicit no-arg constructor.", e);
} catch (IllegalAccessException e) {
log.warn("The class "+className+" or its no-arg constructor are inaccessible.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setInitSQL(String initSQL) {
this.initSQL = initSQL;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnConnect(boolean testOnConnect) {
this.testOnConnect = testOnConnect;
}
/**
* {@inheritDoc}
*/
@Override
public void setJdbcInterceptors(String jdbcInterceptors) {
this.jdbcInterceptors = jdbcInterceptors;
this.interceptors = null;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("ConnectionPool[");
try {
String[] fields = DataSourceFactory.ALL_PROPERTIES;
for (String field: fields) {
final String[] prefix = new String[] {"get","is"};
for (int j=0; j<prefix.length; j++) {
String name = prefix[j]
+ field.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ field.substring(1);
Method m = null;
try {
m = getClass().getMethod(name);
}catch (NoSuchMethodException nm) {
continue;
}
buf.append(field);
buf.append("=");
if (DataSourceFactory.PROP_PASSWORD.equals(field)) {
buf.append("********");
} else {
buf.append(m.invoke(this, new Object[0]));
}
buf.append("; ");
break;
}
}
}catch (Exception x) {
//shouldn't happen
log.debug("toString() call failed", x);
}
return buf.toString();
}
public static int getPoolCounter() {
return poolCounter.get();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isJmxEnabled() {
return jmxEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public void setJmxEnabled(boolean jmxEnabled) {
this.jmxEnabled = jmxEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultReadOnly() {
return defaultReadOnly;
}
/**
* {@inheritDoc}
*/
@Override
public int getSuspectTimeout() {
return this.suspectTimeout;
}
/**
* {@inheritDoc}
*/
@Override
public void setSuspectTimeout(int seconds) {
this.suspectTimeout = seconds;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPoolSweeperEnabled() {
boolean timer = getTimeBetweenEvictionRunsMillis()>0;
boolean result = timer && (isRemoveAbandoned() && getRemoveAbandonedTimeout()>0);
result = result || (timer && getSuspectTimeout()>0);
result = result || (timer && isTestWhileIdle() && getValidationQuery()!=null);
result = result || (timer && getMinEvictableIdleTimeMillis()>0);
return result;
}
public static class InterceptorDefinition implements Serializable {
private static final long serialVersionUID = 1L;
protected String className;
protected Map<String,InterceptorProperty> properties = new HashMap<>();
protected volatile Class<?> clazz = null;
public InterceptorDefinition(String className) {
this.className = className;
}
public InterceptorDefinition(Class<?> cl) {
this(cl.getName());
clazz = cl;
}
public String getClassName() {
return className;
}
public void addProperty(String name, String value) {
InterceptorProperty p = new InterceptorProperty(name,value);
addProperty(p);
}
public void addProperty(InterceptorProperty p) {
properties.put(p.getName(), p);
}
public Map<String,InterceptorProperty> getProperties() {
return properties;
}
@SuppressWarnings("unchecked")
public Class<? extends JdbcInterceptor> getInterceptorClass() throws ClassNotFoundException {
if (clazz==null) {
if (getClassName().indexOf(".")<0) {
if (log.isDebugEnabled()) {
log.debug("Loading interceptor class:"+PoolConfiguration.PKG_PREFIX+getClassName());
}
clazz = Class.forName(PoolConfiguration.PKG_PREFIX+getClassName(), true, this.getClass().getClassLoader());
} else {
if (log.isDebugEnabled()) {
log.debug("Loading interceptor class:"+getClassName());
}
clazz = Class.forName(getClassName(), true, this.getClass().getClassLoader());
}
}
return (Class<? extends JdbcInterceptor>)clazz;
}
}
public static class InterceptorProperty implements Serializable {
private static final long serialVersionUID = 1L;
String name;
String value;
public InterceptorProperty(String name, String value) {
assert(name!=null);
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public boolean getValueAsBoolean(boolean def) {
if (value==null) return def;
if ("true".equals(value)) return true;
if ("false".equals(value)) return false;
return def;
}
public int getValueAsInt(int def) {
if (value==null) return def;
try {
int v = Integer.parseInt(value);
return v;
}catch (NumberFormatException nfe) {
return def;
}
}
public long getValueAsLong(long def) {
if (value==null) return def;
try {
return Long.parseLong(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public byte getValueAsByte(byte def) {
if (value==null) return def;
try {
return Byte.parseByte(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public short getValueAsShort(short def) {
if (value==null) return def;
try {
return Short.parseShort(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public float getValueAsFloat(float def) {
if (value==null) return def;
try {
return Float.parseFloat(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public double getValueAsDouble(double def) {
if (value==null) return def;
try {
return Double.parseDouble(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public char getValueAschar(char def) {
if (value==null) return def;
try {
return value.charAt(0);
}catch (StringIndexOutOfBoundsException nfe) {
return def;
}
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object o) {
if (o==this) return true;
if (o instanceof InterceptorProperty) {
InterceptorProperty other = (InterceptorProperty)o;
return other.name.equals(this.name);
}
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUseEquals() {
return useEquals;
}
/**
* {@inheritDoc}
*/
@Override
public void setUseEquals(boolean useEquals) {
this.useEquals = useEquals;
}
/**
* {@inheritDoc}
*/
@Override
public long getMaxAge() {
return maxAge;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxAge(long maxAge) {
this.maxAge = maxAge;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseLock() {
return useLock;
}
/**
* {@inheritDoc}
*/
@Override
public void setUseLock(boolean useLock) {
this.useLock = useLock;
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSource(Object ds) {
this.dataSource = ds;
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataSource() {
return dataSource;
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSourceJNDI(String jndiDS) {
this.dataSourceJNDI = jndiDS;
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSourceJNDI() {
return this.dataSourceJNDI;
}
public static Properties getProperties(String propText, Properties props) {
if (props==null) props = new Properties();
if (propText != null) {
try {
props.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes()));
}catch (IOException x) {
throw new RuntimeException(x);
}
}
return props;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlternateUsernameAllowed() {
return alternateUsernameAllowed;
}
/**
* {@inheritDoc}
*/
@Override
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) {
this.alternateUsernameAllowed = alternateUsernameAllowed;
}
/**
* {@inheritDoc}
*/
@Override
public void setCommitOnReturn(boolean commitOnReturn) {
this.commitOnReturn = commitOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCommitOnReturn() {
return this.commitOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public void setRollbackOnReturn(boolean rollbackOnReturn) {
this.rollbackOnReturn = rollbackOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getRollbackOnReturn() {
return this.rollbackOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) {
this.useDisposableConnectionFacade = useDisposableConnectionFacade;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseDisposableConnectionFacade() {
return useDisposableConnectionFacade;
}
/**
* {@inheritDoc}
*/
@Override
public void setLogValidationErrors(boolean logValidationErrors) {
this.logValidationErrors = logValidationErrors;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getLogValidationErrors() {
return this.logValidationErrors;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getPropagateInterruptState() {
return propagateInterruptState;
}
/**
* {@inheritDoc}
*/
@Override
public void setPropagateInterruptState(boolean propagateInterruptState) {
this.propagateInterruptState = propagateInterruptState;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
|
55,343
|
Bug 55343 Add flag to ignore exceptions while creating initial pool
|
I want my initial pool to be of some size i.e. not empty AND start even if it fails to create all or some of connections. If pool fails to create initial connections for some reason it just throws exceptions. To workaround that I have to set initial pool size to 0. It can be handy to add a flag to ignore (just log them) exceptions that occur while creating initial connections.
|
resolved fixed
|
4aa42d7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-04T08:56:24Z
| 2013-08-02T10:40:00Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java
|
/* 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.jdbc.pool.jmx;
/**
* @author Filip Hanik
*/
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolConfiguration;
import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition;
import org.apache.tomcat.jdbc.pool.PoolUtilities;
import org.apache.tomcat.jdbc.pool.Validator;
public class ConnectionPool extends NotificationBroadcasterSupport implements ConnectionPoolMBean {
/**
* logger
*/
private static final Log log = LogFactory.getLog(ConnectionPool.class);
/**
* the connection pool
*/
protected org.apache.tomcat.jdbc.pool.ConnectionPool pool = null;
/**
* sequence for JMX notifications
*/
protected AtomicInteger sequence = new AtomicInteger(0);
/**
* Listeners that are local and interested in our notifications, no need for JMX
*/
protected ConcurrentLinkedQueue<NotificationListener> listeners =
new ConcurrentLinkedQueue<>();
public ConnectionPool(org.apache.tomcat.jdbc.pool.ConnectionPool pool) {
super();
this.pool = pool;
}
public org.apache.tomcat.jdbc.pool.ConnectionPool getPool() {
return pool;
}
public PoolConfiguration getPoolProperties() {
return pool.getPoolProperties();
}
//=================================================================
// NOTIFICATION INFO
//=================================================================
public static final String NOTIFY_INIT = "INIT FAILED";
public static final String NOTIFY_CONNECT = "CONNECTION FAILED";
public static final String NOTIFY_ABANDON = "CONNECTION ABANDONED";
public static final String SLOW_QUERY_NOTIFICATION = "SLOW QUERY";
public static final String FAILED_QUERY_NOTIFICATION = "FAILED QUERY";
public static final String SUSPECT_ABANDONED_NOTIFICATION = "SUSPECT CONNETION ABANDONED";
public static final String POOL_EMPTY = "POOL EMPTY";
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
MBeanNotificationInfo[] pres = super.getNotificationInfo();
MBeanNotificationInfo[] loc = getDefaultNotificationInfo();
MBeanNotificationInfo[] aug = new MBeanNotificationInfo[pres.length + loc.length];
if (pres.length>0) System.arraycopy(pres, 0, aug, 0, pres.length);
if (loc.length >0) System.arraycopy(loc, 0, aug, pres.length, loc.length);
return aug;
}
public static MBeanNotificationInfo[] getDefaultNotificationInfo() {
String[] types = new String[] {NOTIFY_INIT, NOTIFY_CONNECT, NOTIFY_ABANDON, SLOW_QUERY_NOTIFICATION, FAILED_QUERY_NOTIFICATION, SUSPECT_ABANDONED_NOTIFICATION};
String name = Notification.class.getName();
String description = "A connection pool error condition was met.";
MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description);
return new MBeanNotificationInfo[] {info};
}
/**
* Return true if the notification was sent successfully, false otherwise.
* @param type
* @param message
* @return true if the notification succeeded
*/
public boolean notify(final String type, String message) {
try {
Notification n = new Notification(
type,
this,
sequence.incrementAndGet(),
System.currentTimeMillis(),
"["+type+"] "+message);
sendNotification(n);
for (NotificationListener listener : listeners) {
listener.handleNotification(n,this);
}
return true;
}catch (Exception x) {
if (log.isDebugEnabled()) {
log.debug("Notify failed. Type="+type+"; Message="+message,x);
}
return false;
}
}
public void addListener(NotificationListener list) {
listeners.add(list);
}
public boolean removeListener(NotificationListener list) {
return listeners.remove(list);
}
//=================================================================
// POOL STATS
//=================================================================
@Override
public int getSize() {
return pool.getSize();
}
@Override
public int getIdle() {
return pool.getIdle();
}
@Override
public int getActive() {
return pool.getActive();
}
@Override
public int getNumIdle() {
return getIdle();
}
@Override
public int getNumActive() {
return getActive();
}
@Override
public int getWaitCount() {
return pool.getWaitCount();
}
//=================================================================
// POOL OPERATIONS
//=================================================================
@Override
public void checkIdle() {
pool.checkIdle();
}
@Override
public void checkAbandoned() {
pool.checkAbandoned();
}
@Override
public void testIdle() {
pool.testAllIdle();
}
//=================================================================
// POOL PROPERTIES
//=================================================================
//=========================================================
// PROPERTIES / CONFIGURATION
//=========================================================
@Override
public String getConnectionProperties() {
return getPoolProperties().getConnectionProperties();
}
@Override
public Properties getDbProperties() {
return PoolUtilities.cloneWithoutPassword(getPoolProperties().getDbProperties());
}
@Override
public String getDefaultCatalog() {
return getPoolProperties().getDefaultCatalog();
}
@Override
public int getDefaultTransactionIsolation() {
return getPoolProperties().getDefaultTransactionIsolation();
}
@Override
public String getDriverClassName() {
return getPoolProperties().getDriverClassName();
}
@Override
public int getInitialSize() {
return getPoolProperties().getInitialSize();
}
@Override
public String getInitSQL() {
return getPoolProperties().getInitSQL();
}
@Override
public String getJdbcInterceptors() {
return getPoolProperties().getJdbcInterceptors();
}
@Override
public int getMaxActive() {
return getPoolProperties().getMaxActive();
}
@Override
public int getMaxIdle() {
return getPoolProperties().getMaxIdle();
}
@Override
public int getMaxWait() {
return getPoolProperties().getMaxWait();
}
@Override
public int getMinEvictableIdleTimeMillis() {
return getPoolProperties().getMinEvictableIdleTimeMillis();
}
@Override
public int getMinIdle() {
return getPoolProperties().getMinIdle();
}
@Override
public long getMaxAge() {
return getPoolProperties().getMaxAge();
}
@Override
public String getName() {
return this.getPoolName();
}
@Override
public int getNumTestsPerEvictionRun() {
return getPoolProperties().getNumTestsPerEvictionRun();
}
/**
* @return DOES NOT RETURN THE PASSWORD, IT WOULD SHOW UP IN JMX
*/
@Override
public String getPassword() {
return "Password not available as DataSource/JMX operation.";
}
@Override
public int getRemoveAbandonedTimeout() {
return getPoolProperties().getRemoveAbandonedTimeout();
}
@Override
public int getTimeBetweenEvictionRunsMillis() {
return getPoolProperties().getTimeBetweenEvictionRunsMillis();
}
@Override
public String getUrl() {
return getPoolProperties().getUrl();
}
@Override
public String getUsername() {
return getPoolProperties().getUsername();
}
@Override
public long getValidationInterval() {
return getPoolProperties().getValidationInterval();
}
@Override
public String getValidationQuery() {
return getPoolProperties().getValidationQuery();
}
/**
* {@inheritDoc}
*/
@Override
public String getValidatorClassName() {
return getPoolProperties().getValidatorClassName();
}
/**
* {@inheritDoc}
*/
@Override
public Validator getValidator() {
return getPoolProperties().getValidator();
}
@Override
public boolean isAccessToUnderlyingConnectionAllowed() {
return getPoolProperties().isAccessToUnderlyingConnectionAllowed();
}
@Override
public Boolean isDefaultAutoCommit() {
return getPoolProperties().isDefaultAutoCommit();
}
@Override
public Boolean isDefaultReadOnly() {
return getPoolProperties().isDefaultReadOnly();
}
@Override
public boolean isLogAbandoned() {
return getPoolProperties().isLogAbandoned();
}
@Override
public boolean isPoolSweeperEnabled() {
return getPoolProperties().isPoolSweeperEnabled();
}
@Override
public boolean isRemoveAbandoned() {
return getPoolProperties().isRemoveAbandoned();
}
@Override
public int getAbandonWhenPercentageFull() {
return getPoolProperties().getAbandonWhenPercentageFull();
}
@Override
public boolean isTestOnBorrow() {
return getPoolProperties().isTestOnBorrow();
}
@Override
public boolean isTestOnConnect() {
return getPoolProperties().isTestOnConnect();
}
@Override
public boolean isTestOnReturn() {
return getPoolProperties().isTestOnReturn();
}
@Override
public boolean isTestWhileIdle() {
return getPoolProperties().isTestWhileIdle();
}
@Override
public Boolean getDefaultAutoCommit() {
return getPoolProperties().getDefaultAutoCommit();
}
@Override
public Boolean getDefaultReadOnly() {
return getPoolProperties().getDefaultReadOnly();
}
@Override
public InterceptorDefinition[] getJdbcInterceptorsAsArray() {
return getPoolProperties().getJdbcInterceptorsAsArray();
}
@Override
public boolean getUseLock() {
return getPoolProperties().getUseLock();
}
@Override
public boolean isFairQueue() {
return getPoolProperties().isFairQueue();
}
@Override
public boolean isJmxEnabled() {
return getPoolProperties().isJmxEnabled();
}
@Override
public boolean isUseEquals() {
return getPoolProperties().isUseEquals();
}
@Override
public void setAbandonWhenPercentageFull(int percentage) {
getPoolProperties().setAbandonWhenPercentageFull(percentage);
}
@Override
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) {
getPoolProperties().setAccessToUnderlyingConnectionAllowed(accessToUnderlyingConnectionAllowed);
}
@Override
public void setDbProperties(Properties dbProperties) {
getPoolProperties().setDbProperties(dbProperties);
}
@Override
public void setDefaultReadOnly(Boolean defaultReadOnly) {
getPoolProperties().setDefaultReadOnly(defaultReadOnly);
}
@Override
public void setMaxAge(long maxAge) {
getPoolProperties().setMaxAge(maxAge);
}
@Override
public void setName(String name) {
getPoolProperties().setName(name);
}
@Override
public String getPoolName() {
return getPoolProperties().getName();
}
@Override
public void setConnectionProperties(String connectionProperties) {
getPoolProperties().setConnectionProperties(connectionProperties);
}
@Override
public void setDefaultAutoCommit(Boolean defaultAutoCommit) {
getPoolProperties().setDefaultAutoCommit(defaultAutoCommit);
}
@Override
public void setDefaultCatalog(String defaultCatalog) {
getPoolProperties().setDefaultCatalog(defaultCatalog);
}
@Override
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
getPoolProperties().setDefaultTransactionIsolation(defaultTransactionIsolation);
}
@Override
public void setDriverClassName(String driverClassName) {
getPoolProperties().setDriverClassName(driverClassName);
}
@Override
public void setFairQueue(boolean fairQueue) {
getPoolProperties().setFairQueue(fairQueue);
}
@Override
public void setInitialSize(int initialSize) {
// noop - this pool is already running
throw new UnsupportedOperationException();
}
@Override
public void setInitSQL(String initSQL) {
getPoolProperties().setInitSQL(initSQL);
}
@Override
public void setJdbcInterceptors(String jdbcInterceptors) {
// noop - this pool is already running
throw new UnsupportedOperationException();
}
@Override
public void setJmxEnabled(boolean jmxEnabled) {
// noop - this pool is already running and obviously jmx enabled
throw new UnsupportedOperationException();
}
@Override
public void setLogAbandoned(boolean logAbandoned) {
getPoolProperties().setLogAbandoned(logAbandoned);
}
@Override
public void setMaxActive(int maxActive) {
getPoolProperties().setMaxActive(maxActive);
}
@Override
public void setMaxIdle(int maxIdle) {
getPoolProperties().setMaxIdle(maxIdle);
}
@Override
public void setMaxWait(int maxWait) {
getPoolProperties().setMaxWait(maxWait);
}
@Override
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setMinIdle(int minIdle) {
getPoolProperties().setMinIdle(minIdle);
}
@Override
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
getPoolProperties().setNumTestsPerEvictionRun(numTestsPerEvictionRun);
}
@Override
public void setPassword(String password) {
getPoolProperties().setPassword(password);
}
@Override
public void setRemoveAbandoned(boolean removeAbandoned) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setRemoveAbandoned(removeAbandoned);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setRemoveAbandonedTimeout(removeAbandonedTimeout);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setTestOnBorrow(boolean testOnBorrow) {
getPoolProperties().setTestOnBorrow(testOnBorrow);
}
@Override
public void setTestOnConnect(boolean testOnConnect) {
getPoolProperties().setTestOnConnect(testOnConnect);
}
@Override
public void setTestOnReturn(boolean testOnReturn) {
getPoolProperties().setTestOnReturn(testOnReturn);
}
@Override
public void setTestWhileIdle(boolean testWhileIdle) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setTestWhileIdle(testWhileIdle);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setUrl(String url) {
getPoolProperties().setUrl(url);
}
@Override
public void setUseEquals(boolean useEquals) {
getPoolProperties().setUseEquals(useEquals);
}
@Override
public void setUseLock(boolean useLock) {
getPoolProperties().setUseLock(useLock);
}
@Override
public void setUsername(String username) {
getPoolProperties().setUsername(username);
}
@Override
public void setValidationInterval(long validationInterval) {
getPoolProperties().setValidationInterval(validationInterval);
}
@Override
public void setValidationQuery(String validationQuery) {
getPoolProperties().setValidationQuery(validationQuery);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidatorClassName(String className) {
getPoolProperties().setValidatorClassName(className);
}
/**
* {@inheritDoc}
*/
@Override
public int getSuspectTimeout() {
return getPoolProperties().getSuspectTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public void setSuspectTimeout(int seconds) {
getPoolProperties().setSuspectTimeout(seconds);
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSource(Object ds) {
getPoolProperties().setDataSource(ds);
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataSource() {
return getPoolProperties().getDataSource();
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSourceJNDI(String jndiDS) {
getPoolProperties().setDataSourceJNDI(jndiDS);
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSourceJNDI() {
return getPoolProperties().getDataSourceJNDI();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlternateUsernameAllowed() {
return getPoolProperties().isAlternateUsernameAllowed();
}
/**
* {@inheritDoc}
*/
@Override
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) {
getPoolProperties().setAlternateUsernameAllowed(alternateUsernameAllowed);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidator(Validator validator) {
getPoolProperties().setValidator(validator);
}
/**
* {@inheritDoc}
*/
@Override
public void setCommitOnReturn(boolean commitOnReturn) {
getPoolProperties().setCommitOnReturn(commitOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCommitOnReturn() {
return getPoolProperties().getCommitOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setRollbackOnReturn(boolean rollbackOnReturn) {
getPoolProperties().setRollbackOnReturn(rollbackOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getRollbackOnReturn() {
return getPoolProperties().getRollbackOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) {
getPoolProperties().setUseDisposableConnectionFacade(useDisposableConnectionFacade);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseDisposableConnectionFacade() {
return getPoolProperties().getUseDisposableConnectionFacade();
}
/**
* {@inheritDoc}
*/
@Override
public void setLogValidationErrors(boolean logValidationErrors) {
getPoolProperties().setLogValidationErrors(logValidationErrors);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getLogValidationErrors() {
return getPoolProperties().getLogValidationErrors();
}
/**
* {@inheritDoc}
*/
@Override
public boolean getPropagateInterruptState() {
return getPoolProperties().getPropagateInterruptState();
}
/**
* {@inheritDoc}
*/
@Override
public void setPropagateInterruptState(boolean propagateInterruptState) {
getPoolProperties().setPropagateInterruptState(propagateInterruptState);
}
/**
* {@inheritDoc}
*/
@Override
public void purge() {
pool.purge();
}
/**
* {@inheritDoc}
*/
@Override
public void purgeOnReturn() {
pool.purgeOnReturn();
}
}
|
55,527
|
Bug 55527 JSSESocketFactory conditionally converts alias to lower case; condition is unwise
|
JSSESocketFactory conditionally converts the alias to lower case. The condition is coded as follows: private static final String defaultKeystoreType = "JKS"; ... if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } If the intention is to downcase only JKS store aliases, then the comparison should be made with "JKS", not a constant that happens to contain "JKS" at present. Using a specific comparator would both clarify the code and protect against a possible change to the default (albeit very unlikely).
|
resolved fixed
|
f126b5a
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-05T10:36:34Z
| 2013-09-05T14:06:40Z
|
java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java
|
/*
* 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.net.jsse;
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.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
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.SSLException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.Constants;
import org.apache.tomcat.util.net.SSLUtil;
import org.apache.tomcat.util.net.ServerSocketFactory;
import org.apache.tomcat.util.res.StringManager;
/**
* SSL server socket factory. It <b>requires</b> a valid RSA key and
* JSSE.<br/>
* keytool -genkey -alias tomcat -keyalg RSA</br>
* Use "changeit" as password (this is the default we use).
*
* @author Harish Prabandham
* @author Costin Manolache
* @author Stefan Freyr Stefansson
* @author EKR -- renamed to JSSESocketFactory
* @author Jan Luehe
* @author Bill Barker
*/
public class JSSESocketFactory implements ServerSocketFactory, SSLUtil {
private static final org.apache.juli.logging.Log log =
org.apache.juli.logging.LogFactory.getLog(JSSESocketFactory.class);
private static final StringManager sm =
StringManager.getManager("org.apache.tomcat.util.net.jsse.res");
private static final boolean RFC_5746_SUPPORTED;
private static final String[] DEFAULT_SERVER_PROTOCOLS;
private static final String[] DEAFULT_SERVER_CIPHER_SUITES;
// Defaults - made public where re-used
private static final String defaultProtocol = "TLS";
private static final String defaultKeystoreType = "JKS";
private static final String defaultKeystoreFile
= System.getProperty("user.home") + "/.keystore";
private static final int defaultSessionCacheSize = 0;
private static final int defaultSessionTimeout = 86400;
private static final String ALLOW_ALL_SUPPORTED_CIPHERS = "ALL";
public static final String DEFAULT_KEY_PASS = "changeit";
static {
boolean result = false;
SSLContext context;
String[] ciphers = null;
String[] protocols = null;
try {
context = SSLContext.getInstance("TLS");
context.init(null, null, null);
SSLServerSocketFactory ssf = context.getServerSocketFactory();
String supportedCiphers[] = ssf.getSupportedCipherSuites();
for (String cipher : supportedCiphers) {
if ("TLS_EMPTY_RENEGOTIATION_INFO_SCSV".equals(cipher)) {
result = true;
break;
}
}
// There is no API to obtain the default server protocols and cipher
// suites. Having inspected the OpenJDK code there the same results
// can be achieved via the standard API but there is no guarantee
// that every JVM implementation determines the defaults the same
// way. Therefore the defaults are determined by creating a server
// socket and requested the configured values.
SSLServerSocket socket = (SSLServerSocket) ssf.createServerSocket();
ciphers = socket.getEnabledCipherSuites();
protocols = socket.getEnabledProtocols();
} catch (NoSuchAlgorithmException e) {
// Assume no RFC 5746 support
} catch (KeyManagementException e) {
// Assume no RFC 5746 support
} catch (IOException e) {
// Unable to determine default ciphers/protocols so use none
}
RFC_5746_SUPPORTED = result;
DEAFULT_SERVER_CIPHER_SUITES = ciphers;
DEFAULT_SERVER_PROTOCOLS = protocols;
}
private AbstractEndpoint<?> endpoint;
protected SSLServerSocketFactory sslProxy = null;
protected String[] enabledCiphers;
protected String[] enabledProtocols;
protected boolean allowUnsafeLegacyRenegotiation = false;
/**
* 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 (AbstractEndpoint<?> endpoint) {
this.endpoint = endpoint;
}
@Override
public ServerSocket createSocket (int port)
throws IOException
{
init();
ServerSocket socket = sslProxy.createServerSocket(port);
initServerSocket(socket);
return socket;
}
@Override
public ServerSocket createSocket (int port, int backlog)
throws IOException
{
init();
ServerSocket socket = sslProxy.createServerSocket(port, backlog);
initServerSocket(socket);
return socket;
}
@Override
public ServerSocket createSocket (int port, int backlog,
InetAddress ifAddress)
throws IOException
{
init();
ServerSocket socket = sslProxy.createServerSocket(port, backlog,
ifAddress);
initServerSocket(socket);
return socket;
}
@Override
public Socket acceptSocket(ServerSocket socket)
throws IOException
{
SSLSocket asock = null;
try {
asock = (SSLSocket)socket.accept();
} catch (SSLException e){
throw new SocketException("SSL handshake error" + e.toString());
}
return asock;
}
@Override
public void handshake(Socket sock) throws IOException {
// We do getSession instead of startHandshake() so we can call this multiple times
SSLSession session = ((SSLSocket)sock).getSession();
if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL"))
throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL");
if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) {
// Prevent further handshakes by removing all cipher suites
((SSLSocket) sock).setEnabledCipherSuites(new String[0]);
}
}
@Override
public String[] getEnableableCiphers(SSLContext context) {
String requestedCiphersStr = endpoint.getCiphers();
if (ALLOW_ALL_SUPPORTED_CIPHERS.equals(requestedCiphersStr)) {
return context.getSupportedSSLParameters().getCipherSuites();
}
if ((requestedCiphersStr == null)
|| (requestedCiphersStr.trim().length() == 0)) {
return DEAFULT_SERVER_CIPHER_SUITES;
}
List<String> requestedCiphers = new ArrayList<>();
for (String rc : requestedCiphersStr.split(",")) {
final String cipher = rc.trim();
if (cipher.length() > 0) {
requestedCiphers.add(cipher);
}
}
if (requestedCiphers.isEmpty()) {
return DEAFULT_SERVER_CIPHER_SUITES;
}
List<String> ciphers = new ArrayList<>(requestedCiphers);
ciphers.retainAll(Arrays.asList(context.getSupportedSSLParameters()
.getCipherSuites()));
if (ciphers.isEmpty()) {
log.warn(sm.getString("jsse.requested_ciphers_not_supported",
requestedCiphersStr));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jsse.enableable_ciphers", ciphers));
if (ciphers.size() != requestedCiphers.size()) {
List<String> skipped = new ArrayList<>(requestedCiphers);
skipped.removeAll(ciphers);
log.debug(sm.getString("jsse.unsupported_ciphers", skipped));
}
}
return ciphers.toArray(new String[ciphers.size()]);
}
public String[] getEnabledCiphers() {
return enabledCiphers;
}
/*
* Gets the SSL server's keystore password.
*/
protected String getKeystorePassword() {
String keystorePass = endpoint.getKeystorePass();
if (keystorePass == null) {
keystorePass = endpoint.getKeyPass();
}
if (keystorePass == null) {
keystorePass = DEFAULT_KEY_PASS;
}
return keystorePass;
}
/*
* Gets the SSL server's keystore.
*/
protected KeyStore getKeystore(String type, String provider, String pass)
throws IOException {
String keystoreFile = endpoint.getKeystoreFile();
if (keystoreFile == null)
keystoreFile = defaultKeystoreFile;
return getStore(type, provider, keystoreFile, pass);
}
/*
* Gets the SSL server's truststore.
*/
protected KeyStore getTrustStore(String keystoreType,
String keystoreProvider) throws IOException {
KeyStore trustStore = null;
String truststoreFile = endpoint.getTruststoreFile();
if(truststoreFile == null) {
truststoreFile = System.getProperty("javax.net.ssl.trustStore");
}
if(log.isDebugEnabled()) {
log.debug("Truststore = " + truststoreFile);
}
String truststorePassword = endpoint.getTruststorePass();
if( truststorePassword == null) {
truststorePassword =
System.getProperty("javax.net.ssl.trustStorePassword");
}
if(log.isDebugEnabled()) {
log.debug("TrustPass = " + truststorePassword);
}
String truststoreType = endpoint.getTruststoreType();
if( truststoreType == null) {
truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
}
if(truststoreType == null) {
truststoreType = keystoreType;
}
if(log.isDebugEnabled()) {
log.debug("trustType = " + truststoreType);
}
String truststoreProvider = endpoint.getTruststoreProvider();
if( truststoreProvider == null) {
truststoreProvider =
System.getProperty("javax.net.ssl.trustStoreProvider");
}
if (truststoreProvider == null) {
truststoreProvider = keystoreProvider;
}
if(log.isDebugEnabled()) {
log.debug("trustProvider = " + truststoreProvider);
}
if (truststoreFile != null){
try {
trustStore = getStore(truststoreType, truststoreProvider,
truststoreFile, truststorePassword);
} catch (IOException ioe) {
Throwable cause = ioe.getCause();
if (cause instanceof UnrecoverableKeyException) {
// Log a warning we had a password issue
log.warn(sm.getString("jsse.invalid_truststore_password"),
cause);
// Re-try
trustStore = getStore(truststoreType, truststoreProvider,
truststoreFile, null);
} else {
// Something else went wrong - re-throw
throw ioe;
}
}
}
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(
Constants.CATALINA_BASE_PROP), path);
}
istream = new FileInputStream(keyStoreFile);
}
char[] storePass = null;
if (pass != null && !"".equals(pass)) {
storePass = pass.toCharArray();
}
ks.load(istream, storePass);
} catch (FileNotFoundException fnfe) {
log.error(sm.getString("jsse.keystore_load_failed", type, path,
fnfe.getMessage()), fnfe);
throw fnfe;
} catch (IOException ioe) {
// May be expected when working with a trust store
// Re-throw. Caller will catch and log as required
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 = endpoint.getClientAuth();
if("true".equalsIgnoreCase(clientAuthStr) ||
"yes".equalsIgnoreCase(clientAuthStr)) {
requireClientAuth = true;
} else if("want".equalsIgnoreCase(clientAuthStr)) {
wantClientAuth = true;
}
SSLContext context = createSSLContext();
context.init(getKeyManagers(), getTrustManagers(), null);
// Configure SSL session cache
SSLSessionContext sessionContext =
context.getServerSessionContext();
if (sessionContext != null) {
configureSessionContext(sessionContext);
}
// create proxy
sslProxy = context.getServerSocketFactory();
// Determine which cipher suites to enable
enabledCiphers = getEnableableCiphers(context);
enabledProtocols = getEnableableProtocols(context);
allowUnsafeLegacyRenegotiation = "true".equals(
endpoint.getAllowUnsafeLegacyRenegotiation());
// Check the SSL config is OK
checkConfig();
} catch(Exception e) {
if( e instanceof IOException )
throw (IOException)e;
throw new IOException(e.getMessage(), e);
}
}
@Override
public SSLContext createSSLContext() throws Exception {
// SSL protocol variant (e.g., TLS, SSL v3, etc.)
String protocol = endpoint.getSslProtocol();
if (protocol == null) {
protocol = defaultProtocol;
}
SSLContext context = SSLContext.getInstance(protocol);
return context;
}
@Override
public KeyManager[] getKeyManagers() throws Exception {
String keystoreType = endpoint.getKeystoreType();
if (keystoreType == null) {
keystoreType = defaultKeystoreType;
}
String algorithm = endpoint.getAlgorithm();
if (algorithm == null) {
algorithm = KeyManagerFactory.getDefaultAlgorithm();
}
return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(),
algorithm, endpoint.getKeyAlias());
}
@Override
public TrustManager[] getTrustManagers() throws Exception {
String truststoreType = endpoint.getTruststoreType();
if (truststoreType == null) {
truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
}
if (truststoreType == null) {
truststoreType = endpoint.getKeystoreType();
}
if (truststoreType == null) {
truststoreType = defaultKeystoreType;
}
String algorithm = endpoint.getTruststoreAlgorithm();
if (algorithm == null) {
algorithm = TrustManagerFactory.getDefaultAlgorithm();
}
return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(),
algorithm);
}
@Override
public void configureSessionContext(SSLSessionContext sslSessionContext) {
int sessionCacheSize;
if (endpoint.getSessionCacheSize() != null) {
sessionCacheSize = Integer.parseInt(
endpoint.getSessionCacheSize());
} else {
sessionCacheSize = defaultSessionCacheSize;
}
int sessionTimeout;
if (endpoint.getSessionTimeout() != null) {
sessionTimeout = Integer.parseInt(endpoint.getSessionTimeout());
} else {
sessionTimeout = defaultSessionTimeout;
}
sslSessionContext.setSessionCacheSize(sessionCacheSize);
sslSessionContext.setSessionTimeout(sessionTimeout);
}
/**
* Gets the initialized key managers.
*/
protected KeyManager[] getKeyManagers(String keystoreType,
String keystoreProvider,
String algorithm,
String keyAlias)
throws Exception {
KeyManager[] kms = null;
String keystorePass = getKeystorePassword();
KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
throw new IOException(
sm.getString("jsse.alias_no_key_entry", keyAlias));
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
String keyPass = endpoint.getKeyPass();
if (keyPass == null) {
keyPass = keystorePass;
}
kmf.init(ks, keyPass.toCharArray());
kms = kmf.getKeyManagers();
if (keyAlias != null) {
String alias = keyAlias;
if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
alias = alias.toLowerCase(Locale.ENGLISH);
}
for(int i=0; i<kms.length; i++) {
kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
}
}
return kms;
}
/**
* Gets the initialized trust managers.
*/
protected TrustManager[] getTrustManagers(String keystoreType,
String keystoreProvider, String algorithm)
throws Exception {
String crlf = endpoint.getCrlFile();
String className = endpoint.getTrustManagerClassName();
if(className != null && className.length() > 0) {
ClassLoader classLoader = getClass().getClassLoader();
Class<?> clazz = classLoader.loadClass(className);
if(!(TrustManager.class.isAssignableFrom(clazz))){
throw new InstantiationException(sm.getString(
"jsse.invalidTrustManagerClassName", className));
}
Object trustManagerObject = clazz.newInstance();
TrustManager trustManager = (TrustManager) trustManagerObject;
return new TrustManager[]{ trustManager };
}
TrustManager[] tms = null;
KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider);
if (trustStore != null || endpoint.getTrustManagerClassName() != null) {
if (crlf == null) {
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(algorithm);
tmf.init(trustStore);
tms = tmf.getTrustManagers();
} else {
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(algorithm);
CertPathParameters params =
getParameters(algorithm, crlf, 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<? extends CRL> crls = getCRLs(crlf);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
xparams.addCertStore(store);
xparams.setRevocationEnabled(true);
String trustLength = endpoint.getTrustMaxCertLength();
if(trustLength != null) {
try {
xparams.setMaxPathLength(Integer.parseInt(trustLength));
} catch(Exception ex) {
log.warn("Bad maxCertLength: "+trustLength);
}
}
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(Constants.CATALINA_BASE_PROP), 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) {
// Ignore
}
}
}
return crls;
}
@Override
public String[] getEnableableProtocols(SSLContext context) {
String[] requestedProtocols = endpoint.getSslEnabledProtocolsArray();
if ((requestedProtocols == null) || (requestedProtocols.length == 0)) {
return DEFAULT_SERVER_PROTOCOLS;
}
List<String> protocols = new ArrayList<>(
Arrays.asList(requestedProtocols));
protocols.retainAll(Arrays.asList(context.getSupportedSSLParameters()
.getProtocols()));
if (protocols.isEmpty()) {
log.warn(sm.getString("jsse.requested_protocols_not_supported",
Arrays.asList(requestedProtocols)));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jsse.enableable_protocols", protocols));
if (protocols.size() != requestedProtocols.length) {
List<String> skipped = new ArrayList<>(
Arrays.asList(requestedProtocols));
skipped.removeAll(protocols);
log.debug(sm.getString("jsse.unsupported_protocols", skipped));
}
}
return protocols.toArray(new String[protocols.size()]);
}
/**
* Configure Client authentication for this version of JSSE. The
* JSSE included in Java 1.4 supports the 'want' value. Prior
* versions of JSSE will treat 'want' as 'false'.
* @param socket the SSLServerSocket
*/
protected void configureClientAuth(SSLServerSocket socket){
if (wantClientAuth){
socket.setWantClientAuth(wantClientAuth);
} else {
socket.setNeedClientAuth(requireClientAuth);
}
}
/**
* Configures the given SSL server socket with the requested cipher suites,
* protocol versions, and need for client authentication
*/
private void initServerSocket(ServerSocket ssocket) {
SSLServerSocket socket = (SSLServerSocket) ssocket;
socket.setEnabledCipherSuites(enabledCiphers);
socket.setEnabledProtocols(enabledProtocols);
// we don't know if client auth is needed -
// after parsing the request we may re-handshake
configureClientAuth(socket);
}
/**
* Checks that the certificate is compatible with the enabled cipher suites.
* If we don't check now, the JIoEndpoint can enter a nasty logging loop.
* See bug 45528.
*/
private void checkConfig() throws IOException {
// Create an unbound server socket
ServerSocket socket = sslProxy.createServerSocket();
initServerSocket(socket);
try {
// Set the timeout to 1ms as all we care about is if it throws an
// SSLException on accept.
socket.setSoTimeout(1);
socket.accept();
// Will never get here - no client can connect to an unbound port
} catch (SSLException ssle) {
// SSL configuration is invalid. Possibly cert doesn't match ciphers
IOException ioe = new IOException(sm.getString(
"jsse.invalid_ssl_conf", ssle.getMessage()));
ioe.initCause(ssle);
throw ioe;
} catch (Exception e) {
/*
* Possible ways of getting here
* socket.accept() throws a SecurityException
* socket.setSoTimeout() throws a SocketException
* socket.accept() throws some other exception (after a JDK change)
* In these cases the test won't work so carry on - essentially
* the behaviour before this patch
* socket.accept() throws a SocketTimeoutException
* In this case all is well so carry on
*/
} finally {
// Should be open here but just in case
if (!socket.isClosed()) {
socket.close();
}
}
}
}
|
55,521
|
Bug 55521 Race Condition in HttpSession#invalidate() / HttpServletRequest#getSession(boolean)
| null |
resolved fixed
|
262c069
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-05T15:42:48Z
| 2013-09-04T13:06:40Z
|
java/org/apache/catalina/ha/session/DeltaSession.java
|
/*
* 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.ha.session;
import java.io.Externalizable;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.catalina.Manager;
import org.apache.catalina.SessionListener;
import org.apache.catalina.ha.CatalinaCluster;
import org.apache.catalina.ha.ClusterManager;
import org.apache.catalina.ha.ClusterMessage;
import org.apache.catalina.ha.ClusterSession;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.session.ManagerBase;
import org.apache.catalina.session.StandardManager;
import org.apache.catalina.session.StandardSession;
import org.apache.catalina.tribes.io.ReplicationStream;
import org.apache.catalina.tribes.tipis.ReplicatedMapEntry;
import org.apache.tomcat.util.res.StringManager;
/**
*
* Similar to the StandardSession except that this session will keep
* track of deltas during a request.
*
* @author Filip Hanik
* @version $Id$
*/
public class DeltaSession extends StandardSession implements Externalizable,ClusterSession,ReplicatedMapEntry {
public static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(DeltaSession.class);
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(Constants.Package);
// ----------------------------------------------------- Instance Variables
/**
* only the primary session will expire, or be able to expire due to
* inactivity. This is set to false as soon as I receive this session over
* the wire in a session message. That means that someone else has made a
* request on another server.
*/
private transient boolean isPrimarySession = true;
/**
* The delta request contains all the action info
*
*/
private transient DeltaRequest deltaRequest = null;
/**
* Last time the session was replicated, used for distributed expiring of
* session
*/
private transient long lastTimeReplicated = System.currentTimeMillis();
protected final Lock diffLock = new ReentrantReadWriteLock().writeLock();
private long version;
// ----------------------------------------------------------- Constructors
public DeltaSession() {
this(null);
}
/**
* Construct a new Session associated with the specified Manager.
*
* @param manager
* The manager with which this Session is associated
*/
public DeltaSession(Manager manager) {
super(manager);
this.resetDeltaRequest();
}
// ----------------------------------------------------- ReplicatedMapEntry
/**
* Has the object changed since last replication
* and is not in a locked state
* @return boolean
*/
@Override
public boolean isDirty() {
return getDeltaRequest().getSize()>0;
}
/**
* If this returns true, the map will extract the diff using getDiff()
* Otherwise it will serialize the entire object.
* @return boolean
*/
@Override
public boolean isDiffable() {
return true;
}
/**
* Returns a diff and sets the dirty map to false
* @return byte[]
* @throws IOException
*/
@Override
public byte[] getDiff() throws IOException {
try{
lock();
return getDeltaRequest().serialize();
}finally{
unlock();
}
}
public ClassLoader[] getClassLoaders() {
if ( manager instanceof BackupManager ) return ((BackupManager)manager).getClassLoaders();
else if ( manager instanceof ClusterManagerBase ) return ((ClusterManagerBase)manager).getClassLoaders();
else if ( manager instanceof StandardManager ) {
StandardManager sm = (StandardManager)manager;
return ClusterManagerBase.getClassLoaders(sm.getContext());
} else if ( manager instanceof ManagerBase ) {
ManagerBase mb = (ManagerBase)manager;
return ClusterManagerBase.getClassLoaders(mb.getContext());
}//end if
return null;
}
/**
* Applies a diff to an existing object.
* @param diff byte[]
* @param offset int
* @param length int
* @throws IOException
*/
@Override
public void applyDiff(byte[] diff, int offset, int length) throws IOException, ClassNotFoundException {
try {
lock();
ReplicationStream stream = ( (ClusterManager) getManager()).getReplicationStream(diff, offset, length);
ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
try {
ClassLoader[] loaders = getClassLoaders();
if (loaders != null && loaders.length > 0)
Thread.currentThread().setContextClassLoader(loaders[0]);
getDeltaRequest().readExternal(stream);
getDeltaRequest().execute(this, ((ClusterManager)getManager()).isNotifyListenersOnReplication());
} finally {
Thread.currentThread().setContextClassLoader(contextLoader);
}
}finally {
unlock();
}
}
/**
* Resets the current diff state and resets the dirty flag
*/
@Override
public void resetDiff() {
resetDeltaRequest();
}
/**
* Lock during serialization
*/
@Override
public void lock() {
diffLock.lock();
}
/**
* Unlock after serialization
*/
@Override
public void unlock() {
diffLock.unlock();
}
@Override
public void setOwner(Object owner) {
if ( owner instanceof ClusterManager && getManager()==null) {
ClusterManager cm = (ClusterManager)owner;
this.setManager(cm);
this.setValid(true);
this.setPrimarySession(false);
this.access();
this.resetDeltaRequest();
this.endAccess();
}
}
/**
* If this returns true, to replicate that an object has been accessed
* @return boolean
*/
@Override
public boolean isAccessReplicate() {
long replDelta = System.currentTimeMillis() - getLastTimeReplicated();
if (maxInactiveInterval >=0 && replDelta > (maxInactiveInterval * 1000)) {
return true;
}
return false;
}
/**
* Access to an existing object.
*/
@Override
public void accessEntry() {
this.access();
this.setPrimarySession(false);
this.endAccess();
}
// ----------------------------------------------------- Session Properties
/**
* returns true if this session is the primary session, if that is the case,
* the manager can expire it upon timeout.
*/
@Override
public boolean isPrimarySession() {
return isPrimarySession;
}
/**
* Sets whether this is the primary session or not.
*
* @param primarySession
* Flag value
*/
@Override
public void setPrimarySession(boolean primarySession) {
this.isPrimarySession = primarySession;
}
/**
* {@inheritDoc}
*/
@Override
public void setId(String id, boolean notify) {
super.setId(id, notify);
resetDeltaRequest();
}
/**
* Set the session identifier for this session.
*
* @param id
* The new session identifier
*/
@Override
public void setId(String id) {
super.setId(id, true);
resetDeltaRequest();
}
@Override
public void setMaxInactiveInterval(int interval) {
this.setMaxInactiveInterval(interval,true);
}
public void setMaxInactiveInterval(int interval, boolean addDeltaRequest) {
super.maxInactiveInterval = interval;
if (addDeltaRequest && (deltaRequest != null)) {
try {
lock();
deltaRequest.setMaxInactiveInterval(interval);
}finally{
unlock();
}
}
}
/**
* Set the <code>isNew</code> flag for this session.
*
* @param isNew
* The new value for the <code>isNew</code> flag
*/
@Override
public void setNew(boolean isNew) {
setNew(isNew, true);
}
public void setNew(boolean isNew, boolean addDeltaRequest) {
super.setNew(isNew);
if (addDeltaRequest && (deltaRequest != null)){
try {
lock();
deltaRequest.setNew(isNew);
}finally{
unlock();
}
}
}
/**
* Set the authenticated Principal that is associated with this Session.
* This provides an <code>Authenticator</code> with a means to cache a
* previously authenticated Principal, and avoid potentially expensive
* <code>Realm.authenticate()</code> calls on every request.
*
* @param principal
* The new Principal, or <code>null</code> if none
*/
@Override
public void setPrincipal(Principal principal) {
setPrincipal(principal, true);
}
public void setPrincipal(Principal principal, boolean addDeltaRequest) {
try {
lock();
super.setPrincipal(principal);
if (addDeltaRequest && (deltaRequest != null))
deltaRequest.setPrincipal(principal);
} finally {
unlock();
}
}
/**
* Set the authentication type used to authenticate our cached
* Principal, if any.
*
* @param authType The new cached authentication type
*/
@Override
public void setAuthType(String authType) {
setAuthType(authType, true);
}
public void setAuthType(String authType, boolean addDeltaRequest) {
try {
lock();
super.setAuthType(authType);
if (addDeltaRequest && (deltaRequest != null))
deltaRequest.setAuthType(authType);
} finally {
unlock();
}
}
/**
* Return the <code>isValid</code> flag for this session.
*/
@Override
public boolean isValid() {
if (this.expiring) {
return true;
}
if (!this.isValid) {
return false;
}
if (ACTIVITY_CHECK && accessCount.get() > 0) {
return true;
}
if (maxInactiveInterval > 0) {
long timeNow = System.currentTimeMillis();
int timeIdle;
if (LAST_ACCESS_AT_START) {
timeIdle = (int) ((timeNow - lastAccessedTime) / 1000L);
} else {
timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L);
}
if (isPrimarySession()) {
if (timeIdle >= maxInactiveInterval) {
expire(true);
}
} else {
if (timeIdle >= (2 * maxInactiveInterval)) {
//if the session has been idle twice as long as allowed,
//the primary session has probably crashed, and no other
//requests are coming in. that is why we do this. otherwise
//we would have a memory leak
expire(true, false);
}
}
}
return (this.isValid);
}
/**
* End the access and register to ReplicationValve (crossContext support)
*/
@Override
public void endAccess() {
super.endAccess() ;
if(manager instanceof DeltaManager) {
((DeltaManager)manager).registerSessionAtReplicationValve(this);
}
}
// ------------------------------------------------- Session Public Methods
/**
* Perform the internal processing required to invalidate this session,
* without triggering an exception if the session has already expired.
*
* @param notify
* Should we notify listeners about the demise of this session?
*/
@Override
public void expire(boolean notify) {
expire(notify, true);
}
public void expire(boolean notify, boolean notifyCluster) {
if (expiring)
return;
String expiredId = getIdInternal();
if(notifyCluster && expiredId != null && manager != null &&
manager instanceof DeltaManager) {
DeltaManager dmanager = (DeltaManager)manager;
CatalinaCluster cluster = dmanager.getCluster();
ClusterMessage msg = dmanager.requestCompleted(expiredId, true);
if (msg != null) {
cluster.send(msg);
}
}
super.expire(notify);
if (notifyCluster) {
if (log.isDebugEnabled())
log.debug(sm.getString("deltaSession.notifying",
((ClusterManager)manager).getName(),
Boolean.valueOf(isPrimarySession()),
expiredId));
if ( manager instanceof DeltaManager ) {
( (DeltaManager) manager).sessionExpired(expiredId);
}
}
}
/**
* Release all object references, and initialize instance variables, in
* preparation for reuse of this object.
*/
@Override
public void recycle() {
try {
lock();
super.recycle();
deltaRequest.clear();
}finally{
unlock();
}
}
/**
* Return a string representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("DeltaSession[");
sb.append(id);
sb.append("]");
return (sb.toString());
}
// ------------------------------------------------ Session Package Methods
@Override
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
try {
lock();
readObjectData(in);
}finally{
unlock();
}
}
/**
* Read a serialized version of the contents of this session object from the
* specified object input stream, without requiring that the StandardSession
* itself have been serialized.
*
* @param stream
* The object input stream to read from
*
* @exception ClassNotFoundException
* if an unknown class is specified
* @exception IOException
* if an input/output error occurs
*/
@Override
public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException {
doReadObject((ObjectInput)stream);
}
public void readObjectData(ObjectInput stream) throws ClassNotFoundException, IOException {
doReadObject(stream);
}
/**
* Write a serialized version of the contents of this session object to the
* specified object output stream, without requiring that the
* StandardSession itself have been serialized.
*
* @param stream
* The object output stream to write to
*
* @exception IOException
* if an input/output error occurs
*/
@Override
public void writeObjectData(ObjectOutputStream stream) throws IOException {
writeObjectData((ObjectOutput)stream);
}
public void writeObjectData(ObjectOutput stream) throws IOException {
doWriteObject(stream);
}
public void resetDeltaRequest() {
try {
lock();
if (deltaRequest == null) {
deltaRequest = new DeltaRequest(getIdInternal(), false);
} else {
deltaRequest.reset();
deltaRequest.setSessionId(getIdInternal());
}
}finally{
unlock();
}
}
public DeltaRequest getDeltaRequest() {
if (deltaRequest == null) resetDeltaRequest();
return deltaRequest;
}
// ------------------------------------------------- HttpSession Properties
// ----------------------------------------------HttpSession Public Methods
/**
* Check whether the Object can be distributed.
* The object is always distributable, if the cluster manager
* decides to never distribute it.
* @param name The name of the attribute to check
* @param value The value of the attribute to check
* @return true if the attribute is distributable, false otherwise
*/
@Override
protected boolean isAttributeDistributable(String name, Object value) {
if (manager instanceof ClusterManagerBase &&
!((ClusterManagerBase)manager).willAttributeDistribute(name))
return true;
return super.isAttributeDistributable(name, value);
}
/**
* Exclude attributes from replication.
* @param name the attribute's name
* @return true if attribute should not be replicated
*/
@Override
protected boolean exclude(String name) {
if (super.exclude(name))
return true;
if (manager instanceof ClusterManagerBase)
return !((ClusterManagerBase)manager).willAttributeDistribute(name);
return false;
}
/**
* Remove the object bound with the specified name from this session. If the
* session does not have an object bound with this name, this method does
* nothing.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueUnbound()</code> on the object.
*
* @param name
* Name of the object to remove from this session.
* @param notify
* Should we notify interested listeners that this attribute is
* being removed?
*
* @exception IllegalStateException
* if this method is called on an invalidated session
*/
@Override
public void removeAttribute(String name, boolean notify) {
removeAttribute(name, notify, true);
}
public void removeAttribute(String name, boolean notify,boolean addDeltaRequest) {
// Validate our current state
if (!isValid()) throw new IllegalStateException(sm.getString("standardSession.removeAttribute.ise"));
removeAttributeInternal(name, notify, addDeltaRequest);
}
/**
* Bind an object to this session, using the specified name. If an object of
* the same name is already bound to this session, the object is replaced.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueBound()</code> on the object.
*
* @param name
* Name to which the object is bound, cannot be null
* @param value
* Object to be bound, cannot be null
*
* @exception IllegalArgumentException
* if an attempt is made to add a non-serializable object in
* an environment marked distributable.
* @exception IllegalStateException
* if this method is called on an invalidated session
*/
@Override
public void setAttribute(String name, Object value) {
setAttribute(name, value, true, true);
}
public void setAttribute(String name, Object value, boolean notify,boolean addDeltaRequest) {
// Name cannot be null
if (name == null) throw new IllegalArgumentException(sm.getString("standardSession.setAttribute.namenull"));
// Null value is the same as removeAttribute()
if (value == null) {
removeAttribute(name);
return;
}
try {
lock();
super.setAttribute(name,value, notify);
if (addDeltaRequest && deltaRequest != null && !exclude(name)) {
deltaRequest.setAttribute(name, value);
}
} finally {
unlock();
}
}
// -------------------------------------------- HttpSession Private Methods
/**
* Read a serialized version of this session object from the specified
* object input stream.
* <p>
* <b>IMPLEMENTATION NOTE </b>: The reference to the owning Manager is not
* restored by this method, and must be set explicitly.
*
* @param stream
* The input stream to read from
*
* @exception ClassNotFoundException
* if an unknown class is specified
* @exception IOException
* if an input/output error occurs
*/
@Override
protected void doReadObject(ObjectInputStream stream) throws ClassNotFoundException, IOException {
doReadObject((ObjectInput)stream);
}
private void doReadObject(ObjectInput stream) throws ClassNotFoundException, IOException {
// Deserialize the scalar instance variables (except Manager)
authType = null; // Transient only
creationTime = ( (Long) stream.readObject()).longValue();
lastAccessedTime = ( (Long) stream.readObject()).longValue();
maxInactiveInterval = ( (Integer) stream.readObject()).intValue();
isNew = ( (Boolean) stream.readObject()).booleanValue();
isValid = ( (Boolean) stream.readObject()).booleanValue();
thisAccessedTime = ( (Long) stream.readObject()).longValue();
version = ( (Long) stream.readObject()).longValue();
boolean hasPrincipal = stream.readBoolean();
principal = null;
if (hasPrincipal) {
principal = SerializablePrincipal.readPrincipal(stream);
}
// setId((String) stream.readObject());
id = (String) stream.readObject();
if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.readSession", id));
// Deserialize the attribute count and attribute values
if (attributes == null) attributes = new ConcurrentHashMap<>();
int n = ( (Integer) stream.readObject()).intValue();
boolean isValidSave = isValid;
isValid = true;
for (int i = 0; i < n; i++) {
String name = (String) stream.readObject();
Object value = stream.readObject();
if ( (value instanceof String) && (value.equals(NOT_SERIALIZED)))
continue;
attributes.put(name, value);
}
isValid = isValidSave;
if (listeners == null) {
ArrayList<SessionListener> arrayList = new ArrayList<>();
listeners = arrayList;
}
if (notes == null) {
notes = new Hashtable<>();
}
activate();
}
@Override
public void writeExternal(ObjectOutput out ) throws java.io.IOException {
try {
lock();
doWriteObject(out);
}finally {
unlock();
}
}
/**
* Write a serialized version of this session object to the specified object
* output stream.
* <p>
* <b>IMPLEMENTATION NOTE </b>: The owning Manager will not be stored in the
* serialized representation of this Session. After calling
* <code>readObject()</code>, you must set the associated Manager
* explicitly.
* <p>
* <b>IMPLEMENTATION NOTE </b>: Any attribute that is not Serializable will
* be unbound from the session, with appropriate actions if it implements
* HttpSessionBindingListener. If you do not want any such attributes, be
* sure the <code>distributable</code> property of the associated Manager
* is set to <code>true</code>.
*
* @param stream
* The output stream to write to
*
* @exception IOException
* if an input/output error occurs
*/
@Override
protected void doWriteObject(ObjectOutputStream stream) throws IOException {
doWriteObject((ObjectOutput)stream);
}
private void doWriteObject(ObjectOutput stream) throws IOException {
// Write the scalar instance variables (except Manager)
stream.writeObject(Long.valueOf(creationTime));
stream.writeObject(Long.valueOf(lastAccessedTime));
stream.writeObject(Integer.valueOf(maxInactiveInterval));
stream.writeObject(Boolean.valueOf(isNew));
stream.writeObject(Boolean.valueOf(isValid));
stream.writeObject(Long.valueOf(thisAccessedTime));
stream.writeObject(Long.valueOf(version));
stream.writeBoolean(getPrincipal() != null);
if (getPrincipal() != null) {
SerializablePrincipal.writePrincipal((GenericPrincipal) principal,stream);
}
stream.writeObject(id);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaSession.writeSession", id));
// Accumulate the names of serializable and non-serializable attributes
String keys[] = keys();
ArrayList<String> saveNames = new ArrayList<>();
ArrayList<Object> saveValues = new ArrayList<>();
for (int i = 0; i < keys.length; i++) {
Object value = null;
value = attributes.get(keys[i]);
if (value == null || exclude(keys[i]))
continue;
else if (value instanceof Serializable) {
saveNames.add(keys[i]);
saveValues.add(value);
}
}
// Serialize the attribute count and the Serializable attributes
int n = saveNames.size();
stream.writeObject(Integer.valueOf(n));
for (int i = 0; i < n; i++) {
stream.writeObject( saveNames.get(i));
try {
stream.writeObject(saveValues.get(i));
} catch (NotSerializableException e) {
log.error(sm.getString("standardSession.notSerializable",saveNames.get(i), id), e);
stream.writeObject(NOT_SERIALIZED);
log.error(" storing attribute '" + saveNames.get(i)+ "' with value NOT_SERIALIZED");
}
}
}
// -------------------------------------------------------- Private Methods
protected void removeAttributeInternal(String name, boolean notify,
boolean addDeltaRequest) {
try {
lock();
// Remove this attribute from our collection
Object value = attributes.get(name);
if (value == null) return;
super.removeAttributeInternal(name,notify);
if (addDeltaRequest && deltaRequest != null && !exclude(name)) {
deltaRequest.removeAttribute(name);
}
}finally {
unlock();
}
}
@Override
public long getLastTimeReplicated() {
return lastTimeReplicated;
}
@Override
public long getVersion() {
return version;
}
@Override
public void setLastTimeReplicated(long lastTimeReplicated) {
this.lastTimeReplicated = lastTimeReplicated;
}
@Override
public void setVersion(long version) {
this.version = version;
}
protected void setAccessCount(int count) {
if ( accessCount == null && ACTIVITY_CHECK ) accessCount = new AtomicInteger();
if ( accessCount != null ) super.accessCount.set(count);
}
}
|
55,521
|
Bug 55521 Race Condition in HttpSession#invalidate() / HttpServletRequest#getSession(boolean)
| null |
resolved fixed
|
262c069
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-05T15:42:48Z
| 2013-09-04T13:06:40Z
|
java/org/apache/catalina/session/StandardSession.java
|
/*
* 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.session;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.SessionEvent;
import org.apache.catalina.SessionListener;
import org.apache.catalina.TomcatPrincipal;
import org.apache.catalina.security.SecurityUtil;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
* Standard implementation of the <b>Session</b> interface. This object is
* serializable, so that it can be stored in persistent storage or transferred
* to a different JVM for distributable session support.
* <p>
* <b>IMPLEMENTATION NOTE</b>: An instance of this class represents both the
* internal (Session) and application level (HttpSession) view of the session.
* However, because the class itself is not declared public, Java logic outside
* of the <code>org.apache.catalina.session</code> package cannot cast an
* HttpSession view of this instance back to a Session view.
* <p>
* <b>IMPLEMENTATION NOTE</b>: If you add fields to this class, you must
* make sure that you carry them over in the read/writeObject methods so
* that this class is properly serialized.
*
* @author Craig R. McClanahan
* @author Sean Legassick
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @version $Id$
*/
public class StandardSession implements HttpSession, Session, Serializable {
private static final long serialVersionUID = 1L;
protected static final boolean STRICT_SERVLET_COMPLIANCE;
protected static final boolean ACTIVITY_CHECK;
protected static final boolean LAST_ACCESS_AT_START;
static {
STRICT_SERVLET_COMPLIANCE = Globals.STRICT_SERVLET_COMPLIANCE;
String activityCheck = System.getProperty(
"org.apache.catalina.session.StandardSession.ACTIVITY_CHECK");
if (activityCheck == null) {
ACTIVITY_CHECK = STRICT_SERVLET_COMPLIANCE;
} else {
ACTIVITY_CHECK =
Boolean.valueOf(activityCheck).booleanValue();
}
String lastAccessAtStart = System.getProperty(
"org.apache.catalina.session.StandardSession.LAST_ACCESS_AT_START");
if (lastAccessAtStart == null) {
LAST_ACCESS_AT_START = STRICT_SERVLET_COMPLIANCE;
} else {
LAST_ACCESS_AT_START =
Boolean.valueOf(lastAccessAtStart).booleanValue();
}
}
// ----------------------------------------------------------- Constructors
/**
* Construct a new Session associated with the specified Manager.
*
* @param manager The manager with which this Session is associated
*/
public StandardSession(Manager manager) {
super();
this.manager = manager;
// Initialize access count
if (ACTIVITY_CHECK) {
accessCount = new AtomicInteger();
}
}
// ----------------------------------------------------- Instance Variables
/**
* Type array.
*/
protected static final String EMPTY_ARRAY[] = new String[0];
/**
* The dummy attribute value serialized when a NotSerializableException is
* encountered in <code>writeObject()</code>.
*/
protected static final String NOT_SERIALIZED =
"___NOT_SERIALIZABLE_EXCEPTION___";
/**
* The collection of user data attributes associated with this Session.
*/
protected Map<String, Object> attributes = new ConcurrentHashMap<>();
/**
* The authentication type used to authenticate our cached Principal,
* if any. NOTE: This value is not included in the serialized
* version of this object.
*/
protected transient String authType = null;
/**
* The time this session was created, in milliseconds since midnight,
* January 1, 1970 GMT.
*/
protected long creationTime = 0L;
/**
* Set of attribute names which are not allowed to be persisted.
*/
protected static final String[] excludedAttributes = {
Globals.SUBJECT_ATTR,
Globals.GSS_CREDENTIAL_ATTR
};
/**
* We are currently processing a session expiration, so bypass
* certain IllegalStateException tests. NOTE: This value is not
* included in the serialized version of this object.
*/
protected transient volatile boolean expiring = false;
/**
* The facade associated with this session. NOTE: This value is not
* included in the serialized version of this object.
*/
protected transient StandardSessionFacade facade = null;
/**
* The session identifier of this Session.
*/
protected String id = null;
/**
* The last accessed time for this Session.
*/
protected volatile long lastAccessedTime = creationTime;
/**
* The session event listeners for this Session.
*/
protected transient ArrayList<SessionListener> listeners = new ArrayList<>();
/**
* The Manager with which this Session is associated.
*/
protected transient Manager manager = null;
/**
* The maximum time interval, in seconds, between client requests before
* the servlet container may invalidate this session. A negative time
* indicates that the session should never time out.
*/
protected int maxInactiveInterval = -1;
/**
* Flag indicating whether this session is new or not.
*/
protected boolean isNew = false;
/**
* Flag indicating whether this session is valid or not.
*/
protected volatile boolean isValid = false;
/**
* Internal notes associated with this session by Catalina components
* and event listeners. <b>IMPLEMENTATION NOTE:</b> This object is
* <em>not</em> saved and restored across session serializations!
*/
protected transient Map<String, Object> notes = new Hashtable<>();
/**
* The authenticated Principal associated with this session, if any.
* <b>IMPLEMENTATION NOTE:</b> This object is <i>not</i> saved and
* restored across session serializations!
*/
protected transient Principal principal = null;
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* The HTTP session context associated with this session.
*/
@Deprecated
protected static volatile
javax.servlet.http.HttpSessionContext sessionContext = null;
/**
* The property change support for this component. NOTE: This value
* is not included in the serialized version of this object.
*/
protected final transient PropertyChangeSupport support =
new PropertyChangeSupport(this);
/**
* The current accessed time for this session.
*/
protected volatile long thisAccessedTime = creationTime;
/**
* The access count for this session.
*/
protected transient AtomicInteger accessCount = null;
// ----------------------------------------------------- Session Properties
/**
* Return the authentication type used to authenticate our cached
* Principal, if any.
*/
@Override
public String getAuthType() {
return (this.authType);
}
/**
* Set the authentication type used to authenticate our cached
* Principal, if any.
*
* @param authType The new cached authentication type
*/
@Override
public void setAuthType(String authType) {
String oldAuthType = this.authType;
this.authType = authType;
support.firePropertyChange("authType", oldAuthType, this.authType);
}
/**
* Set the creation time for this session. This method is called by the
* Manager when an existing Session instance is reused.
*
* @param time The new creation time
*/
@Override
public void setCreationTime(long time) {
this.creationTime = time;
this.lastAccessedTime = time;
this.thisAccessedTime = time;
}
/**
* Return the session identifier for this session.
*/
@Override
public String getId() {
return (this.id);
}
/**
* Return the session identifier for this session.
*/
@Override
public String getIdInternal() {
return (this.id);
}
/**
* Set the session identifier for this session.
*
* @param id The new session identifier
*/
@Override
public void setId(String id) {
setId(id, true);
}
/**
* {@inheritDoc}
*/
@Override
public void setId(String id, boolean notify) {
if ((this.id != null) && (manager != null))
manager.remove(this);
this.id = id;
if (manager != null)
manager.add(this);
if (notify) {
tellNew();
}
}
/**
* Inform the listeners about the new session.
*
*/
public void tellNew() {
// Notify interested session event listeners
fireSessionEvent(Session.SESSION_CREATED_EVENT, null);
// Notify interested application event listeners
Context context = manager.getContext();
Object listeners[] = context.getApplicationLifecycleListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event =
new HttpSessionEvent(getSession());
for (int i = 0; i < listeners.length; i++) {
if (!(listeners[i] instanceof HttpSessionListener))
continue;
HttpSessionListener listener =
(HttpSessionListener) listeners[i];
try {
context.fireContainerEvent("beforeSessionCreated",
listener);
listener.sessionCreated(event);
context.fireContainerEvent("afterSessionCreated", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent("afterSessionCreated",
listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
/**
* Inform the listeners about the change session ID.
*
* @param newId new session ID
* @param oldId old session ID
* @param notifySessionListeners Should any associated sessionListeners be
* notified that session ID has been changed?
* @param notifyContainerListeners Should any associated ContainerListeners
* be notified that session ID has been changed?
*/
@Override
public void tellChangedSessionId(String newId, String oldId,
boolean notifySessionListeners, boolean notifyContainerListeners) {
Context context = manager.getContext();
// notify ContainerListeners
if (notifyContainerListeners) {
context.fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT,
new String[] {oldId, newId});
}
// notify HttpSessionIdListener
if (notifySessionListeners) {
Object listeners[] = context.getApplicationEventListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event =
new HttpSessionEvent(getSession());
for(Object listener : listeners) {
if (!(listener instanceof HttpSessionIdListener))
continue;
HttpSessionIdListener idListener =
(HttpSessionIdListener)listener;
try {
idListener.sessionIdChanged(event, oldId);
} catch (Throwable t) {
manager.getContext().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
}
/**
* Return the last time the client sent a request associated with this
* session, as the number of milliseconds since midnight, January 1, 1970
* GMT. Actions that your application takes, such as getting or setting
* a value associated with the session, do not affect the access time.
* This one gets updated whenever a request starts.
*/
@Override
public long getThisAccessedTime() {
if (!isValidInternal()) {
throw new IllegalStateException
(sm.getString("standardSession.getThisAccessedTime.ise"));
}
return (this.thisAccessedTime);
}
/**
* Return the last client access time without invalidation check
* @see #getThisAccessedTime()
*/
@Override
public long getThisAccessedTimeInternal() {
return (this.thisAccessedTime);
}
/**
* Return the last time the client sent a request associated with this
* session, as the number of milliseconds since midnight, January 1, 1970
* GMT. Actions that your application takes, such as getting or setting
* a value associated with the session, do not affect the access time.
* This one gets updated whenever a request finishes.
*/
@Override
public long getLastAccessedTime() {
if (!isValidInternal()) {
throw new IllegalStateException
(sm.getString("standardSession.getLastAccessedTime.ise"));
}
return (this.lastAccessedTime);
}
/**
* Return the last client access time without invalidation check
* @see #getLastAccessedTime()
*/
@Override
public long getLastAccessedTimeInternal() {
return (this.lastAccessedTime);
}
/**
* Return the Manager within which this Session is valid.
*/
@Override
public Manager getManager() {
return (this.manager);
}
/**
* Set the Manager within which this Session is valid.
*
* @param manager The new Manager
*/
@Override
public void setManager(Manager manager) {
this.manager = manager;
}
/**
* Return the maximum time interval, in seconds, between client requests
* before the servlet container will invalidate the session. A negative
* time indicates that the session should never time out.
*/
@Override
public int getMaxInactiveInterval() {
return (this.maxInactiveInterval);
}
/**
* Set the maximum time interval, in seconds, between client requests
* before the servlet container will invalidate the session. A zero or
* negative time indicates that the session should never time out.
*
* @param interval The new maximum interval
*/
@Override
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
/**
* Set the <code>isNew</code> flag for this session.
*
* @param isNew The new value for the <code>isNew</code> flag
*/
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
/**
* Return the authenticated Principal that is associated with this Session.
* This provides an <code>Authenticator</code> with a means to cache a
* previously authenticated Principal, and avoid potentially expensive
* <code>Realm.authenticate()</code> calls on every request. If there
* is no current associated Principal, return <code>null</code>.
*/
@Override
public Principal getPrincipal() {
return (this.principal);
}
/**
* Set the authenticated Principal that is associated with this Session.
* This provides an <code>Authenticator</code> with a means to cache a
* previously authenticated Principal, and avoid potentially expensive
* <code>Realm.authenticate()</code> calls on every request.
*
* @param principal The new Principal, or <code>null</code> if none
*/
@Override
public void setPrincipal(Principal principal) {
Principal oldPrincipal = this.principal;
this.principal = principal;
support.firePropertyChange("principal", oldPrincipal, this.principal);
}
/**
* Return the <code>HttpSession</code> for which this object
* is the facade.
*/
@Override
public HttpSession getSession() {
if (facade == null){
if (SecurityUtil.isPackageProtectionEnabled()){
final StandardSession fsession = this;
facade = AccessController.doPrivileged(
new PrivilegedAction<StandardSessionFacade>(){
@Override
public StandardSessionFacade run(){
return new StandardSessionFacade(fsession);
}
});
} else {
facade = new StandardSessionFacade(this);
}
}
return (facade);
}
/**
* Return the <code>isValid</code> flag for this session.
*/
@Override
public boolean isValid() {
if (this.expiring) {
return true;
}
if (!this.isValid) {
return false;
}
if (ACTIVITY_CHECK && accessCount.get() > 0) {
return true;
}
if (maxInactiveInterval > 0) {
long timeNow = System.currentTimeMillis();
int timeIdle;
if (LAST_ACCESS_AT_START) {
timeIdle = (int) ((timeNow - lastAccessedTime) / 1000L);
} else {
timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L);
}
if (timeIdle >= maxInactiveInterval) {
expire(true);
}
}
return (this.isValid);
}
/**
* Set the <code>isValid</code> flag for this session.
*
* @param isValid The new value for the <code>isValid</code> flag
*/
@Override
public void setValid(boolean isValid) {
this.isValid = isValid;
}
// ------------------------------------------------- Session Public Methods
/**
* Update the accessed time information for this session. This method
* should be called by the context when a request comes in for a particular
* session, even if the application does not reference it.
*/
@Override
public void access() {
this.thisAccessedTime = System.currentTimeMillis();
if (ACTIVITY_CHECK) {
accessCount.incrementAndGet();
}
}
/**
* End the access.
*/
@Override
public void endAccess() {
isNew = false;
/**
* The servlet spec mandates to ignore request handling time
* in lastAccessedTime.
*/
if (LAST_ACCESS_AT_START) {
this.lastAccessedTime = this.thisAccessedTime;
this.thisAccessedTime = System.currentTimeMillis();
} else {
this.thisAccessedTime = System.currentTimeMillis();
this.lastAccessedTime = this.thisAccessedTime;
}
if (ACTIVITY_CHECK) {
accessCount.decrementAndGet();
}
}
/**
* Add a session event listener to this component.
*/
@Override
public void addSessionListener(SessionListener listener) {
listeners.add(listener);
}
/**
* Perform the internal processing required to invalidate this session,
* without triggering an exception if the session has already expired.
*/
@Override
public void expire() {
expire(true);
}
/**
* Perform the internal processing required to invalidate this session,
* without triggering an exception if the session has already expired.
*
* @param notify Should we notify listeners about the demise of
* this session?
*/
public void expire(boolean notify) {
// Check to see if expire is in progress or has previously been called
if (expiring || !isValid)
return;
synchronized (this) {
// Check again, now we are inside the sync so this code only runs once
// Double check locking - expiring and isValid need to be volatile
if (expiring || !isValid)
return;
if (manager == null)
return;
// Mark this session as "being expired"
expiring = true;
// Notify interested application event listeners
// FIXME - Assumes we call listeners in reverse order
Context context = manager.getContext();
// The call to expire() may not have been triggered by the webapp.
// Make sure the webapp's class loader is set when calling the
// listeners
ClassLoader oldTccl = null;
if (context.getLoader() != null &&
context.getLoader().getClassLoader() != null) {
oldTccl = Thread.currentThread().getContextClassLoader();
if (Globals.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> pa = new PrivilegedSetTccl(
context.getLoader().getClassLoader());
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(
context.getLoader().getClassLoader());
}
}
try {
if (notify) {
Object listeners[] = context.getApplicationLifecycleListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event =
new HttpSessionEvent(getSession());
for (int i = 0; i < listeners.length; i++) {
int j = (listeners.length - 1) - i;
if (!(listeners[j] instanceof HttpSessionListener))
continue;
HttpSessionListener listener =
(HttpSessionListener) listeners[j];
try {
context.fireContainerEvent("beforeSessionDestroyed",
listener);
listener.sessionDestroyed(event);
context.fireContainerEvent("afterSessionDestroyed",
listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent(
"afterSessionDestroyed", listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
} finally {
if (oldTccl != null) {
if (Globals.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> pa =
new PrivilegedSetTccl(oldTccl);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(oldTccl);
}
}
}
if (ACTIVITY_CHECK) {
accessCount.set(0);
}
setValid(false);
// Remove this session from our manager's active sessions
manager.remove(this, true);
// Notify interested session event listeners
if (notify) {
fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
}
// Call the logout method
if (principal instanceof TomcatPrincipal) {
TomcatPrincipal gp = (TomcatPrincipal) principal;
try {
gp.logout();
} catch (Exception e) {
manager.getContext().getLogger().error(
sm.getString("standardSession.logoutfail"),
e);
}
}
// We have completed expire of this session
expiring = false;
// Unbind any objects associated with this session
String keys[] = keys();
for (int i = 0; i < keys.length; i++)
removeAttributeInternal(keys[i], notify);
}
}
/**
* Perform the internal processing required to passivate
* this session.
*/
public void passivate() {
// Notify interested session event listeners
fireSessionEvent(Session.SESSION_PASSIVATED_EVENT, null);
// Notify ActivationListeners
HttpSessionEvent event = null;
String keys[] = keys();
for (int i = 0; i < keys.length; i++) {
Object attribute = attributes.get(keys[i]);
if (attribute instanceof HttpSessionActivationListener) {
if (event == null)
event = new HttpSessionEvent(getSession());
try {
((HttpSessionActivationListener)attribute)
.sessionWillPassivate(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
manager.getContext().getLogger().error
(sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
/**
* Perform internal processing required to activate this
* session.
*/
public void activate() {
// Initialize access count
if (ACTIVITY_CHECK) {
accessCount = new AtomicInteger();
}
// Notify interested session event listeners
fireSessionEvent(Session.SESSION_ACTIVATED_EVENT, null);
// Notify ActivationListeners
HttpSessionEvent event = null;
String keys[] = keys();
for (int i = 0; i < keys.length; i++) {
Object attribute = attributes.get(keys[i]);
if (attribute instanceof HttpSessionActivationListener) {
if (event == null)
event = new HttpSessionEvent(getSession());
try {
((HttpSessionActivationListener)attribute)
.sessionDidActivate(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
manager.getContext().getLogger().error
(sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
/**
* Return the object bound with the specified name to the internal notes
* for this session, or <code>null</code> if no such binding exists.
*
* @param name Name of the note to be returned
*/
@Override
public Object getNote(String name) {
return (notes.get(name));
}
/**
* Return an Iterator containing the String names of all notes bindings
* that exist for this session.
*/
@Override
public Iterator<String> getNoteNames() {
return (notes.keySet().iterator());
}
/**
* Release all object references, and initialize instance variables, in
* preparation for reuse of this object.
*/
@Override
public void recycle() {
// Reset the instance variables associated with this Session
attributes.clear();
setAuthType(null);
creationTime = 0L;
expiring = false;
id = null;
lastAccessedTime = 0L;
maxInactiveInterval = -1;
notes.clear();
setPrincipal(null);
isNew = false;
isValid = false;
manager = null;
}
/**
* Remove any object bound to the specified name in the internal notes
* for this session.
*
* @param name Name of the note to be removed
*/
@Override
public void removeNote(String name) {
notes.remove(name);
}
/**
* Remove a session event listener from this component.
*/
@Override
public void removeSessionListener(SessionListener listener) {
listeners.remove(listener);
}
/**
* Bind an object to a specified name in the internal notes associated
* with this session, replacing any existing binding for this name.
*
* @param name Name to which the object should be bound
* @param value Object to be bound to the specified name
*/
@Override
public void setNote(String name, Object value) {
notes.put(name, value);
}
/**
* Return a string representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("StandardSession[");
sb.append(id);
sb.append("]");
return (sb.toString());
}
// ------------------------------------------------ Session Package Methods
/**
* Read a serialized version of the contents of this session object from
* the specified object input stream, without requiring that the
* StandardSession itself have been serialized.
*
* @param stream The object input stream to read from
*
* @exception ClassNotFoundException if an unknown class is specified
* @exception IOException if an input/output error occurs
*/
public void readObjectData(ObjectInputStream stream)
throws ClassNotFoundException, IOException {
doReadObject(stream);
}
/**
* Write a serialized version of the contents of this session object to
* the specified object output stream, without requiring that the
* StandardSession itself have been serialized.
*
* @param stream The object output stream to write to
*
* @exception IOException if an input/output error occurs
*/
public void writeObjectData(ObjectOutputStream stream)
throws IOException {
doWriteObject(stream);
}
// ------------------------------------------------- HttpSession Properties
/**
* Return the time when this session was created, in milliseconds since
* midnight, January 1, 1970 GMT.
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
@Override
public long getCreationTime() {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.getCreationTime.ise"));
return (this.creationTime);
}
/**
* Return the time when this session was created, in milliseconds since
* midnight, January 1, 1970 GMT, bypassing the session validation checks.
*/
@Override
public long getCreationTimeInternal() {
return this.creationTime;
}
/**
* Return the ServletContext to which this session belongs.
*/
@Override
public ServletContext getServletContext() {
if (manager == null)
return (null);
Context context = manager.getContext();
if (context == null)
return (null);
else
return (context.getServletContext());
}
/**
* Return the session context with which this session is associated.
*
* @deprecated As of Version 2.1, this method is deprecated and has no
* replacement. It will be removed in a future version of the
* Java Servlet API.
*/
@Override
@Deprecated
public javax.servlet.http.HttpSessionContext getSessionContext() {
if (sessionContext == null)
sessionContext = new StandardSessionContext();
return (sessionContext);
}
// ----------------------------------------------HttpSession Public Methods
/**
* Return the object bound with the specified name in this session, or
* <code>null</code> if no object is bound with that name.
*
* @param name Name of the attribute to be returned
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
@Override
public Object getAttribute(String name) {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.getAttribute.ise"));
if (name == null) return null;
return (attributes.get(name));
}
/**
* Return an <code>Enumeration</code> of <code>String</code> objects
* containing the names of the objects bound to this session.
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
@Override
public Enumeration<String> getAttributeNames() {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.getAttributeNames.ise"));
Set<String> names = new HashSet<>();
names.addAll(attributes.keySet());
return Collections.enumeration(names);
}
/**
* Return the object bound with the specified name in this session, or
* <code>null</code> if no object is bound with that name.
*
* @param name Name of the value to be returned
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*
* @deprecated As of Version 2.2, this method is replaced by
* <code>getAttribute()</code>
*/
@Override
@Deprecated
public Object getValue(String name) {
return (getAttribute(name));
}
/**
* Return the set of names of objects bound to this session. If there
* are no such objects, a zero-length array is returned.
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*
* @deprecated As of Version 2.2, this method is replaced by
* <code>getAttributeNames()</code>
*/
@Override
@Deprecated
public String[] getValueNames() {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.getValueNames.ise"));
return (keys());
}
/**
* Invalidates this session and unbinds any objects bound to it.
*
* @exception IllegalStateException if this method is called on
* an invalidated session
*/
@Override
public void invalidate() {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.invalidate.ise"));
// Cause this session to expire
expire();
}
/**
* Return <code>true</code> if the client does not yet know about the
* session, or if the client chooses not to join the session. For
* example, if the server used only cookie-based sessions, and the client
* has disabled the use of cookies, then a session would be new on each
* request.
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
@Override
public boolean isNew() {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.isNew.ise"));
return (this.isNew);
}
/**
* Bind an object to this session, using the specified name. If an object
* of the same name is already bound to this session, the object is
* replaced.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueBound()</code> on the object.
*
* @param name Name to which the object is bound, cannot be null
* @param value Object to be bound, cannot be null
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*
* @deprecated As of Version 2.2, this method is replaced by
* <code>setAttribute()</code>
*/
@Override
@Deprecated
public void putValue(String name, Object value) {
setAttribute(name, value);
}
/**
* Remove the object bound with the specified name from this session. If
* the session does not have an object bound with this name, this method
* does nothing.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueUnbound()</code> on the object.
*
* @param name Name of the object to remove from this session.
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
@Override
public void removeAttribute(String name) {
removeAttribute(name, true);
}
/**
* Remove the object bound with the specified name from this session. If
* the session does not have an object bound with this name, this method
* does nothing.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueUnbound()</code> on the object.
*
* @param name Name of the object to remove from this session.
* @param notify Should we notify interested listeners that this
* attribute is being removed?
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
public void removeAttribute(String name, boolean notify) {
// Validate our current state
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.removeAttribute.ise"));
removeAttributeInternal(name, notify);
}
/**
* Remove the object bound with the specified name from this session. If
* the session does not have an object bound with this name, this method
* does nothing.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueUnbound()</code> on the object.
*
* @param name Name of the object to remove from this session.
*
* @exception IllegalStateException if this method is called on an
* invalidated session
*
* @deprecated As of Version 2.2, this method is replaced by
* <code>removeAttribute()</code>
*/
@Override
@Deprecated
public void removeValue(String name) {
removeAttribute(name);
}
/**
* Bind an object to this session, using the specified name. If an object
* of the same name is already bound to this session, the object is
* replaced.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueBound()</code> on the object.
*
* @param name Name to which the object is bound, cannot be null
* @param value Object to be bound, cannot be null
*
* @exception IllegalArgumentException if an attempt is made to add a
* non-serializable object in an environment marked distributable.
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
@Override
public void setAttribute(String name, Object value) {
setAttribute(name,value,true);
}
/**
* Bind an object to this session, using the specified name. If an object
* of the same name is already bound to this session, the object is
* replaced.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueBound()</code> on the object.
*
* @param name Name to which the object is bound, cannot be null
* @param value Object to be bound, cannot be null
* @param notify whether to notify session listeners
* @exception IllegalArgumentException if an attempt is made to add a
* non-serializable object in an environment marked distributable.
* @exception IllegalStateException if this method is called on an
* invalidated session
*/
public void setAttribute(String name, Object value, boolean notify) {
// Name cannot be null
if (name == null)
throw new IllegalArgumentException
(sm.getString("standardSession.setAttribute.namenull"));
// Null value is the same as removeAttribute()
if (value == null) {
removeAttribute(name);
return;
}
// Validate our current state
if (!isValidInternal())
throw new IllegalStateException(sm.getString(
"standardSession.setAttribute.ise", getIdInternal()));
if ((manager != null) && manager.getDistributable() &&
!isAttributeDistributable(name, value))
throw new IllegalArgumentException
(sm.getString("standardSession.setAttribute.iae", name));
// Construct an event with the new value
HttpSessionBindingEvent event = null;
// Call the valueBound() method if necessary
if (notify && value instanceof HttpSessionBindingListener) {
// Don't call any notification if replacing with the same value
Object oldValue = attributes.get(name);
if (value != oldValue) {
event = new HttpSessionBindingEvent(getSession(), name, value);
try {
((HttpSessionBindingListener) value).valueBound(event);
} catch (Throwable t){
manager.getContext().getLogger().error
(sm.getString("standardSession.bindingEvent"), t);
}
}
}
// Replace or add this attribute
Object unbound = attributes.put(name, value);
// Call the valueUnbound() method if necessary
if (notify && (unbound != null) && (unbound != value) &&
(unbound instanceof HttpSessionBindingListener)) {
try {
((HttpSessionBindingListener) unbound).valueUnbound
(new HttpSessionBindingEvent(getSession(), name));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
manager.getContext().getLogger().error
(sm.getString("standardSession.bindingEvent"), t);
}
}
if ( !notify ) return;
// Notify interested application event listeners
Context context = manager.getContext();
Object listeners[] = context.getApplicationEventListeners();
if (listeners == null)
return;
for (int i = 0; i < listeners.length; i++) {
if (!(listeners[i] instanceof HttpSessionAttributeListener))
continue;
HttpSessionAttributeListener listener =
(HttpSessionAttributeListener) listeners[i];
try {
if (unbound != null) {
context.fireContainerEvent("beforeSessionAttributeReplaced",
listener);
if (event == null) {
event = new HttpSessionBindingEvent
(getSession(), name, unbound);
}
listener.attributeReplaced(event);
context.fireContainerEvent("afterSessionAttributeReplaced",
listener);
} else {
context.fireContainerEvent("beforeSessionAttributeAdded",
listener);
if (event == null) {
event = new HttpSessionBindingEvent
(getSession(), name, value);
}
listener.attributeAdded(event);
context.fireContainerEvent("afterSessionAttributeAdded",
listener);
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
if (unbound != null) {
context.fireContainerEvent(
"afterSessionAttributeReplaced", listener);
} else {
context.fireContainerEvent("afterSessionAttributeAdded",
listener);
}
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error
(sm.getString("standardSession.attributeEvent"), t);
}
}
}
// ------------------------------------------ HttpSession Protected Methods
/**
* Return the <code>isValid</code> flag for this session without any expiration
* check.
*/
protected boolean isValidInternal() {
return (this.isValid || this.expiring);
}
/**
* Check whether the Object can be distributed. This implementation
* simply checks for serializability. Derived classes might use other
* distribution technology not based on serialization and can extend
* this check.
* @param name The name of the attribute to check
* @param value The value of the attribute to check
* @return true if the attribute is distributable, false otherwise
*/
protected boolean isAttributeDistributable(String name, Object value) {
return value instanceof Serializable;
}
/**
* Read a serialized version of this session object from the specified
* object input stream.
* <p>
* <b>IMPLEMENTATION NOTE</b>: The reference to the owning Manager
* is not restored by this method, and must be set explicitly.
*
* @param stream The input stream to read from
*
* @exception ClassNotFoundException if an unknown class is specified
* @exception IOException if an input/output error occurs
*/
protected void doReadObject(ObjectInputStream stream)
throws ClassNotFoundException, IOException {
// Deserialize the scalar instance variables (except Manager)
authType = null; // Transient only
creationTime = ((Long) stream.readObject()).longValue();
lastAccessedTime = ((Long) stream.readObject()).longValue();
maxInactiveInterval = ((Integer) stream.readObject()).intValue();
isNew = ((Boolean) stream.readObject()).booleanValue();
isValid = ((Boolean) stream.readObject()).booleanValue();
thisAccessedTime = ((Long) stream.readObject()).longValue();
principal = null; // Transient only
// setId((String) stream.readObject());
id = (String) stream.readObject();
if (manager.getContext().getLogger().isDebugEnabled())
manager.getContext().getLogger().debug
("readObject() loading session " + id);
// Deserialize the attribute count and attribute values
if (attributes == null)
attributes = new ConcurrentHashMap<>();
int n = ((Integer) stream.readObject()).intValue();
boolean isValidSave = isValid;
isValid = true;
for (int i = 0; i < n; i++) {
String name = (String) stream.readObject();
Object value = stream.readObject();
if ((value instanceof String) && (value.equals(NOT_SERIALIZED)))
continue;
if (manager.getContext().getLogger().isDebugEnabled())
manager.getContext().getLogger().debug(" loading attribute '" + name +
"' with value '" + value + "'");
attributes.put(name, value);
}
isValid = isValidSave;
if (listeners == null) {
listeners = new ArrayList<>();
}
if (notes == null) {
notes = new Hashtable<>();
}
}
/**
* Write a serialized version of this session object to the specified
* object output stream.
* <p>
* <b>IMPLEMENTATION NOTE</b>: The owning Manager will not be stored
* in the serialized representation of this Session. After calling
* <code>readObject()</code>, you must set the associated Manager
* explicitly.
* <p>
* <b>IMPLEMENTATION NOTE</b>: Any attribute that is not Serializable
* will be unbound from the session, with appropriate actions if it
* implements HttpSessionBindingListener. If you do not want any such
* attributes, be sure the <code>distributable</code> property of the
* associated Manager is set to <code>true</code>.
*
* @param stream The output stream to write to
*
* @exception IOException if an input/output error occurs
*/
protected void doWriteObject(ObjectOutputStream stream) throws IOException {
// Write the scalar instance variables (except Manager)
stream.writeObject(Long.valueOf(creationTime));
stream.writeObject(Long.valueOf(lastAccessedTime));
stream.writeObject(Integer.valueOf(maxInactiveInterval));
stream.writeObject(Boolean.valueOf(isNew));
stream.writeObject(Boolean.valueOf(isValid));
stream.writeObject(Long.valueOf(thisAccessedTime));
stream.writeObject(id);
if (manager.getContext().getLogger().isDebugEnabled())
manager.getContext().getLogger().debug
("writeObject() storing session " + id);
// Accumulate the names of serializable and non-serializable attributes
String keys[] = keys();
ArrayList<String> saveNames = new ArrayList<>();
ArrayList<Object> saveValues = new ArrayList<>();
for (int i = 0; i < keys.length; i++) {
Object value = attributes.get(keys[i]);
if (value == null)
continue;
else if ( (value instanceof Serializable)
&& (!exclude(keys[i]) )) {
saveNames.add(keys[i]);
saveValues.add(value);
} else {
removeAttributeInternal(keys[i], true);
}
}
// Serialize the attribute count and the Serializable attributes
int n = saveNames.size();
stream.writeObject(Integer.valueOf(n));
for (int i = 0; i < n; i++) {
stream.writeObject(saveNames.get(i));
try {
stream.writeObject(saveValues.get(i));
if (manager.getContext().getLogger().isDebugEnabled())
manager.getContext().getLogger().debug
(" storing attribute '" + saveNames.get(i) +
"' with value '" + saveValues.get(i) + "'");
} catch (NotSerializableException e) {
manager.getContext().getLogger().warn
(sm.getString("standardSession.notSerializable",
saveNames.get(i), id), e);
stream.writeObject(NOT_SERIALIZED);
if (manager.getContext().getLogger().isDebugEnabled())
manager.getContext().getLogger().debug
(" storing attribute '" + saveNames.get(i) +
"' with value NOT_SERIALIZED");
}
}
}
/**
* Exclude standard attributes that cannot be serialized.
* @param name the attribute's name
*/
protected boolean exclude(String name){
for (int i = 0; i < excludedAttributes.length; i++) {
if (name.equalsIgnoreCase(excludedAttributes[i]))
return true;
}
return false;
}
// ------------------------------------------------------ Protected Methods
/**
* Notify all session event listeners that a particular event has
* occurred for this Session. The default implementation performs
* this notification synchronously using the calling thread.
*
* @param type Event type
* @param data Event data
*/
public void fireSessionEvent(String type, Object data) {
if (listeners.size() < 1)
return;
SessionEvent event = new SessionEvent(this, type, data);
SessionListener list[] = new SessionListener[0];
synchronized (listeners) {
list = listeners.toArray(list);
}
for (int i = 0; i < list.length; i++){
(list[i]).sessionEvent(event);
}
}
/**
* Return the names of all currently defined session attributes
* as an array of Strings. If there are no defined attributes, a
* zero-length array is returned.
*/
protected String[] keys() {
return attributes.keySet().toArray(EMPTY_ARRAY);
}
/**
* Remove the object bound with the specified name from this session. If
* the session does not have an object bound with this name, this method
* does nothing.
* <p>
* After this method executes, and if the object implements
* <code>HttpSessionBindingListener</code>, the container calls
* <code>valueUnbound()</code> on the object.
*
* @param name Name of the object to remove from this session.
* @param notify Should we notify interested listeners that this
* attribute is being removed?
*/
protected void removeAttributeInternal(String name, boolean notify) {
// Avoid NPE
if (name == null) return;
// Remove this attribute from our collection
Object value = attributes.remove(name);
// Do we need to do valueUnbound() and attributeRemoved() notification?
if (!notify || (value == null)) {
return;
}
// Call the valueUnbound() method if necessary
HttpSessionBindingEvent event = null;
if (value instanceof HttpSessionBindingListener) {
event = new HttpSessionBindingEvent(getSession(), name, value);
((HttpSessionBindingListener) value).valueUnbound(event);
}
// Notify interested application event listeners
Context context = manager.getContext();
Object listeners[] = context.getApplicationEventListeners();
if (listeners == null)
return;
for (int i = 0; i < listeners.length; i++) {
if (!(listeners[i] instanceof HttpSessionAttributeListener))
continue;
HttpSessionAttributeListener listener =
(HttpSessionAttributeListener) listeners[i];
try {
context.fireContainerEvent("beforeSessionAttributeRemoved",
listener);
if (event == null) {
event = new HttpSessionBindingEvent
(getSession(), name, value);
}
listener.attributeRemoved(event);
context.fireContainerEvent("afterSessionAttributeRemoved",
listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent("afterSessionAttributeRemoved",
listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error
(sm.getString("standardSession.attributeEvent"), t);
}
}
}
private static class PrivilegedSetTccl
implements PrivilegedAction<Void> {
private ClassLoader cl;
PrivilegedSetTccl(ClassLoader cl) {
this.cl = cl;
}
@Override
public Void run() {
Thread.currentThread().setContextClassLoader(cl);
return null;
}
}
}
// ------------------------------------------------------------ Protected Class
/**
* This class is a dummy implementation of the <code>HttpSessionContext</code>
* interface, to conform to the requirement that such an object be returned
* when <code>HttpSession.getSessionContext()</code> is called.
*
* @author Craig R. McClanahan
*
* @deprecated As of Java Servlet API 2.1 with no replacement. The
* interface will be removed in a future version of this API.
*/
@Deprecated
final class StandardSessionContext
implements javax.servlet.http.HttpSessionContext {
private static final List<String> emptyString = Collections.emptyList();
/**
* Return the session identifiers of all sessions defined
* within this context.
*
* @deprecated As of Java Servlet API 2.1 with no replacement.
* This method must return an empty <code>Enumeration</code>
* and will be removed in a future version of the API.
*/
@Override
@Deprecated
public Enumeration<String> getIds() {
return Collections.enumeration(emptyString);
}
/**
* Return the <code>HttpSession</code> associated with the
* specified session identifier.
*
* @param id Session identifier for which to look up a session
*
* @deprecated As of Java Servlet API 2.1 with no replacement.
* This method must return null and will be removed in a
* future version of the API.
*/
@Override
@Deprecated
public HttpSession getSession(String id) {
return (null);
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
|
/*
* 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.jdbc.pool;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* Implementation of simple connection pool.
* The ConnectionPool uses a {@link PoolProperties} object for storing all the meta information about the connection pool.
* As the underlying implementation, the connection pool uses {@link java.util.concurrent.BlockingQueue} to store active and idle connections.
* A custom implementation of a fair {@link FairBlockingQueue} blocking queue is provided with the connection pool itself.
* @author Filip Hanik
* @version 1.0
*/
public class ConnectionPool {
/**
* Default domain for objects registering with an mbean server
*/
public static final String POOL_JMX_DOMAIN = "tomcat.jdbc";
/**
* Prefix type for JMX registration
*/
public static final String POOL_JMX_TYPE_PREFIX = POOL_JMX_DOMAIN+":type=";
/**
* Logger
*/
private static final Log log = LogFactory.getLog(ConnectionPool.class);
//===============================================================================
// INSTANCE/QUICK ACCESS VARIABLE
//===============================================================================
/**
* Carries the size of the pool, instead of relying on a queue implementation
* that usually iterates over to get an exact count
*/
private AtomicInteger size = new AtomicInteger(0);
/**
* All the information about the connection pool
* These are the properties the pool got instantiated with
*/
private PoolConfiguration poolProperties;
/**
* Contains all the connections that are in use
* TODO - this shouldn't be a blocking queue, simply a list to hold our objects
*/
private BlockingQueue<PooledConnection> busy;
/**
* Contains all the idle connections
*/
private BlockingQueue<PooledConnection> idle;
/**
* The thread that is responsible for checking abandoned and idle threads
*/
private volatile PoolCleaner poolCleaner;
/**
* Pool closed flag
*/
private volatile boolean closed = false;
/**
* Since newProxyInstance performs the same operation, over and over
* again, it is much more optimized if we simply store the constructor ourselves.
*/
private Constructor<?> proxyClassConstructor;
/**
* Executor service used to cancel Futures
*/
private ThreadPoolExecutor cancellator = new ThreadPoolExecutor(0,1,1000,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
/**
* reference to the JMX mbean
*/
protected org.apache.tomcat.jdbc.pool.jmx.ConnectionPool jmxPool = null;
/**
* counter to track how many threads are waiting for a connection
*/
private AtomicInteger waitcount = new AtomicInteger(0);
private AtomicLong poolVersion = new AtomicLong(Long.MIN_VALUE);
//===============================================================================
// PUBLIC METHODS
//===============================================================================
/**
* Instantiate a connection pool. This will create connections if initialSize is larger than 0.
* The {@link PoolProperties} should not be reused for another connection pool.
* @param prop PoolProperties - all the properties for this connection pool
* @throws SQLException
*/
public ConnectionPool(PoolConfiguration prop) throws SQLException {
//setup quick access variables and pools
init(prop);
}
/**
* Retrieves a Connection future. If a connection is not available, one can block using future.get()
* until a connection has become available.
* If a connection is not retrieved, the Future must be cancelled in order for the connection to be returned
* to the pool.
* @return a Future containing a reference to the connection or the future connection
* @throws SQLException
*/
public Future<Connection> getConnectionAsync() throws SQLException {
try {
PooledConnection pc = borrowConnection(0, null, null);
if (pc!=null) {
return new ConnectionFuture(pc);
}
}catch (SQLException x) {
if (x.getMessage().indexOf("NoWait")<0) {
throw x;
}
}
//we can only retrieve a future if the underlying queue supports it.
if (idle instanceof FairBlockingQueue<?>) {
Future<PooledConnection> pcf = ((FairBlockingQueue<PooledConnection>)idle).pollAsync();
return new ConnectionFuture(pcf);
} else if (idle instanceof MultiLockFairBlockingQueue<?>) {
Future<PooledConnection> pcf = ((MultiLockFairBlockingQueue<PooledConnection>)idle).pollAsync();
return new ConnectionFuture(pcf);
} else {
throw new SQLException("Connection pool is misconfigured, doesn't support async retrieval. Set the 'fair' property to 'true'");
}
}
/**
* Borrows a connection from the pool. If a connection is available (in the idle queue) or the pool has not reached
* {@link PoolProperties#maxActive maxActive} connections a connection is returned immediately.
* If no connection is available, the pool will attempt to fetch a connection for {@link PoolProperties#maxWait maxWait} milliseconds.
* @return Connection - a java.sql.Connection/javax.sql.PooledConnection reflection proxy, wrapping the underlying object.
* @throws SQLException - if the wait times out or a failure occurs creating a connection
*/
public Connection getConnection() throws SQLException {
//check out a connection
PooledConnection con = borrowConnection(-1,null,null);
return setupConnection(con);
}
/**
* Borrows a connection from the pool. If a connection is available (in the
* idle queue) or the pool has not reached {@link PoolProperties#maxActive
* maxActive} connections a connection is returned immediately. If no
* connection is available, the pool will attempt to fetch a connection for
* {@link PoolProperties#maxWait maxWait} milliseconds.
*
* @return Connection - a java.sql.Connection/javax.sql.PooledConnection
* reflection proxy, wrapping the underlying object.
* @throws SQLException
* - if the wait times out or a failure occurs creating a
* connection
*/
public Connection getConnection(String username, String password) throws SQLException {
// check out a connection
PooledConnection con = borrowConnection(-1, username, password);
return setupConnection(con);
}
/**
* Returns the name of this pool
* @return String - the name of the pool
*/
public String getName() {
return getPoolProperties().getPoolName();
}
/**
* Return the number of threads waiting for a connection
* @return number of threads waiting for a connection
*/
public int getWaitCount() {
return waitcount.get();
}
/**
* Returns the pool properties associated with this connection pool
* @return PoolProperties
*
*/
public PoolConfiguration getPoolProperties() {
return this.poolProperties;
}
/**
* Returns the total size of this pool, this includes both busy and idle connections
* @return int - number of established connections to the database
*/
public int getSize() {
return size.get();
}
/**
* Returns the number of connections that are in use
* @return int - number of established connections that are being used by the application
*/
public int getActive() {
return busy.size();
}
/**
* Returns the number of idle connections
* @return int - number of established connections not being used
*/
public int getIdle() {
return idle.size();
}
/**
* Returns true if {@link #close close} has been called, and the connection pool is unusable
* @return boolean
*/
public boolean isClosed() {
return this.closed;
}
//===============================================================================
// PROTECTED METHODS
//===============================================================================
/**
* configures a pooled connection as a proxy.
* This Proxy implements {@link java.sql.Connection} and {@link javax.sql.PooledConnection} interfaces.
* All calls on {@link java.sql.Connection} methods will be propagated down to the actual JDBC connection except for the
* {@link java.sql.Connection#close()} method.
* @param con a {@link PooledConnection} to wrap in a Proxy
* @return a {@link java.sql.Connection} object wrapping a pooled connection.
* @throws SQLException if an interceptor can't be configured, if the proxy can't be instantiated
*/
protected Connection setupConnection(PooledConnection con) throws SQLException {
//fetch previously cached interceptor proxy - one per connection
JdbcInterceptor handler = con.getHandler();
if (handler==null) {
//build the proxy handler
handler = new ProxyConnection(this,con,getPoolProperties().isUseEquals());
//set up the interceptor chain
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=proxies.length-1; i>=0; i--) {
try {
//create a new instance
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
//configure properties
interceptor.setProperties(proxies[i].getProperties());
//setup the chain
interceptor.setNext(handler);
//call reset
interceptor.reset(this, con);
//configure the last one to be held by the connection
handler = interceptor;
}catch(Exception x) {
SQLException sx = new SQLException("Unable to instantiate interceptor chain.");
sx.initCause(x);
throw sx;
}
}
//cache handler for the next iteration
con.setHandler(handler);
} else {
JdbcInterceptor next = handler;
//we have a cached handler, reset it
while (next!=null) {
next.reset(this, con);
next = next.getNext();
}
}
try {
getProxyConstructor(con.getXAConnection() != null);
//create the proxy
//TODO possible optimization, keep track if this connection was returned properly, and don't generate a new facade
Connection connection = null;
if (getPoolProperties().getUseDisposableConnectionFacade() ) {
connection = (Connection)proxyClassConstructor.newInstance(new Object[] { new DisposableConnectionFacade(handler) });
} else {
connection = (Connection)proxyClassConstructor.newInstance(new Object[] {handler});
}
//return the connection
return connection;
}catch (Exception x) {
SQLException s = new SQLException();
s.initCause(x);
throw s;
}
}
/**
* Creates and caches a {@link java.lang.reflect.Constructor} used to instantiate the proxy object.
* We cache this, since the creation of a constructor is fairly slow.
* @return constructor used to instantiate the wrapper object
* @throws NoSuchMethodException
*/
public Constructor<?> getProxyConstructor(boolean xa) throws NoSuchMethodException {
//cache the constructor
if (proxyClassConstructor == null ) {
Class<?> proxyClass = xa ?
Proxy.getProxyClass(ConnectionPool.class.getClassLoader(), new Class[] {java.sql.Connection.class,javax.sql.PooledConnection.class, javax.sql.XAConnection.class}) :
Proxy.getProxyClass(ConnectionPool.class.getClassLoader(), new Class[] {java.sql.Connection.class,javax.sql.PooledConnection.class});
proxyClassConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class });
}
return proxyClassConstructor;
}
/**
* Closes the pool and all disconnects all idle connections
* Active connections will be closed upon the {@link java.sql.Connection#close close} method is called
* on the underlying connection instead of being returned to the pool
* @param force - true to even close the active connections
*/
protected void close(boolean force) {
//are we already closed
if (this.closed) return;
//prevent other threads from entering
this.closed = true;
//stop background thread
if (poolCleaner!=null) {
poolCleaner.stopRunning();
}
/* release all idle connections */
BlockingQueue<PooledConnection> pool = (idle.size()>0)?idle:(force?busy:idle);
while (pool.size()>0) {
try {
//retrieve the next connection
PooledConnection con = pool.poll(1000, TimeUnit.MILLISECONDS);
//close it and retrieve the next one, if one is available
while (con != null) {
//close the connection
if (pool==idle)
release(con);
else
abandon(con);
if (pool.size()>0) {
con = pool.poll(1000, TimeUnit.MILLISECONDS);
} else {
break;
}
} //while
} catch (InterruptedException ex) {
if (getPoolProperties().getPropagateInterruptState()) {
Thread.currentThread().interrupt();
}
}
if (pool.size()==0 && force && pool!=busy) pool = busy;
}
if (this.getPoolProperties().isJmxEnabled()) this.jmxPool = null;
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=0; i<proxies.length; i++) {
try {
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
interceptor.setProperties(proxies[i].getProperties());
interceptor.poolClosed(this);
}catch (Exception x) {
log.debug("Unable to inform interceptor of pool closure.",x);
}
}
} //closePool
/**
* Initialize the connection pool - called from the constructor
* @param properties PoolProperties - properties used to initialize the pool with
* @throws SQLException if initialization fails
*/
protected void init(PoolConfiguration properties) throws SQLException {
poolProperties = properties;
//make sure the pool is properly configured
if (properties.getMaxActive()<1) {
log.warn("maxActive is smaller than 1, setting maxActive to: "+PoolProperties.DEFAULT_MAX_ACTIVE);
properties.setMaxActive(PoolProperties.DEFAULT_MAX_ACTIVE);
}
if (properties.getMaxActive()<properties.getInitialSize()) {
log.warn("initialSize is larger than maxActive, setting initialSize to: "+properties.getMaxActive());
properties.setInitialSize(properties.getMaxActive());
}
if (properties.getMinIdle()>properties.getMaxActive()) {
log.warn("minIdle is larger than maxActive, setting minIdle to: "+properties.getMaxActive());
properties.setMinIdle(properties.getMaxActive());
}
if (properties.getMaxIdle()>properties.getMaxActive()) {
log.warn("maxIdle is larger than maxActive, setting maxIdle to: "+properties.getMaxActive());
properties.setMaxIdle(properties.getMaxActive());
}
if (properties.getMaxIdle()<properties.getMinIdle()) {
log.warn("maxIdle is smaller than minIdle, setting maxIdle to: "+properties.getMinIdle());
properties.setMaxIdle(properties.getMinIdle());
}
//make space for 10 extra in case we flow over a bit
busy = new ArrayBlockingQueue<>(properties.getMaxActive(),false);
//busy = new FairBlockingQueue<PooledConnection>();
//make space for 10 extra in case we flow over a bit
if (properties.isFairQueue()) {
idle = new FairBlockingQueue<>();
//idle = new MultiLockFairBlockingQueue<PooledConnection>();
//idle = new LinkedTransferQueue<PooledConnection>();
//idle = new ArrayBlockingQueue<PooledConnection>(properties.getMaxActive(),false);
} else {
idle = new ArrayBlockingQueue<>(properties.getMaxActive(),properties.isFairQueue());
}
initializePoolCleaner(properties);
//create JMX MBean
if (this.getPoolProperties().isJmxEnabled()) createMBean();
//Parse and create an initial set of interceptors. Letting them know the pool has started.
//These interceptors will not get any connection.
PoolProperties.InterceptorDefinition[] proxies = getPoolProperties().getJdbcInterceptorsAsArray();
for (int i=0; i<proxies.length; i++) {
try {
if (log.isDebugEnabled()) {
log.debug("Creating interceptor instance of class:"+proxies[i].getInterceptorClass());
}
JdbcInterceptor interceptor = proxies[i].getInterceptorClass().newInstance();
interceptor.setProperties(proxies[i].getProperties());
interceptor.poolStarted(this);
}catch (Exception x) {
log.error("Unable to inform interceptor of pool start.",x);
if (jmxPool!=null) jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_INIT, getStackTrace(x));
close(true);
SQLException ex = new SQLException();
ex.initCause(x);
throw ex;
}
}
//initialize the pool with its initial set of members
PooledConnection[] initialPool = new PooledConnection[poolProperties.getInitialSize()];
try {
for (int i = 0; i < initialPool.length; i++) {
initialPool[i] = this.borrowConnection(0, null, null); //don't wait, should be no contention
} //for
} catch (SQLException x) {
log.error("Unable to create initial connections of pool.", x);
if (!poolProperties.isIgnoreExceptionOnPreLoad()) {
if (jmxPool!=null) jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_INIT, getStackTrace(x));
close(true);
throw x;
}
} finally {
//return the members as idle to the pool
for (int i = 0; i < initialPool.length; i++) {
if (initialPool[i] != null) {
try {this.returnConnection(initialPool[i]);}catch(Exception x){/*NOOP*/}
} //end if
} //for
} //catch
closed = false;
}
public void initializePoolCleaner(PoolConfiguration properties) {
//if the evictor thread is supposed to run, start it now
if (properties.isPoolSweeperEnabled()) {
poolCleaner = new PoolCleaner(this, properties.getTimeBetweenEvictionRunsMillis());
poolCleaner.start();
} //end if
}
//===============================================================================
// CONNECTION POOLING IMPL LOGIC
//===============================================================================
/**
* thread safe way to abandon a connection
* signals a connection to be abandoned.
* this will disconnect the connection, and log the stack trace if logAbanded=true
* @param con PooledConnection
*/
protected void abandon(PooledConnection con) {
if (con == null)
return;
try {
con.lock();
String trace = con.getStackTrace();
if (getPoolProperties().isLogAbandoned()) {
log.warn("Connection has been abandoned " + con + ":" + trace);
}
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_ABANDON, trace);
}
//release the connection
release(con);
} finally {
con.unlock();
}
}
/**
* thread safe way to abandon a connection
* signals a connection to be abandoned.
* this will disconnect the connection, and log the stack trace if logAbanded=true
* @param con PooledConnection
*/
protected void suspect(PooledConnection con) {
if (con == null)
return;
if (con.isSuspect())
return;
try {
con.lock();
String trace = con.getStackTrace();
if (getPoolProperties().isLogAbandoned()) {
log.warn("Connection has been marked suspect, possibly abandoned " + con + "["+(System.currentTimeMillis()-con.getTimestamp())+" ms.]:" + trace);
}
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.SUSPECT_ABANDONED_NOTIFICATION, trace);
}
con.setSuspect(true);
} finally {
con.unlock();
}
}
/**
* thread safe way to release a connection
* @param con PooledConnection
*/
protected void release(PooledConnection con) {
if (con == null)
return;
try {
con.lock();
if (con.release()) {
//counter only decremented once
size.addAndGet(-1);
con.setHandler(null);
}
} finally {
con.unlock();
}
// we've asynchronously reduced the number of connections
// we could have threads stuck in idle.poll(timeout) that will never be
// notified
if (waitcount.get() > 0) {
idle.offer(create(true));
}
}
/**
* Thread safe way to retrieve a connection from the pool
* @param wait - time to wait, overrides the maxWait from the properties,
* set to -1 if you wish to use maxWait, 0 if you wish no wait time.
* @return PooledConnection
* @throws SQLException
*/
private PooledConnection borrowConnection(int wait, String username, String password) throws SQLException {
if (isClosed()) {
throw new SQLException("Connection pool closed.");
} //end if
//get the current time stamp
long now = System.currentTimeMillis();
//see if there is one available immediately
PooledConnection con = idle.poll();
while (true) {
if (con!=null) {
//configure the connection and return it
PooledConnection result = borrowConnection(now, con, username, password);
//null should never be returned, but was in a previous impl.
if (result!=null) return result;
}
//if we get here, see if we need to create one
//this is not 100% accurate since it doesn't use a shared
//atomic variable - a connection can become idle while we are creating
//a new connection
if (size.get() < getPoolProperties().getMaxActive()) {
//atomic duplicate check
if (size.addAndGet(1) > getPoolProperties().getMaxActive()) {
//if we got here, two threads passed through the first if
size.decrementAndGet();
} else {
//create a connection, we're below the limit
return createConnection(now, con, username, password);
}
} //end if
//calculate wait time for this iteration
long maxWait = wait;
//if the passed in wait time is -1, means we should use the pool property value
if (wait==-1) {
maxWait = (getPoolProperties().getMaxWait()<=0)?Long.MAX_VALUE:getPoolProperties().getMaxWait();
}
long timetowait = Math.max(0, maxWait - (System.currentTimeMillis() - now));
waitcount.incrementAndGet();
try {
//retrieve an existing connection
con = idle.poll(timetowait, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
if (getPoolProperties().getPropagateInterruptState()) {
Thread.currentThread().interrupt();
}
SQLException sx = new SQLException("Pool wait interrupted.");
sx.initCause(ex);
throw sx;
} finally {
waitcount.decrementAndGet();
}
if (maxWait==0 && con == null) { //no wait, return one if we have one
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.POOL_EMPTY, "Pool empty - no wait.");
}
throw new PoolExhaustedException("[" + Thread.currentThread().getName()+"] " +
"NoWait: Pool empty. Unable to fetch a connection, none available["+busy.size()+" in use].");
}
//we didn't get a connection, lets see if we timed out
if (con == null) {
if ((System.currentTimeMillis() - now) >= maxWait) {
if (jmxPool!=null) {
jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.POOL_EMPTY, "Pool empty - timeout.");
}
throw new PoolExhaustedException("[" + Thread.currentThread().getName()+"] " +
"Timeout: Pool empty. Unable to fetch a connection in " + (maxWait / 1000) +
" seconds, none available[size:"+size.get() +"; busy:"+busy.size()+"; idle:"+idle.size()+"; lastwait:"+timetowait+"].");
} else {
//no timeout, lets try again
continue;
}
}
} //while
}
/**
* Creates a JDBC connection and tries to connect to the database.
* @param now timestamp of when this was called
* @param notUsed Argument not used
* @return a PooledConnection that has been connected
* @throws SQLException
*/
protected PooledConnection createConnection(long now, PooledConnection notUsed, String username, String password) throws SQLException {
//no connections where available we'll create one
PooledConnection con = create(false);
if (username!=null) con.getAttributes().put(PooledConnection.PROP_USER, username);
if (password!=null) con.getAttributes().put(PooledConnection.PROP_PASSWORD, password);
boolean error = false;
try {
//connect and validate the connection
con.lock();
con.connect();
if (con.validate(PooledConnection.VALIDATE_INIT)) {
//no need to lock a new one, its not contented
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
} else {
//validation failed, make sure we disconnect
//and clean up
error =true;
} //end if
} catch (Exception e) {
error = true;
if (log.isDebugEnabled())
log.debug("Unable to create a new JDBC connection.", e);
if (e instanceof SQLException) {
throw (SQLException)e;
} else {
SQLException ex = new SQLException(e.getMessage());
ex.initCause(e);
throw ex;
}
} finally {
// con can never be null here
if (error ) {
release(con);
}
con.unlock();
}//catch
return null;
}
/**
* Validates and configures a previously idle connection
* @param now - timestamp
* @param con - the connection to validate and configure
* @return con
* @throws SQLException if a validation error happens
*/
protected PooledConnection borrowConnection(long now, PooledConnection con, String username, String password) throws SQLException {
//we have a connection, lets set it up
//flag to see if we need to nullify
boolean setToNull = false;
try {
con.lock();
boolean usercheck = con.checkUser(username, password);
if (con.isReleased()) {
return null;
}
if (!con.isDiscarded() && !con.isInitialized()) {
//attempt to connect
try {
con.connect();
} catch (Exception x) {
release(con);
setToNull = true;
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
}
if (usercheck) {
if ((!con.isDiscarded()) && con.validate(PooledConnection.VALIDATE_BORROW)) {
//set the timestamp
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
//set the stack trace for this pool
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
}
}
//if we reached here, that means the connection
//is either has another principal, is discarded or validation failed.
//we will make one more attempt
//in order to guarantee that the thread that just acquired
//the connection shouldn't have to poll again.
try {
con.reconnect();
if (con.validate(PooledConnection.VALIDATE_INIT)) {
//set the timestamp
con.setTimestamp(now);
if (getPoolProperties().isLogAbandoned()) {
//set the stack trace for this pool
con.setStackTrace(getThreadDump());
}
if (!busy.offer(con)) {
log.debug("Connection doesn't fit into busy array, connection will not be traceable.");
}
return con;
} else {
//validation failed.
release(con);
setToNull = true;
throw new SQLException("Failed to validate a newly established connection.");
}
} catch (Exception x) {
release(con);
setToNull = true;
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
} finally {
con.unlock();
if (setToNull) {
con = null;
}
}
}
/**
* Terminate the current transaction for the given connection.
* @param con
* @return <code>true</code> if the connection TX termination succeeded
* otherwise <code>false</code>
*/
protected boolean terminateTransaction(PooledConnection con) {
try {
if (Boolean.FALSE.equals(con.getPoolProperties().getDefaultAutoCommit())) {
if (this.getPoolProperties().getRollbackOnReturn()) {
boolean autocommit = con.getConnection().getAutoCommit();
if (!autocommit) con.getConnection().rollback();
} else if (this.getPoolProperties().getCommitOnReturn()) {
boolean autocommit = con.getConnection().getAutoCommit();
if (!autocommit) con.getConnection().commit();
}
}
return true;
} catch (SQLException x) {
log.warn("Unable to terminate transaction, connection will be closed.",x);
return false;
}
}
/**
* Determines if a connection should be closed upon return to the pool.
* @param con - the connection
* @param action - the validation action that should be performed
* @return true if the connection should be closed
*/
protected boolean shouldClose(PooledConnection con, int action) {
if (con.getConnectionVersion() < getPoolVersion()) return true;
if (con.isDiscarded()) return true;
if (isClosed()) return true;
if (!con.validate(action)) return true;
if (!terminateTransaction(con)) return true;
if (getPoolProperties().getMaxAge()>0 ) {
return (System.currentTimeMillis()-con.getLastConnected()) > getPoolProperties().getMaxAge();
} else {
return false;
}
}
/**
* Returns a connection to the pool
* If the pool is closed, the connection will be released
* If the connection is not part of the busy queue, it will be released.
* If {@link PoolProperties#testOnReturn} is set to true it will be validated
* @param con PooledConnection to be returned to the pool
*/
protected void returnConnection(PooledConnection con) {
if (isClosed()) {
//if the connection pool is closed
//close the connection instead of returning it
release(con);
return;
} //end if
if (con != null) {
try {
con.lock();
if (busy.remove(con)) {
if (!shouldClose(con,PooledConnection.VALIDATE_RETURN)) {
con.setStackTrace(null);
con.setTimestamp(System.currentTimeMillis());
if (((idle.size()>=poolProperties.getMaxIdle()) && !poolProperties.isPoolSweeperEnabled()) || (!idle.offer(con))) {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool, idle["+idle.size()+"]>=maxIdle["+poolProperties.getMaxIdle()+"] idle.offer failed.");
}
release(con);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool.");
}
release(con);
} //end if
} else {
if (log.isDebugEnabled()) {
log.debug("Connection ["+con+"] will be closed and not returned to the pool, busy.remove failed.");
}
release(con);
}
} finally {
con.unlock();
}
} //end if
} //checkIn
/**
* Determines if a connection should be abandoned based on
* {@link PoolProperties#abandonWhenPercentageFull} setting.
* @return true if the connection should be abandoned
*/
protected boolean shouldAbandon() {
if (poolProperties.getAbandonWhenPercentageFull()==0) return true;
float used = busy.size();
float max = poolProperties.getMaxActive();
float perc = poolProperties.getAbandonWhenPercentageFull();
return (used/max*100f)>=perc;
}
/**
* Iterates through all the busy connections and checks for connections that have timed out
*/
public void checkAbandoned() {
try {
if (busy.size()==0) return;
Iterator<PooledConnection> locked = busy.iterator();
int sto = getPoolProperties().getSuspectTimeout();
while (locked.hasNext()) {
PooledConnection con = locked.next();
boolean setToNull = false;
try {
con.lock();
//the con has been returned to the pool
//ignore it
if (idle.contains(con))
continue;
long time = con.getTimestamp();
long now = System.currentTimeMillis();
if (shouldAbandon() && (now - time) > con.getAbandonTimeout()) {
busy.remove(con);
abandon(con);
setToNull = true;
} else if (sto > 0 && (now - time) > (sto*1000)) {
suspect(con);
} else {
//do nothing
} //end if
} finally {
con.unlock();
if (setToNull)
con = null;
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("checkAbandoned failed." ,e);
} catch (Exception e) {
log.warn("checkAbandoned failed, it will be retried.",e);
}
}
/**
* Iterates through the idle connections and resizes the idle pool based on parameters
* {@link PoolProperties#maxIdle}, {@link PoolProperties#minIdle}, {@link PoolProperties#minEvictableIdleTimeMillis}
*/
public void checkIdle() {
checkIdle(false);
}
public void checkIdle(boolean ignoreMinSize) {
try {
if (idle.size()==0) return;
long now = System.currentTimeMillis();
Iterator<PooledConnection> unlocked = idle.iterator();
while ( (ignoreMinSize || (idle.size()>=getPoolProperties().getMinIdle())) && unlocked.hasNext()) {
PooledConnection con = unlocked.next();
boolean setToNull = false;
try {
con.lock();
//the con been taken out, we can't clean it up
if (busy.contains(con))
continue;
long time = con.getTimestamp();
if (shouldReleaseIdle(now, con, time)) {
release(con);
idle.remove(con);
setToNull = true;
} else {
//do nothing
} //end if
} finally {
con.unlock();
if (setToNull)
con = null;
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("checkIdle failed." ,e);
} catch (Exception e) {
log.warn("checkIdle failed, it will be retried.",e);
}
}
protected boolean shouldReleaseIdle(long now, PooledConnection con, long time) {
if (con.getConnectionVersion() < getPoolVersion()) return true;
else return (con.getReleaseTime()>0) && ((now - time) > con.getReleaseTime()) && (getSize()>getPoolProperties().getMinIdle());
}
/**
* Forces a validation of all idle connections if {@link PoolProperties#testWhileIdle} is set.
*/
public void testAllIdle() {
try {
if (idle.size()==0) return;
Iterator<PooledConnection> unlocked = idle.iterator();
while (unlocked.hasNext()) {
PooledConnection con = unlocked.next();
try {
con.lock();
//the con been taken out, we can't clean it up
if (busy.contains(con))
continue;
if (!con.validate(PooledConnection.VALIDATE_IDLE)) {
idle.remove(con);
release(con);
}
} finally {
con.unlock();
}
} //while
} catch (ConcurrentModificationException e) {
log.debug("testAllIdle failed." ,e);
} catch (Exception e) {
log.warn("testAllIdle failed, it will be retried.",e);
}
}
/**
* Creates a stack trace representing the existing thread's current state.
* @return a string object representing the current state.
* TODO investigate if we simply should store {@link java.lang.Thread#getStackTrace()} elements
*/
protected static String getThreadDump() {
Exception x = new Exception();
x.fillInStackTrace();
return getStackTrace(x);
}
/**
* Convert an exception into a String
* @param x - the throwable
* @return a string representing the stack trace
*/
public static String getStackTrace(Throwable x) {
if (x == null) {
return null;
} else {
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.PrintStream writer = new java.io.PrintStream(bout);
x.printStackTrace(writer);
String result = bout.toString();
return (x.getMessage()!=null && x.getMessage().length()>0)? x.getMessage()+";"+result:result;
} //end if
}
/**
* Create a new pooled connection object. Not connected nor validated.
* @return a pooled connection object
*/
protected PooledConnection create(boolean incrementCounter) {
if (incrementCounter) size.incrementAndGet();
PooledConnection con = new PooledConnection(getPoolProperties(), this);
return con;
}
/**
* Purges all connections in the pool.
* For connections currently in use, these connections will be
* purged when returned on the pool. This call also
* purges connections that are idle and in the pool
* To only purge used/active connections see {@link #purgeOnReturn()}
*/
public void purge() {
purgeOnReturn();
checkIdle(true);
}
/**
* Purges connections when they are returned from the pool.
* This call does not purge idle connections until they are used.
* To purge idle connections see {@link #purge()}
*/
public void purgeOnReturn() {
poolVersion.incrementAndGet();
}
/**
* Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded
* @param con
*/
protected void finalize(PooledConnection con) {
JdbcInterceptor handler = con.getHandler();
while (handler!=null) {
handler.reset(null, null);
handler=handler.getNext();
}
}
/**
* Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded
* @param con
*/
protected void disconnectEvent(PooledConnection con, boolean finalizing) {
JdbcInterceptor handler = con.getHandler();
while (handler!=null) {
handler.disconnected(this, con, finalizing);
handler=handler.getNext();
}
}
/**
* Return the object that is potentially registered in JMX for notifications
* @return the object implementing the {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} interface
*/
public org.apache.tomcat.jdbc.pool.jmx.ConnectionPool getJmxPool() {
return jmxPool;
}
/**
* Create MBean object that can be registered.
*/
protected void createMBean() {
try {
jmxPool = new org.apache.tomcat.jdbc.pool.jmx.ConnectionPool(this);
} catch (Exception x) {
log.warn("Unable to start JMX integration for connection pool. Instance["+getName()+"] can't be monitored.",x);
}
}
/**
* Tread safe wrapper around a future for the regular queue
* This one retrieves the pooled connection object
* and performs the initialization according to
* interceptors and validation rules.
* This class is thread safe and is cancellable
* @author fhanik
*
*/
protected class ConnectionFuture implements Future<Connection>, Runnable {
Future<PooledConnection> pcFuture = null;
AtomicBoolean configured = new AtomicBoolean(false);
CountDownLatch latch = new CountDownLatch(1);
volatile Connection result = null;
SQLException cause = null;
AtomicBoolean cancelled = new AtomicBoolean(false);
volatile PooledConnection pc = null;
public ConnectionFuture(Future<PooledConnection> pcf) {
this.pcFuture = pcf;
}
public ConnectionFuture(PooledConnection pc) throws SQLException {
this.pc = pc;
result = ConnectionPool.this.setupConnection(pc);
configured.set(true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (pc!=null) {
return false;
} else if ((!cancelled.get()) && cancelled.compareAndSet(false, true)) {
//cancel by retrieving the connection and returning it to the pool
ConnectionPool.this.cancellator.execute(this);
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Connection get() throws InterruptedException, ExecutionException {
try {
return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}catch (TimeoutException x) {
throw new ExecutionException(x);
}
}
/**
* {@inheritDoc}
*/
@Override
public Connection get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
PooledConnection pc = this.pc!=null?this.pc:pcFuture.get(timeout,unit);
if (pc!=null) {
if (result!=null) return result;
if (configured.compareAndSet(false, true)) {
try {
pc = borrowConnection(System.currentTimeMillis(),pc, null, null);
result = ConnectionPool.this.setupConnection(pc);
} catch (SQLException x) {
cause = x;
} finally {
latch.countDown();
}
} else {
//if we reach here, another thread is configuring the actual connection
latch.await(timeout,unit); //this shouldn't block for long
}
if (result==null) throw new ExecutionException(cause);
return result;
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCancelled() {
return pc==null && (pcFuture.isCancelled() || cancelled.get());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDone() {
return pc!=null || pcFuture.isDone();
}
/**
* run method to be executed when cancelled by an executor
*/
@Override
public void run() {
try {
Connection con = get(); //complete this future
con.close(); //return to the pool
}catch (ExecutionException ex) {
//we can ignore this
}catch (Exception x) {
ConnectionPool.log.error("Unable to cancel ConnectionFuture.",x);
}
}
}
private static volatile Timer poolCleanTimer = null;
private static HashSet<PoolCleaner> cleaners = new HashSet<>();
private static synchronized void registerCleaner(PoolCleaner cleaner) {
unregisterCleaner(cleaner);
cleaners.add(cleaner);
if (poolCleanTimer == null) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(ConnectionPool.class.getClassLoader());
poolCleanTimer = new Timer("PoolCleaner["+ System.identityHashCode(ConnectionPool.class.getClassLoader()) + ":"+
System.currentTimeMillis() + "]", true);
}finally {
Thread.currentThread().setContextClassLoader(loader);
}
}
poolCleanTimer.scheduleAtFixedRate(cleaner, cleaner.sleepTime,cleaner.sleepTime);
}
private static synchronized void unregisterCleaner(PoolCleaner cleaner) {
boolean removed = cleaners.remove(cleaner);
if (removed) {
cleaner.cancel();
if (poolCleanTimer != null) {
poolCleanTimer.purge();
if (cleaners.size() == 0) {
poolCleanTimer.cancel();
poolCleanTimer = null;
}
}
}
}
public static Set<TimerTask> getPoolCleaners() {
return Collections.<TimerTask>unmodifiableSet(cleaners);
}
public long getPoolVersion() {
return poolVersion.get();
}
public static Timer getPoolTimer() {
return poolCleanTimer;
}
protected static class PoolCleaner extends TimerTask {
protected WeakReference<ConnectionPool> pool;
protected long sleepTime;
protected volatile long lastRun = 0;
PoolCleaner(ConnectionPool pool, long sleepTime) {
this.pool = new WeakReference<>(pool);
this.sleepTime = sleepTime;
if (sleepTime <= 0) {
log.warn("Database connection pool evicter thread interval is set to 0, defaulting to 30 seconds");
this.sleepTime = 1000 * 30;
} else if (sleepTime < 1000) {
log.warn("Database connection pool evicter thread interval is set to lower than 1 second.");
}
}
@Override
public void run() {
ConnectionPool pool = this.pool.get();
if (pool == null) {
stopRunning();
} else if (!pool.isClosed() &&
(System.currentTimeMillis() - lastRun) > sleepTime) {
lastRun = System.currentTimeMillis();
try {
if (pool.getPoolProperties().isRemoveAbandoned())
pool.checkAbandoned();
if (pool.getPoolProperties().getMinIdle() < pool.idle
.size())
pool.checkIdle();
if (pool.getPoolProperties().isTestWhileIdle())
pool.testAllIdle();
} catch (Exception x) {
log.error("", x);
}
}
}
public void start() {
registerCleaner(this);
}
public void stopRunning() {
unregisterCleaner(this);
}
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java
|
/*
* 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.jdbc.pool;
import java.sql.Connection;
import java.util.Hashtable;
import java.util.Properties;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* <p>JNDI object factory that creates an instance of
* <code>BasicDataSource</code> that has been configured based on the
* <code>RefAddr</code> values of the specified <code>Reference</code>,
* which must match the names and data types of the
* <code>BasicDataSource</code> bean properties.</p>
* <br/>
* Properties available for configuration:<br/>
* <a href="http://commons.apache.org/dbcp/configuration.html">Commons DBCP properties</a><br/>
*<ol>
* <li>initSQL - A query that gets executed once, right after the connection is established.</li>
* <li>testOnConnect - run validationQuery after connection has been established.</li>
* <li>validationInterval - avoid excess validation, only run validation at most at this frequency - time in milliseconds.</li>
* <li>jdbcInterceptors - a semicolon separated list of classnames extending {@link JdbcInterceptor} class.</li>
* <li>jmxEnabled - true of false, whether to register the pool with JMX.</li>
* <li>fairQueue - true of false, whether the pool should sacrifice a little bit of performance for true fairness.</li>
*</ol>
* @author Craig R. McClanahan
* @author Dirk Verbeeck
* @author Filip Hanik
*/
public class DataSourceFactory implements ObjectFactory {
private static final Log log = LogFactory.getLog(DataSourceFactory.class);
protected static final String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
protected static final String PROP_DEFAULTREADONLY = "defaultReadOnly";
protected static final String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
protected static final String PROP_DEFAULTCATALOG = "defaultCatalog";
protected static final String PROP_DRIVERCLASSNAME = "driverClassName";
protected static final String PROP_PASSWORD = "password";
protected static final String PROP_URL = "url";
protected static final String PROP_USERNAME = "username";
protected static final String PROP_MAXACTIVE = "maxActive";
protected static final String PROP_MAXIDLE = "maxIdle";
protected static final String PROP_MINIDLE = "minIdle";
protected static final String PROP_INITIALSIZE = "initialSize";
protected static final String PROP_MAXWAIT = "maxWait";
protected static final String PROP_MAXAGE = "maxAge";
protected static final String PROP_TESTONBORROW = "testOnBorrow";
protected static final String PROP_TESTONRETURN = "testOnReturn";
protected static final String PROP_TESTWHILEIDLE = "testWhileIdle";
protected static final String PROP_TESTONCONNECT = "testOnConnect";
protected static final String PROP_VALIDATIONQUERY = "validationQuery";
protected static final String PROP_VALIDATOR_CLASS_NAME = "validatorClassName";
protected static final String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
protected static final String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
protected static final String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
protected static final String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
protected static final String PROP_REMOVEABANDONED = "removeAbandoned";
protected static final String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
protected static final String PROP_LOGABANDONED = "logAbandoned";
protected static final String PROP_ABANDONWHENPERCENTAGEFULL = "abandonWhenPercentageFull";
protected static final String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
protected static final String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
protected static final String PROP_CONNECTIONPROPERTIES = "connectionProperties";
protected static final String PROP_INITSQL = "initSQL";
protected static final String PROP_INTERCEPTORS = "jdbcInterceptors";
protected static final String PROP_VALIDATIONINTERVAL = "validationInterval";
protected static final String PROP_JMX_ENABLED = "jmxEnabled";
protected static final String PROP_FAIR_QUEUE = "fairQueue";
protected static final String PROP_USE_EQUALS = "useEquals";
protected static final String PROP_USE_CON_LOCK = "useLock";
protected static final String PROP_DATASOURCE= "dataSource";
protected static final String PROP_DATASOURCE_JNDI = "dataSourceJNDI";
protected static final String PROP_SUSPECT_TIMEOUT = "suspectTimeout";
protected static final String PROP_ALTERNATE_USERNAME_ALLOWED = "alternateUsernameAllowed";
protected static final String PROP_COMMITONRETURN = "commitOnReturn";
protected static final String PROP_ROLLBACKONRETURN = "rollbackOnReturn";
protected static final String PROP_USEDISPOSABLECONNECTIONFACADE = "useDisposableConnectionFacade";
protected static final String PROP_LOGVALIDATIONERRORS = "logValidationErrors";
protected static final String PROP_PROPAGATEINTERRUPTSTATE = "propagateInterruptState";
protected static final String PROP_IGNOREEXCEPTIONONPRELOAD = "ignoreExceptionOnPreLoad";
public static final int UNKNOWN_TRANSACTIONISOLATION = -1;
public static final String OBJECT_NAME = "object_name";
protected static final String[] ALL_PROPERTIES = {
PROP_DEFAULTAUTOCOMMIT,
PROP_DEFAULTREADONLY,
PROP_DEFAULTTRANSACTIONISOLATION,
PROP_DEFAULTCATALOG,
PROP_DRIVERCLASSNAME,
PROP_MAXACTIVE,
PROP_MAXIDLE,
PROP_MINIDLE,
PROP_INITIALSIZE,
PROP_MAXWAIT,
PROP_TESTONBORROW,
PROP_TESTONRETURN,
PROP_TIMEBETWEENEVICTIONRUNSMILLIS,
PROP_NUMTESTSPEREVICTIONRUN,
PROP_MINEVICTABLEIDLETIMEMILLIS,
PROP_TESTWHILEIDLE,
PROP_TESTONCONNECT,
PROP_PASSWORD,
PROP_URL,
PROP_USERNAME,
PROP_VALIDATIONQUERY,
PROP_VALIDATOR_CLASS_NAME,
PROP_VALIDATIONINTERVAL,
PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED,
PROP_REMOVEABANDONED,
PROP_REMOVEABANDONEDTIMEOUT,
PROP_LOGABANDONED,
PROP_POOLPREPAREDSTATEMENTS,
PROP_MAXOPENPREPAREDSTATEMENTS,
PROP_CONNECTIONPROPERTIES,
PROP_INITSQL,
PROP_INTERCEPTORS,
PROP_JMX_ENABLED,
PROP_FAIR_QUEUE,
PROP_USE_EQUALS,
OBJECT_NAME,
PROP_ABANDONWHENPERCENTAGEFULL,
PROP_MAXAGE,
PROP_USE_CON_LOCK,
PROP_DATASOURCE,
PROP_DATASOURCE_JNDI,
PROP_SUSPECT_TIMEOUT,
PROP_ALTERNATE_USERNAME_ALLOWED,
PROP_COMMITONRETURN,
PROP_ROLLBACKONRETURN,
PROP_USEDISPOSABLECONNECTIONFACADE,
PROP_LOGVALIDATIONERRORS,
PROP_PROPAGATEINTERRUPTSTATE,
PROP_IGNOREEXCEPTIONONPRELOAD
};
// -------------------------------------------------- ObjectFactory Methods
/**
* <p>Create and return a new <code>BasicDataSource</code> instance. If no
* instance can be created, return <code>null</code> instead.</p>
*
* @param obj The possibly null object containing location or
* reference information that can be used in creating an object
* @param name The name of this object relative to <code>nameCtx</code>
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or <code>null</code> if <code>name</code>
* is relative to the default initial context
* @param environment The possibly null environment that is used in
* creating this object
*
* @exception Exception if an exception occurs creating the instance
*/
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment) throws Exception {
// We only know how to deal with <code>javax.naming.Reference</code>s
// that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference)) {
return null;
}
Reference ref = (Reference) obj;
boolean XA = false;
boolean ok = false;
if ("javax.sql.DataSource".equals(ref.getClassName())) {
ok = true;
}
if ("javax.sql.XADataSource".equals(ref.getClassName())) {
ok = true;
XA = true;
}
if (org.apache.tomcat.jdbc.pool.DataSource.class.getName().equals(ref.getClassName())) {
ok = true;
}
if (!ok) {
log.warn(ref.getClassName()+" is not a valid class name/type for this JNDI factory.");
return null;
}
Properties properties = new Properties();
for (int i = 0; i < ALL_PROPERTIES.length; i++) {
String propertyName = ALL_PROPERTIES[i];
RefAddr ra = ref.get(propertyName);
if (ra != null) {
String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue);
}
}
return createDataSource(properties,nameCtx,XA);
}
public static PoolConfiguration parsePoolProperties(Properties properties) {
PoolConfiguration poolProperties = new PoolProperties();
String value = null;
value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
poolProperties.setDefaultAutoCommit(Boolean.valueOf(value));
}
value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
poolProperties.setDefaultReadOnly(Boolean.valueOf(value));
}
value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = UNKNOWN_TRANSACTIONISOLATION;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
} else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
} else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
} else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
} else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
} else {
try {
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation: " + value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = UNKNOWN_TRANSACTIONISOLATION;
}
}
poolProperties.setDefaultTransactionIsolation(level);
}
value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
poolProperties.setDefaultCatalog(value);
}
value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
poolProperties.setDriverClassName(value);
}
value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
poolProperties.setMaxActive(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
poolProperties.setMaxIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
poolProperties.setMinIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
poolProperties.setInitialSize(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
poolProperties.setMaxWait(Integer.parseInt(value));
}
value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
poolProperties.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
poolProperties.setTestOnReturn(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONCONNECT);
if (value != null) {
poolProperties.setTestOnConnect(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
poolProperties.setTimeBetweenEvictionRunsMillis(Integer.parseInt(value));
}
value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
poolProperties.setNumTestsPerEvictionRun(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
poolProperties.setMinEvictableIdleTimeMillis(Integer.parseInt(value));
}
value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
poolProperties.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
poolProperties.setPassword(value);
}
value = properties.getProperty(PROP_URL);
if (value != null) {
poolProperties.setUrl(value);
}
value = properties.getProperty(PROP_USERNAME);
if (value != null) {
poolProperties.setUsername(value);
}
value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
poolProperties.setValidationQuery(value);
}
value = properties.getProperty(PROP_VALIDATOR_CLASS_NAME);
if (value != null) {
poolProperties.setValidatorClassName(value);
}
value = properties.getProperty(PROP_VALIDATIONINTERVAL);
if (value != null) {
poolProperties.setValidationInterval(Long.parseLong(value));
}
value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
poolProperties.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONED);
if (value != null) {
poolProperties.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
if (value != null) {
poolProperties.setRemoveAbandonedTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_LOGABANDONED);
if (value != null) {
poolProperties.setLogAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
log.warn(PROP_POOLPREPAREDSTATEMENTS + " is not a valid setting, it will have no effect.");
}
value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
log.warn(PROP_MAXOPENPREPAREDSTATEMENTS + " is not a valid setting, it will have no effect.");
}
value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
poolProperties.setDbProperties(p);
} else {
poolProperties.setDbProperties(new Properties());
}
if (poolProperties.getUsername()!=null) {
poolProperties.getDbProperties().setProperty("user",poolProperties.getUsername());
}
if (poolProperties.getPassword()!=null) {
poolProperties.getDbProperties().setProperty("password",poolProperties.getPassword());
}
value = properties.getProperty(PROP_INITSQL);
if (value != null) {
poolProperties.setInitSQL(value);
}
value = properties.getProperty(PROP_INTERCEPTORS);
if (value != null) {
poolProperties.setJdbcInterceptors(value);
}
value = properties.getProperty(PROP_JMX_ENABLED);
if (value != null) {
poolProperties.setJmxEnabled(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_FAIR_QUEUE);
if (value != null) {
poolProperties.setFairQueue(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_USE_EQUALS);
if (value != null) {
poolProperties.setUseEquals(Boolean.parseBoolean(value));
}
value = properties.getProperty(OBJECT_NAME);
if (value != null) {
poolProperties.setName(ObjectName.quote(value));
}
value = properties.getProperty(PROP_ABANDONWHENPERCENTAGEFULL);
if (value != null) {
poolProperties.setAbandonWhenPercentageFull(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXAGE);
if (value != null) {
poolProperties.setMaxAge(Long.parseLong(value));
}
value = properties.getProperty(PROP_USE_CON_LOCK);
if (value != null) {
poolProperties.setUseLock(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_DATASOURCE);
if (value != null) {
//this should never happen
throw new IllegalArgumentException("Can't set dataSource property as a string, this must be a javax.sql.DataSource object.");
}
value = properties.getProperty(PROP_DATASOURCE_JNDI);
if (value != null) {
poolProperties.setDataSourceJNDI(value);
}
value = properties.getProperty(PROP_SUSPECT_TIMEOUT);
if (value != null) {
poolProperties.setSuspectTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_ALTERNATE_USERNAME_ALLOWED);
if (value != null) {
poolProperties.setAlternateUsernameAllowed(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_COMMITONRETURN);
if (value != null) {
poolProperties.setCommitOnReturn(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_ROLLBACKONRETURN);
if (value != null) {
poolProperties.setRollbackOnReturn(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_USEDISPOSABLECONNECTIONFACADE);
if (value != null) {
poolProperties.setUseDisposableConnectionFacade(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_LOGVALIDATIONERRORS);
if (value != null) {
poolProperties.setLogValidationErrors(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_PROPAGATEINTERRUPTSTATE);
if (value != null) {
poolProperties.setPropagateInterruptState(Boolean.parseBoolean(value));
}
value = properties.getProperty(PROP_IGNOREEXCEPTIONONPRELOAD);
if (value != null) {
poolProperties.setIgnoreExceptionOnPreLoad(Boolean.parseBoolean(value));
}
return poolProperties;
}
/**
* Creates and configures a {@link DataSource} instance based on the
* given properties.
*
* @param properties the datasource configuration properties
* @throws Exception if an error occurs creating the data source
*/
public DataSource createDataSource(Properties properties) throws Exception {
return createDataSource(properties,null,false);
}
public DataSource createDataSource(Properties properties,Context context, boolean XA) throws Exception {
PoolConfiguration poolProperties = DataSourceFactory.parsePoolProperties(properties);
if (poolProperties.getDataSourceJNDI()!=null && poolProperties.getDataSource()==null) {
performJNDILookup(context, poolProperties);
}
org.apache.tomcat.jdbc.pool.DataSource dataSource = XA?
new org.apache.tomcat.jdbc.pool.XADataSource(poolProperties) :
new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
//initialise the pool itself
dataSource.createPool();
// Return the configured DataSource instance
return dataSource;
}
public void performJNDILookup(Context context, PoolConfiguration poolProperties) {
Object jndiDS = null;
try {
if (context!=null) {
jndiDS = context.lookup(poolProperties.getDataSourceJNDI());
} else {
log.warn("dataSourceJNDI property is configued, but local JNDI context is null.");
}
} catch (NamingException e) {
log.debug("The name \""+poolProperties.getDataSourceJNDI()+"\" can not be found in the local context.");
}
if (jndiDS==null) {
try {
context = new InitialContext();
jndiDS = context.lookup(poolProperties.getDataSourceJNDI());
} catch (NamingException e) {
log.warn("The name \""+poolProperties.getDataSourceJNDI()+"\" can not be found in the InitialContext.");
}
}
if (jndiDS!=null) {
poolProperties.setDataSource(jndiDS);
}
}
/**
* <p>Parse properties from the string. Format of the string must be [propertyName=property;]*<p>
* @param propText
* @return Properties
* @throws Exception
*/
protected static Properties getProperties(String propText) {
return PoolProperties.getProperties(propText,null);
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java
|
/*
* 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.jdbc.pool;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.sql.XAConnection;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition;
/**
*
* The DataSource proxy lets us implements methods that don't exist in the current
* compiler JDK but might be methods that are part of a future JDK DataSource interface.
* <br/>
* It's a trick to work around compiler issues when implementing interfaces. For example,
* I could put in Java 6 methods of javax.sql.DataSource here, and compile it with JDK 1.5
* and still be able to run under Java 6 without getting NoSuchMethodException.
*
* @author Filip Hanik
* @version 1.0
*/
public class DataSourceProxy implements PoolConfiguration {
private static final Log log = LogFactory.getLog(DataSourceProxy.class);
protected volatile ConnectionPool pool = null;
protected volatile PoolConfiguration poolProperties = null;
public DataSourceProxy() {
this(new PoolProperties());
}
public DataSourceProxy(PoolConfiguration poolProperties) {
if (poolProperties == null) throw new NullPointerException("PoolConfiguration can not be null.");
this.poolProperties = poolProperties;
}
@SuppressWarnings("unused") // Has to match signature in DataSource
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// we are not a wrapper of anything
return false;
}
@SuppressWarnings("unused") // Has to match signature in DataSource
public <T> T unwrap(Class<T> iface) throws SQLException {
//we can't unwrap anything
return null;
}
/**
* {@link javax.sql.DataSource#getConnection()}
*/
public Connection getConnection(String username, String password) throws SQLException {
if (this.getPoolProperties().isAlternateUsernameAllowed()) {
if (pool == null)
return createPool().getConnection(username,password);
return pool.getConnection(username,password);
} else {
return getConnection();
}
}
public PoolConfiguration getPoolProperties() {
return poolProperties;
}
/**
* Sets up the connection pool, by creating a pooling driver.
* @return Driver
* @throws SQLException
*/
public ConnectionPool createPool() throws SQLException {
if (pool != null) {
return pool;
} else {
return pCreatePool();
}
}
/**
* Sets up the connection pool, by creating a pooling driver.
* @return Driver
* @throws SQLException
*/
private synchronized ConnectionPool pCreatePool() throws SQLException {
if (pool != null) {
return pool;
} else {
pool = new ConnectionPool(poolProperties);
return pool;
}
}
/**
* {@link javax.sql.DataSource#getConnection()}
*/
public Connection getConnection() throws SQLException {
if (pool == null)
return createPool().getConnection();
return pool.getConnection();
}
/**
* Invokes an sync operation to retrieve the connection.
* @return a Future containing a reference to the connection when it becomes available
* @throws SQLException
*/
public Future<Connection> getConnectionAsync() throws SQLException {
if (pool == null)
return createPool().getConnectionAsync();
return pool.getConnectionAsync();
}
/**
* {@link javax.sql.XADataSource#getXAConnection()}
*/
public XAConnection getXAConnection() throws SQLException {
Connection con = getConnection();
if (con instanceof XAConnection) {
return (XAConnection)con;
} else {
try {
con.close();
} catch (Exception ignore) {
// Ignore
}
throw new SQLException("Connection from pool does not implement javax.sql.XAConnection");
}
}
/**
* {@link javax.sql.XADataSource#getXAConnection(String, String)}
*/
public XAConnection getXAConnection(String username, String password) throws SQLException {
Connection con = getConnection(username, password);
if (con instanceof XAConnection) {
return (XAConnection)con;
} else {
try {
con.close();
} catch (Exception ignore) {
// Ignore
}
throw new SQLException("Connection from pool does not implement javax.sql.XAConnection");
}
}
/**
* {@link javax.sql.DataSource#getConnection()}
*/
public javax.sql.PooledConnection getPooledConnection() throws SQLException {
return (javax.sql.PooledConnection) getConnection();
}
/**
* {@link javax.sql.DataSource#getConnection()}
* @param username unused
* @param password unused
*/
public javax.sql.PooledConnection getPooledConnection(String username,
String password) throws SQLException {
return (javax.sql.PooledConnection) getConnection();
}
public ConnectionPool getPool() {
return pool;
}
public void close() {
close(false);
}
public void close(boolean all) {
try {
if (pool != null) {
final ConnectionPool p = pool;
pool = null;
if (p!=null) {
p.close(all);
}
}
}catch (Exception x) {
log.warn("Error duing connection pool closure.", x);
}
}
public int getPoolSize() {
final ConnectionPool p = pool;
if (p == null) return 0;
else return p.getSize();
}
@Override
public String toString() {
return super.toString()+"{"+getPoolProperties()+"}";
}
/*-----------------------------------------------------------------------*/
// PROPERTIES WHEN NOT USED WITH FACTORY
/*------------------------------------------------------------------------*/
/**
* {@inheritDoc}
*/
@Override
public String getPoolName() {
return pool.getName();
}
public void setPoolProperties(PoolConfiguration poolProperties) {
this.poolProperties = poolProperties;
}
/**
* {@inheritDoc}
*/
@Override
public void setDriverClassName(String driverClassName) {
this.poolProperties.setDriverClassName(driverClassName);
}
/**
* {@inheritDoc}
*/
@Override
public void setInitialSize(int initialSize) {
this.poolProperties.setInitialSize(initialSize);
}
/**
* {@inheritDoc}
*/
@Override
public void setInitSQL(String initSQL) {
this.poolProperties.setInitSQL(initSQL);
}
/**
* {@inheritDoc}
*/
@Override
public void setLogAbandoned(boolean logAbandoned) {
this.poolProperties.setLogAbandoned(logAbandoned);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxActive(int maxActive) {
this.poolProperties.setMaxActive(maxActive);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxIdle(int maxIdle) {
this.poolProperties.setMaxIdle(maxIdle);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxWait(int maxWait) {
this.poolProperties.setMaxWait(maxWait);
}
/**
* {@inheritDoc}
*/
@Override
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.poolProperties.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
}
/**
* {@inheritDoc}
*/
@Override
public void setMinIdle(int minIdle) {
this.poolProperties.setMinIdle(minIdle);
}
/**
* {@inheritDoc}
*/
@Override
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.poolProperties.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
}
/**
* {@inheritDoc}
*/
@Override
public void setPassword(String password) {
this.poolProperties.setPassword(password);
this.poolProperties.getDbProperties().setProperty("password",this.poolProperties.getPassword());
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandoned(boolean removeAbandoned) {
this.poolProperties.setRemoveAbandoned(removeAbandoned);
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
this.poolProperties.setRemoveAbandonedTimeout(removeAbandonedTimeout);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnBorrow(boolean testOnBorrow) {
this.poolProperties.setTestOnBorrow(testOnBorrow);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnConnect(boolean testOnConnect) {
this.poolProperties.setTestOnConnect(testOnConnect);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnReturn(boolean testOnReturn) {
this.poolProperties.setTestOnReturn(testOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public void setTestWhileIdle(boolean testWhileIdle) {
this.poolProperties.setTestWhileIdle(testWhileIdle);
}
/**
* {@inheritDoc}
*/
@Override
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.poolProperties.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
}
/**
* {@inheritDoc}
*/
@Override
public void setUrl(String url) {
this.poolProperties.setUrl(url);
}
/**
* {@inheritDoc}
*/
@Override
public void setUsername(String username) {
this.poolProperties.setUsername(username);
this.poolProperties.getDbProperties().setProperty("user",getPoolProperties().getUsername());
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationInterval(long validationInterval) {
this.poolProperties.setValidationInterval(validationInterval);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationQuery(String validationQuery) {
this.poolProperties.setValidationQuery(validationQuery);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidatorClassName(String className) {
this.poolProperties.setValidatorClassName(className);
}
/**
* {@inheritDoc}
*/
@Override
public void setJdbcInterceptors(String interceptors) {
this.getPoolProperties().setJdbcInterceptors(interceptors);
}
/**
* {@inheritDoc}
*/
@Override
public void setJmxEnabled(boolean enabled) {
this.getPoolProperties().setJmxEnabled(enabled);
}
/**
* {@inheritDoc}
*/
@Override
public void setFairQueue(boolean fairQueue) {
this.getPoolProperties().setFairQueue(fairQueue);
}
/**
* {@inheritDoc}
*/
@Override
public void setUseLock(boolean useLock) {
this.getPoolProperties().setUseLock(useLock);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultCatalog(String catalog) {
this.getPoolProperties().setDefaultCatalog(catalog);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultAutoCommit(Boolean autocommit) {
this.getPoolProperties().setDefaultAutoCommit(autocommit);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
this.getPoolProperties().setDefaultTransactionIsolation(defaultTransactionIsolation);
}
/**
* {@inheritDoc}
*/
@Override
public void setConnectionProperties(String properties) {
try {
java.util.Properties prop = DataSourceFactory
.getProperties(properties);
Iterator<?> i = prop.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
String value = prop.getProperty(key);
getPoolProperties().getDbProperties().setProperty(key, value);
}
} catch (Exception x) {
log.error("Unable to parse connection properties.", x);
throw new RuntimeException(x);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setUseEquals(boolean useEquals) {
this.getPoolProperties().setUseEquals(useEquals);
}
/**
* no-op
* {@link javax.sql.DataSource#getParentLogger}
*/
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
/**
* no-op
* {@link javax.sql.DataSource#getLogWriter}
*/
@SuppressWarnings("unused") // Has to match signature in DataSource
public PrintWriter getLogWriter() throws SQLException {
return null;
}
/**
* no-op
* {@link javax.sql.DataSource#setLogWriter(PrintWriter)}
*/
@SuppressWarnings("unused") // Has to match signature in DataSource
public void setLogWriter(PrintWriter out) throws SQLException {
// NOOP
}
/**
* no-op
* {@link javax.sql.DataSource#getLoginTimeout}
*/
public int getLoginTimeout() {
if (poolProperties == null) {
return 0;
} else {
return poolProperties.getMaxWait() / 1000;
}
}
/**
* {@link javax.sql.DataSource#setLoginTimeout(int)}
*/
public void setLoginTimeout(int i) {
if (poolProperties == null) {
return;
} else {
poolProperties.setMaxWait(1000 * i);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getSuspectTimeout() {
return getPoolProperties().getSuspectTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public void setSuspectTimeout(int seconds) {
getPoolProperties().setSuspectTimeout(seconds);
}
//===============================================================================
// Expose JMX attributes through Tomcat's dynamic reflection
//===============================================================================
/**
* If the pool has not been created, it will be created during this call.
* @return the number of established but idle connections
*/
public int getIdle() {
try {
return createPool().getIdle();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* {@link #getIdle()}
*/
public int getNumIdle() {
return getIdle();
}
/**
* Forces an abandon check on the connection pool.
* If connections that have been abandoned exists, they will be closed during this run
*/
public void checkAbandoned() {
try {
createPool().checkAbandoned();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* Forces a check for resizing of the idle connections
*/
public void checkIdle() {
try {
createPool().checkIdle();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* @return number of connections in use by the application
*/
public int getActive() {
try {
return createPool().getActive();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* @return number of connections in use by the application
* {@link DataSource#getActive()}
*/
public int getNumActive() {
return getActive();
}
/**
* @return number of threads waiting for a connection
*/
public int getWaitCount() {
try {
return createPool().getWaitCount();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* @return the current size of the pool
*/
public int getSize() {
try {
return createPool().getSize();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
/**
* Performs a validation on idle connections
*/
public void testIdle() {
try {
createPool().testAllIdle();
}catch (SQLException x) {
throw new RuntimeException(x);
}
}
//=========================================================
// PROPERTIES / CONFIGURATION
//=========================================================
/**
* {@inheritDoc}
*/
@Override
public String getConnectionProperties() {
return getPoolProperties().getConnectionProperties();
}
/**
* {@inheritDoc}
*/
@Override
public Properties getDbProperties() {
return getPoolProperties().getDbProperties();
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultCatalog() {
return getPoolProperties().getDefaultCatalog();
}
/**
* {@inheritDoc}
*/
@Override
public int getDefaultTransactionIsolation() {
return getPoolProperties().getDefaultTransactionIsolation();
}
/**
* {@inheritDoc}
*/
@Override
public String getDriverClassName() {
return getPoolProperties().getDriverClassName();
}
/**
* {@inheritDoc}
*/
@Override
public int getInitialSize() {
return getPoolProperties().getInitialSize();
}
/**
* {@inheritDoc}
*/
@Override
public String getInitSQL() {
return getPoolProperties().getInitSQL();
}
/**
* {@inheritDoc}
*/
@Override
public String getJdbcInterceptors() {
return getPoolProperties().getJdbcInterceptors();
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxActive() {
return getPoolProperties().getMaxActive();
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxIdle() {
return getPoolProperties().getMaxIdle();
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxWait() {
return getPoolProperties().getMaxWait();
}
/**
* {@inheritDoc}
*/
@Override
public int getMinEvictableIdleTimeMillis() {
return getPoolProperties().getMinEvictableIdleTimeMillis();
}
/**
* {@inheritDoc}
*/
@Override
public int getMinIdle() {
return getPoolProperties().getMinIdle();
}
/**
* {@inheritDoc}
*/
@Override
public long getMaxAge() {
return getPoolProperties().getMaxAge();
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return getPoolProperties().getName();
}
/**
* {@inheritDoc}
*/
@Override
public int getNumTestsPerEvictionRun() {
return getPoolProperties().getNumTestsPerEvictionRun();
}
/**
* @return DOES NOT RETURN THE PASSWORD, IT WOULD SHOW UP IN JMX
*/
@Override
public String getPassword() {
return "Password not available as DataSource/JMX operation.";
}
/**
* {@inheritDoc}
*/
@Override
public int getRemoveAbandonedTimeout() {
return getPoolProperties().getRemoveAbandonedTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public int getTimeBetweenEvictionRunsMillis() {
return getPoolProperties().getTimeBetweenEvictionRunsMillis();
}
/**
* {@inheritDoc}
*/
@Override
public String getUrl() {
return getPoolProperties().getUrl();
}
/**
* {@inheritDoc}
*/
@Override
public String getUsername() {
return getPoolProperties().getUsername();
}
/**
* {@inheritDoc}
*/
@Override
public long getValidationInterval() {
return getPoolProperties().getValidationInterval();
}
/**
* {@inheritDoc}
*/
@Override
public String getValidationQuery() {
return getPoolProperties().getValidationQuery();
}
/**
* {@inheritDoc}
*/
@Override
public String getValidatorClassName() {
return getPoolProperties().getValidatorClassName();
}
/**
* {@inheritDoc}
*/
@Override
public Validator getValidator() {
return getPoolProperties().getValidator();
}
/**
* {@inheritDoc}
*/
@Override
public void setValidator(Validator validator) {
getPoolProperties().setValidator(validator);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAccessToUnderlyingConnectionAllowed() {
return getPoolProperties().isAccessToUnderlyingConnectionAllowed();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultAutoCommit() {
return getPoolProperties().isDefaultAutoCommit();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultReadOnly() {
return getPoolProperties().isDefaultReadOnly();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLogAbandoned() {
return getPoolProperties().isLogAbandoned();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPoolSweeperEnabled() {
return getPoolProperties().isPoolSweeperEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRemoveAbandoned() {
return getPoolProperties().isRemoveAbandoned();
}
/**
* {@inheritDoc}
*/
@Override
public int getAbandonWhenPercentageFull() {
return getPoolProperties().getAbandonWhenPercentageFull();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnBorrow() {
return getPoolProperties().isTestOnBorrow();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnConnect() {
return getPoolProperties().isTestOnConnect();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnReturn() {
return getPoolProperties().isTestOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestWhileIdle() {
return getPoolProperties().isTestWhileIdle();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultAutoCommit() {
return getPoolProperties().getDefaultAutoCommit();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultReadOnly() {
return getPoolProperties().getDefaultReadOnly();
}
/**
* {@inheritDoc}
*/
@Override
public InterceptorDefinition[] getJdbcInterceptorsAsArray() {
return getPoolProperties().getJdbcInterceptorsAsArray();
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseLock() {
return getPoolProperties().getUseLock();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFairQueue() {
return getPoolProperties().isFairQueue();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isJmxEnabled() {
return getPoolProperties().isJmxEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUseEquals() {
return getPoolProperties().isUseEquals();
}
/**
* {@inheritDoc}
*/
@Override
public void setAbandonWhenPercentageFull(int percentage) {
getPoolProperties().setAbandonWhenPercentageFull(percentage);
}
/**
* {@inheritDoc}
*/
@Override
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) {
getPoolProperties().setAccessToUnderlyingConnectionAllowed(accessToUnderlyingConnectionAllowed);
}
/**
* {@inheritDoc}
*/
@Override
public void setDbProperties(Properties dbProperties) {
getPoolProperties().setDbProperties(dbProperties);
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultReadOnly(Boolean defaultReadOnly) {
getPoolProperties().setDefaultReadOnly(defaultReadOnly);
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxAge(long maxAge) {
getPoolProperties().setMaxAge(maxAge);
}
/**
* {@inheritDoc}
*/
@Override
public void setName(String name) {
getPoolProperties().setName(name);
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSource(Object ds) {
getPoolProperties().setDataSource(ds);
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataSource() {
return getPoolProperties().getDataSource();
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSourceJNDI(String jndiDS) {
getPoolProperties().setDataSourceJNDI(jndiDS);
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSourceJNDI() {
return getPoolProperties().getDataSourceJNDI();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlternateUsernameAllowed() {
return getPoolProperties().isAlternateUsernameAllowed();
}
/**
* {@inheritDoc}
*/
@Override
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) {
getPoolProperties().setAlternateUsernameAllowed(alternateUsernameAllowed);
}
/**
* {@inheritDoc}
*/
@Override
public void setCommitOnReturn(boolean commitOnReturn) {
getPoolProperties().setCommitOnReturn(commitOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCommitOnReturn() {
return getPoolProperties().getCommitOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setRollbackOnReturn(boolean rollbackOnReturn) {
getPoolProperties().setRollbackOnReturn(rollbackOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getRollbackOnReturn() {
return getPoolProperties().getRollbackOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) {
getPoolProperties().setUseDisposableConnectionFacade(useDisposableConnectionFacade);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseDisposableConnectionFacade() {
return getPoolProperties().getUseDisposableConnectionFacade();
}
/**
* {@inheritDoc}
*/
@Override
public void setLogValidationErrors(boolean logValidationErrors) {
getPoolProperties().setLogValidationErrors(logValidationErrors);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getLogValidationErrors() {
return getPoolProperties().getLogValidationErrors();
}
/**
* {@inheritDoc}
*/
@Override
public boolean getPropagateInterruptState() {
return getPoolProperties().getPropagateInterruptState();
}
/**
* {@inheritDoc}
*/
@Override
public void setPropagateInterruptState(boolean propagateInterruptState) {
getPoolProperties().setPropagateInterruptState(propagateInterruptState);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIgnoreExceptionOnPreLoad() {
return getPoolProperties().isIgnoreExceptionOnPreLoad();
}
/**
* {@inheritDoc}
*/
@Override
public void setIgnoreExceptionOnPreLoad(boolean ignoreExceptionOnPreLoad) {
getPoolProperties().setIgnoreExceptionOnPreLoad(ignoreExceptionOnPreLoad);
}
public void purge() {
try {
createPool().purge();
}catch (SQLException x) {
log.error("Unable to purge pool.",x);
}
}
public void purgeOnReturn() {
try {
createPool().purgeOnReturn();
}catch (SQLException x) {
log.error("Unable to purge pool.",x);
}
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java
|
/*
* 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.jdbc.pool;
import java.util.Properties;
import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition;
/**
* A list of properties that are configurable for a connection pool.
* The {@link DataSource} object also implements this interface so that it can be easily configured through
* an IoC container without having to specify a secondary object with a setter method.
* @author fhanik
*
*/
public interface PoolConfiguration {
/**
* JMX prefix for interceptors that register themselves with JMX
*/
public static final String PKG_PREFIX = "org.apache.tomcat.jdbc.pool.interceptor.";
/**
* Connections that have been abandoned (timed out) wont get closed and reported up unless the number of connections in use are
* above the percentage defined by abandonWhenPercentageFull.
* The value should be between 0-100.
* The default value is 0, which implies that connections are eligible for
* closure as soon as removeAbandonedTimeout has been reached.
* @param percentage a value between 0 and 100 to indicate when connections that have been abandoned/timed out are considered abandoned
*/
public void setAbandonWhenPercentageFull(int percentage);
/**
* Connections that have been abandoned (timed out) wont get closed and reported up unless the number of connections in use are
* above the percentage defined by abandonWhenPercentageFull.
* The value should be between 0-100.
* The default value is 0, which implies that connections are eligible for
* closure as soon as removeAbandonedTimeout has been reached.
* @return percentage - a value between 0 and 100 to indicate when connections that have been abandoned/timed out are considered abandoned
*/
public int getAbandonWhenPercentageFull();
/**
* Returns true if a fair queue is being used by the connection pool
* @return true if a fair waiting queue is being used
*/
public boolean isFairQueue();
/**
* Set to true if you wish that calls to getConnection
* should be treated fairly in a true FIFO fashion.
* This uses the {@link FairBlockingQueue} implementation for the list of the idle connections.
* The default value is true.
* This flag is required when you want to use asynchronous connection retrieval.
* @param fairQueue
*/
public void setFairQueue(boolean fairQueue);
/**
* Property not used. Access is always allowed.
* Access can be achieved by calling unwrap on the pooled connection. see {@link javax.sql.DataSource} interface
* or call getConnection through reflection or cast the object as {@link javax.sql.PooledConnection}
* @return true
*/
public boolean isAccessToUnderlyingConnectionAllowed();
/**
* No-op
* @param accessToUnderlyingConnectionAllowed parameter ignored
*/
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed);
/**
* The connection properties that will be sent to the JDBC driver when establishing new connections.
* Format of the string is [propertyName=property;] <br/>
* NOTE - The "user" and "password" properties will be passed explicitly, so they do not need to be included here.
* The default value is null.
*/
public String getConnectionProperties();
/**
* The properties that will be passed into {@link java.sql.Driver#connect(String, Properties)} method.
* Username and password do not need to be stored here, they will be passed into the properties right before the connection is established.
* @param connectionProperties properties - Format of the string is [propertyName=property;]*
* Example: prop1=value1;prop2=value2
*/
public void setConnectionProperties(String connectionProperties);
/**
* Returns the database properties that are passed into the {@link java.sql.Driver#connect(String, Properties)} method.
* @return database properties that are passed into the {@link java.sql.Driver#connect(String, Properties)} method.
*/
public Properties getDbProperties();
/**
* Overrides the database properties passed into the {@link java.sql.Driver#connect(String, Properties)} method.
* @param dbProperties
*/
public void setDbProperties(Properties dbProperties);
/**
* The default auto-commit state of connections created by this pool.
* If not set (null), default is JDBC driver default (If set to null then the {@link java.sql.Connection#setAutoCommit(boolean)} method will not be called.)
* @return the default auto commit setting, null is Driver default.
*/
public Boolean isDefaultAutoCommit();
/**
* The default auto-commit state of connections created by this pool.
* If not set (null), default is JDBC driver default (If set to null then the {@link java.sql.Connection#setAutoCommit(boolean)} method will not be called.)
* @return the default auto commit setting, null is Driver default.
*/
public Boolean getDefaultAutoCommit();
/**
* The default auto-commit state of connections created by this pool.
* If not set (null), default is JDBC driver default (If set to null then the {@link java.sql.Connection#setAutoCommit(boolean)} method will not be called.)
* @param defaultAutoCommit default auto commit setting, null is Driver default.
*/
public void setDefaultAutoCommit(Boolean defaultAutoCommit);
/**
* If non null, during connection creation the method {@link java.sql.Connection#setCatalog(String)} will be called with the set value.
* @return the default catalog, null if not set and accepting the driver default.
*/
public String getDefaultCatalog();
/**
* If non null, during connection creation the method {@link java.sql.Connection#setCatalog(String)} will be called with the set value.
* @param defaultCatalog null if not set and accepting the driver default.
*/
public void setDefaultCatalog(String defaultCatalog);
/**
* If non null, during connection creation the method {@link java.sql.Connection#setReadOnly(boolean)} will be called with the set value.
* @return null if not set and accepting the driver default otherwise the read only value
*/
public Boolean isDefaultReadOnly();
/**
* If non null, during connection creation the method {@link java.sql.Connection#setReadOnly(boolean)} will be called with the set value.
* @return null if not set and accepting the driver default otherwise the read only value
*/
public Boolean getDefaultReadOnly();
/**
* If non null, during connection creation the method {@link java.sql.Connection#setReadOnly(boolean)} will be called with the set value.
* @param defaultReadOnly null if not set and accepting the driver default.
*/
public void setDefaultReadOnly(Boolean defaultReadOnly);
/**
* Returns the default transaction isolation level. If set to {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION} the method
* {@link java.sql.Connection#setTransactionIsolation(int)} will not be called during connection creation.
* @return driver transaction isolation level, or -1 {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION} if not set.
*/
public int getDefaultTransactionIsolation();
/**
* If set to {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION} the method
* {@link java.sql.Connection#setTransactionIsolation(int)} will not be called during connection creation. Otherwise the method
* will be called with the isolation level set by this property.
* @param defaultTransactionIsolation a value of {@link java.sql.Connection#TRANSACTION_NONE}, {@link java.sql.Connection#TRANSACTION_READ_COMMITTED},
* {@link java.sql.Connection#TRANSACTION_READ_UNCOMMITTED}, {@link java.sql.Connection#TRANSACTION_REPEATABLE_READ},
* {@link java.sql.Connection#TRANSACTION_SERIALIZABLE} or {@link DataSourceFactory#UNKNOWN_TRANSACTIONISOLATION}
* The last value will not be set on the connection.
*/
public void setDefaultTransactionIsolation(int defaultTransactionIsolation);
/**
* The fully qualified Java class name of the JDBC driver to be used. The driver has to be accessible from the same classloader as tomcat-jdbc.jar
* @return fully qualified JDBC driver name.
*/
public String getDriverClassName();
/**
* The fully qualified Java class name of the JDBC driver to be used. The driver has to be accessible from the same classloader as tomcat-jdbc.jar
* @param driverClassName a fully qualified Java class name of a {@link java.sql.Driver} implementation.
*/
public void setDriverClassName(String driverClassName);
/**
* Returns the number of connections that will be established when the connection pool is started.
* Default value is 10
* @return number of connections to be started when pool is started
*/
public int getInitialSize();
/**
* Set the number of connections that will be established when the connection pool is started.
* Default value is 10.
* If this value exceeds {@link #setMaxActive(int)} it will automatically be lowered.
* @param initialSize the number of connections to be established.
*
*/
public void setInitialSize(int initialSize);
/**
* boolean flag to set if stack traces should be logged for application code which abandoned a Connection.
* Logging of abandoned Connections adds overhead for every Connection borrow because a stack trace has to be generated.
* The default value is false.
* @return true if the connection pool logs stack traces when connections are borrowed from the pool.
*/
public boolean isLogAbandoned();
/**
* boolean flag to set if stack traces should be logged for application code which abandoned a Connection.
* Logging of abandoned Connections adds overhead for every Connection borrow because a stack trace has to be generated.
* The default value is false.
* @param logAbandoned set to true if stack traces should be recorded when {@link DataSource#getConnection()} is called.
*/
public void setLogAbandoned(boolean logAbandoned);
/**
* The maximum number of active connections that can be allocated from this pool at the same time. The default value is 100
* @return the maximum number of connections used by this pool
*/
public int getMaxActive();
/**
* The maximum number of active connections that can be allocated from this pool at the same time. The default value is 100
* @param maxActive hard limit for number of managed connections by this pool
*/
public void setMaxActive(int maxActive);
/**
* The maximum number of connections that should be kept in the idle pool if {@link #isPoolSweeperEnabled()} returns false.
* If the If {@link #isPoolSweeperEnabled()} returns true, then the idle pool can grow up to {@link #getMaxActive}
* and will be shrunk according to {@link #getMinEvictableIdleTimeMillis()} setting.
* Default value is maxActive:100
* @return the maximum number of idle connections.
*/
public int getMaxIdle();
/**
* The maximum number of connections that should be kept in the idle pool if {@link #isPoolSweeperEnabled()} returns false.
* If the If {@link #isPoolSweeperEnabled()} returns true, then the idle pool can grow up to {@link #getMaxActive}
* and will be shrunk according to {@link #getMinEvictableIdleTimeMillis()} setting.
* Default value is maxActive:100
* @param maxIdle the maximum size of the idle pool
*/
public void setMaxIdle(int maxIdle);
/**
* The maximum number of milliseconds that the pool will wait (when there are no available connections and the
* {@link #getMaxActive} has been reached) for a connection to be returned
* before throwing an exception. Default value is 30000 (30 seconds)
* @return the number of milliseconds to wait for a connection to become available if the pool is maxed out.
*/
public int getMaxWait();
/**
* The maximum number of milliseconds that the pool will wait (when there are no available connections and the
* {@link #getMaxActive} has been reached) for a connection to be returned
* before throwing an exception. Default value is 30000 (30 seconds)
* @param maxWait the maximum number of milliseconds to wait.
*/
public void setMaxWait(int maxWait);
/**
* The minimum amount of time an object must sit idle in the pool before it is eligible for eviction.
* The default value is 60000 (60 seconds).
* @return the minimum amount of idle time in milliseconds before a connection is considered idle and eligible for eviction.
*/
public int getMinEvictableIdleTimeMillis();
/**
* The minimum amount of time an object must sit idle in the pool before it is eligible for eviction.
* The default value is 60000 (60 seconds).
* @param minEvictableIdleTimeMillis the number of milliseconds a connection must be idle to be eligible for eviction.
*/
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis);
/**
* The minimum number of established connections that should be kept in the pool at all times.
* The connection pool can shrink below this number if validation queries fail and connections get closed.
* Default value is derived from {@link #getInitialSize()} (also see {@link #setTestWhileIdle(boolean)}
* The idle pool will not shrink below this value during an eviction run, hence the number of actual connections
* can be between {@link #getMinIdle()} and somewhere between {@link #getMaxIdle()} and {@link #getMaxActive()}
* @return the minimum number of idle or established connections
*/
public int getMinIdle();
/**
* The minimum number of established connections that should be kept in the pool at all times.
* The connection pool can shrink below this number if validation queries fail and connections get closed.
* Default value is derived from {@link #getInitialSize()} (also see {@link #setTestWhileIdle(boolean)}
* The idle pool will not shrink below this value during an eviction run, hence the number of actual connections
* can be between {@link #getMinIdle()} and somewhere between {@link #getMaxIdle()} and {@link #getMaxActive()}
*
* @param minIdle the minimum number of idle or established connections
*/
public void setMinIdle(int minIdle);
/**
* Returns the name of the connection pool. By default a JVM unique random name is assigned.
* @return the name of the pool, should be unique in a JVM
*/
public String getName();
/**
* Sets the name of the connection pool
* @param name the name of the pool, should be unique in a runtime JVM
*/
public void setName(String name);
/**
* Property not used
* @return unknown value
*/
public int getNumTestsPerEvictionRun();
/**
* Property not used
* @param numTestsPerEvictionRun parameter ignored.
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun);
/**
* Returns the password used when establishing connections to the database.
* @return the password in string format
*/
public String getPassword();
/**
* Sets the password to establish the connection with.
* The password will be included as a database property with the name 'password'.
* @param password
* @see #getDbProperties()
*/
public void setPassword(String password);
/**
* @see #getName()
* @return name
*/
public String getPoolName();
/**
* Returns the username used to establish the connection with
* @return the username used to establish the connection with
*/
public String getUsername();
/**
* Sets the username used to establish the connection with
* It will also be a property called 'user' in the database properties.
* @param username
* @see #getDbProperties()
*/
public void setUsername(String username);
/**
* boolean flag to remove abandoned connections if they exceed the removeAbandonedTimout.
* If set to true a connection is considered abandoned and eligible for removal if it has
* been in use longer than the {@link #getRemoveAbandonedTimeout()} and the condition for
* {@link #getAbandonWhenPercentageFull()} is met.
* Setting this to true can recover db connections from applications that fail to close a connection.
* See also {@link #isLogAbandoned()} The default value is false.
* @return true if abandoned connections can be closed and expelled out of the pool
*/
public boolean isRemoveAbandoned();
/**
* boolean flag to remove abandoned connections if they exceed the removeAbandonedTimout.
* If set to true a connection is considered abandoned and eligible for removal if it has
* been in use longer than the {@link #getRemoveAbandonedTimeout()} and the condition for
* {@link #getAbandonWhenPercentageFull()} is met.
* Setting this to true can recover db connections from applications that fail to close a connection.
* See also {@link #isLogAbandoned()} The default value is false.
* @param removeAbandoned set to true if abandoned connections can be closed and expelled out of the pool
*/
public void setRemoveAbandoned(boolean removeAbandoned);
/**
* The time in seconds before a connection can be considered abandoned.
* The timer can be reset upon queries using an interceptor.
* @param removeAbandonedTimeout the time in seconds before a used connection can be considered abandoned
* @see org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer
*/
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout);
/**
* The time in seconds before a connection can be considered abandoned.
* The timer can be reset upon queries using an interceptor.
* @see org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer
* @return the time in seconds before a used connection can be considered abandoned
*/
public int getRemoveAbandonedTimeout();
/**
* The indication of whether objects will be validated before being borrowed from the pool.
* If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @return true if the connection is to be validated upon borrowing a connection from the pool
* @see #getValidationInterval()
*/
public boolean isTestOnBorrow();
/**
* The indication of whether objects will be validated before being borrowed from the pool.
* If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @param testOnBorrow set to true if validation should take place before a connection is handed out to the application
* @see #getValidationInterval()
*/
public void setTestOnBorrow(boolean testOnBorrow);
/**
* The indication of whether objects will be validated after being returned to the pool.
* If the object fails to validate, it will be dropped from the pool.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @return true if validation should take place after a connection is returned to the pool
* @see #getValidationInterval()
*/
public boolean isTestOnReturn();
/**
* The indication of whether objects will be validated after being returned to the pool.
* If the object fails to validate, it will be dropped from the pool.
* NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
* Default value is false
* In order to have a more efficient validation, see {@link #setValidationInterval(long)}
* @param testOnReturn true if validation should take place after a connection is returned to the pool
* @see #getValidationInterval()
*/
public void setTestOnReturn(boolean testOnReturn);
/**
* Set to true if query validation should take place while the connection is idle.
* @return true if validation should take place during idle checks
* @see #setTimeBetweenEvictionRunsMillis(int)
*/
public boolean isTestWhileIdle();
/**
* Set to true if query validation should take place while the connection is idle.
* @param testWhileIdle true if validation should take place during idle checks
* @see #setTimeBetweenEvictionRunsMillis(int)
*/
public void setTestWhileIdle(boolean testWhileIdle);
/**
* The number of milliseconds to sleep between runs of the idle connection validation, abandoned cleaner
* and idle pool resizing. This value should not be set under 1 second.
* It dictates how often we check for idle, abandoned connections, and how often we validate idle connection and resize the idle pool.
* The default value is 5000 (5 seconds)
* @return the sleep time in between validations in milliseconds
*/
public int getTimeBetweenEvictionRunsMillis();
/**
* The number of milliseconds to sleep between runs of the idle connection validation, abandoned cleaner
* and idle pool resizing. This value should not be set under 1 second.
* It dictates how often we check for idle, abandoned connections, and how often we validate idle connection and resize the idle pool.
* The default value is 5000 (5 seconds)
* @param timeBetweenEvictionRunsMillis the sleep time in between validations in milliseconds
*/
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis);
/**
* The URL used to connect to the database
* @return the configured URL for this connection pool
* @see java.sql.Driver#connect(String, Properties)
*/
public String getUrl();
/**
* Sets the URL used to connect to the database
* @param url the configured URL for this connection pool
* @see java.sql.Driver#connect(String, Properties)
*/
public void setUrl(String url);
/**
* The SQL query that will be used to validate connections from this
* pool before returning them to the caller or pool.
* If specified, this query does not have to return any data,
* it just can't throw a SQLException.
* The default value is null.
* Example values are SELECT 1(mysql),
* select 1 from dual(oracle),
* SELECT 1(MS Sql Server)
* @return the query used for validation or null if no validation is performed
*/
public String getValidationQuery();
/**
* The SQL query that will be used to validate connections from this
* pool before returning them to the caller or pool.
* If specified, this query does not have to return any data,
* it just can't throw a SQLException.
* The default value is null.
* Example values are SELECT 1(mysql),
* select 1 from dual(oracle),
* SELECT 1(MS Sql Server)
* @param validationQuery the query used for validation or null if no validation is performed
*/
public void setValidationQuery(String validationQuery);
/**
* Return the name of the optional validator class - may be null.
*
* @return the name of the optional validator class - may be null
*/
public String getValidatorClassName();
/**
* Set the name for an optional validator class which will be used in place of test queries. If set to
* null, standard validation will be used.
*
* @param className the name of the optional validator class
*/
public void setValidatorClassName(String className);
/**
* @return the optional validator object - may be null
*/
public Validator getValidator();
/**
* Sets the validator object
* If this is a non null object, it will be used as a validator instead of the validationQuery
* If this is null, remove the usage of the validator.
*/
public void setValidator(Validator validator);
/**
* avoid excess validation, only run validation at most at this frequency - time in milliseconds.
* If a connection is due for validation, but has been validated previously
* within this interval, it will not be validated again.
* The default value is 30000 (30 seconds).
* @return the validation interval in milliseconds
*/
public long getValidationInterval();
/**
* avoid excess validation, only run validation at most at this frequency - time in milliseconds.
* If a connection is due for validation, but has been validated previously
* within this interval, it will not be validated again.
* The default value is 30000 (30 seconds).
* @param validationInterval the validation interval in milliseconds
*/
public void setValidationInterval(long validationInterval);
/**
* A custom query to be run when a connection is first created. The default value is null.
* This query only runs once per connection, and that is when a new connection is established to the database.
* If this value is non null, it will replace the validation query during connection creation.
* @return the init SQL used to run against the DB or null if not set
*/
public String getInitSQL();
/**
* A custom query to be run when a connection is first created. The default value is null.
* This query only runs once per connection, and that is when a new connection is established to the database.
* If this value is non null, it will replace the validation query during connection creation.
* @param initSQL the init SQL used to run against the DB or null if no query should be executed
*/
public void setInitSQL(String initSQL);
/**
* Returns true if we should run the validation query when connecting to the database for the first time on a connection.
* Normally this is always set to false, unless one wants to use the validationQuery as an init query.
* @return true if we should run the validation query upon connect
*/
public boolean isTestOnConnect();
/**
* Set to true if we should run the validation query when connecting to the database for the first time on a connection.
* Normally this is always set to false, unless one wants to use the validationQuery as an init query.
* Setting an {@link #setInitSQL(String)} will override this setting, as the init SQL will be used instead of the validation query
* @param testOnConnect set to true if we should run the validation query upon connect
*/
public void setTestOnConnect(boolean testOnConnect);
/**
* A semicolon separated list of classnames extending {@link org.apache.tomcat.jdbc.pool.JdbcInterceptor} class.
* These interceptors will be inserted as an interceptor into the chain of operations on a java.sql.Connection object.
* Example interceptors are {@link org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer StatementFinalizer} to close all
* used statements during the session.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer ResetAbandonedTimer} resets the timer upon every operation
* on the connection or a statement.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ConnectionState ConnectionState} caches the auto commit, read only and catalog settings to avoid round trips to the DB.
* The default value is null.
* @return the interceptors that are used for connections.
* Example format: 'ConnectionState(useEquals=true,fast=yes);ResetAbandonedTimer'
*/
public String getJdbcInterceptors();
/**
* A semicolon separated list of classnames extending {@link org.apache.tomcat.jdbc.pool.JdbcInterceptor} class.
* These interceptors will be inserted as an interceptor into the chain of operations on a java.sql.Connection object.
* Example interceptors are {@link org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer StatementFinalizer} to close all
* used statements during the session.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer ResetAbandonedTimer} resets the timer upon every operation
* on the connection or a statement.
* {@link org.apache.tomcat.jdbc.pool.interceptor.ConnectionState ConnectionState} caches the auto commit, read only and catalog settings to avoid round trips to the DB.
* The default value is null.
* @param jdbcInterceptors the interceptors that are used for connections.
* Example format: 'ConnectionState(useEquals=true,fast=yes);ResetAbandonedTimer'
*/
public void setJdbcInterceptors(String jdbcInterceptors);
/**
* Returns the {@link #getJdbcInterceptors()} as an array of objects with properties and the classes.
* @return an array of interceptors that have been configured
*/
public InterceptorDefinition[] getJdbcInterceptorsAsArray();
/**
* If set to true, the connection pool creates a {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} object
* that can be registered with JMX to receive notifications and state about the pool.
* The ConnectionPool object doesn't register itself, as there is no way to keep a static non changing ObjectName across JVM restarts.
* @return true if the mbean object will be created upon startup.
*/
public boolean isJmxEnabled();
/**
* If set to true, the connection pool creates a {@link org.apache.tomcat.jdbc.pool.jmx.ConnectionPoolMBean} object
* that can be registered with JMX to receive notifications and state about the pool.
* The ConnectionPool object doesn't register itself, as there is no way to keep a static non changing ObjectName across JVM restarts.
* @param jmxEnabled set to to if the mbean object should be created upon startup.
*/
public void setJmxEnabled(boolean jmxEnabled);
/**
* Returns true if the pool sweeper is enabled for the connection pool.
* The pool sweeper is enabled if any settings that require async intervention in the pool are turned on
* <source>
boolean result = getTimeBetweenEvictionRunsMillis()>0;
result = result && (isRemoveAbandoned() && getRemoveAbandonedTimeout()>0);
result = result || (isTestWhileIdle() && getValidationQuery()!=null);
return result;
</source>
*
* @return true if a background thread is or will be enabled for this pool
*/
public boolean isPoolSweeperEnabled();
/**
* Set to true if you wish the <code>ProxyConnection</code> class to use <code>String.equals</code> instead of
* <code>==</code> when comparing method names.
* This property does not apply to added interceptors as those are configured individually.
* The default value is <code>false</code>.
* @return true if pool uses {@link String#equals(Object)} instead of == when comparing method names on {@link java.sql.Connection} methods
*/
public boolean isUseEquals();
/**
* Set to true if you wish the <code>ProxyConnection</code> class to use <code>String.equals</code> instead of
* <code>==</code> when comparing method names.
* This property does not apply to added interceptors as those are configured individually.
* The default value is <code>false</code>.
* @param useEquals set to true if the pool should use {@link String#equals(Object)} instead of ==
* when comparing method names on {@link java.sql.Connection} methods
*/
public void setUseEquals(boolean useEquals);
/**
* Time in milliseconds to keep this connection alive even when used.
* When a connection is returned to the pool, the pool will check to see if the
* ((now - time-when-connected) > maxAge) has been reached, and if so,
* it closes the connection rather than returning it to the pool.
* The default value is 0, which implies that connections will be left open and no
* age check will be done upon returning the connection to the pool.
* This is a useful setting for database sessions that leak memory as it ensures that the session
* will have a finite life span.
* @return the time in milliseconds a connection will be open for when used
*/
public long getMaxAge();
/**
* Time in milliseconds to keep this connection alive even when used.
* When a connection is returned to the pool, the pool will check to see if the
* ((now - time-when-connected) > maxAge) has been reached, and if so,
* it closes the connection rather than returning it to the pool.
* The default value is 0, which implies that connections will be left open and no
* age check will be done upon returning the connection to the pool.
* This is a useful setting for database sessions that leak memory as it ensures that the session
* will have a finite life span.
* @param maxAge the time in milliseconds a connection will be open for when used
*/
public void setMaxAge(long maxAge);
/**
* Return true if a lock should be used when operations are performed on the connection object.
* Should be set to false unless you plan to have a background thread of your own doing idle and abandon checking
* such as JMX clients. If the pool sweeper is enabled, then the lock will automatically be used regardless of this setting.
* @return true if a lock is used.
*/
public boolean getUseLock();
/**
* Set to true if a lock should be used when operations are performed on the connection object.
* Should be set to false unless you plan to have a background thread of your own doing idle and abandon checking
* such as JMX clients. If the pool sweeper is enabled, then the lock will automatically be used regardless of this setting.
* @param useLock set to true if a lock should be used on connection operations
*/
public void setUseLock(boolean useLock);
/**
* Similar to {@link #setRemoveAbandonedTimeout(int)} but instead of treating the connection
* as abandoned, and potentially closing the connection, this simply logs the warning if
* {@link #isLogAbandoned()} returns true. If this value is equal or less than 0, no suspect
* checking will be performed. Suspect checking only takes place if the timeout value is larger than 0 and
* the connection was not abandoned or if abandon check is disabled. If a connection is suspect a WARN message gets
* logged and a JMX notification gets sent once.
* @param seconds - the amount of time in seconds that has to pass before a connection is marked suspect.
*/
public void setSuspectTimeout(int seconds);
/**
* Returns the time in seconds to pass before a connection is marked an abanoned suspect.
* Any value lesser than or equal to 0 means the check is disabled.
* @return Returns the time in seconds to pass before a connection is marked an abanoned suspect.
*/
public int getSuspectTimeout();
/**
* Injects a datasource that will be used to retrieve/create connections.
* If a data source is set, the {@link PoolConfiguration#getUrl()} and {@link PoolConfiguration#getDriverClassName()} methods are ignored
* and not used by the pool. If the {@link PoolConfiguration#getUsername()} and {@link PoolConfiguration#getPassword()}
* values are set, the method {@link javax.sql.DataSource#getConnection(String, String)} method will be called instead of the
* {@link javax.sql.DataSource#getConnection()} method.
* If the data source implements {@link javax.sql.XADataSource} the methods
* {@link javax.sql.XADataSource#getXAConnection()} and {@link javax.sql.XADataSource#getXAConnection(String,String)}
* will be invoked.
* @param ds the {@link javax.sql.DataSource} to be used for creating connections to be pooled.
*/
public void setDataSource(Object ds);
/**
* Returns a datasource, if one exists that is being used to create connections.
* This method will return null if the pool is using a {@link java.sql.Driver}
* @return the {@link javax.sql.DataSource} to be used for creating connections to be pooled or null if a Driver is used.
*/
public Object getDataSource();
/**
* Configure the connection pool to use a DataSource according to {@link PoolConfiguration#setDataSource(Object)}
* But instead of injecting the object, specify the JNDI location.
* After a successful JNDI look, the {@link PoolConfiguration#getDataSource()} will not return null.
* @param jndiDS -the JNDI string @TODO specify the rules here.
*/
public void setDataSourceJNDI(String jndiDS);
/**
* Returns the JNDI string configured for data source usage.
* @return the JNDI string or null if not set
*/
public String getDataSourceJNDI();
/**
* Returns true if the call {@link DataSource#getConnection(String, String) getConnection(username,password)} is
* allowed. This is used for when the pool is used by an application accessing multiple schemas.
* There is a performance impact turning this option on.
* @return true if {@link DataSource#getConnection(String, String) getConnection(username,password)} is honored, false if it is ignored.
*/
public boolean isAlternateUsernameAllowed();
/**
* Set to true if the call {@link DataSource#getConnection(String, String) getConnection(username,password)} is
* allowed and honored.. This is used for when the pool is used by an application accessing multiple schemas.
* There is a performance impact turning this option on, even when not used due to username checks.
* @param alternateUsernameAllowed - set true if {@link DataSource#getConnection(String, String) getConnection(username,password)} is honored,
* false if it is to be ignored.
*/
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed);
/**
* Set to true if you want the connection pool to commit any pending transaction when a connection is returned.
* The default value is false, as this could result in committing data.
* This parameter is only looked at if the {@link #getDefaultAutoCommit()} returns false
* @param commitOnReturn set to true if the pool should call {@link java.sql.Connection#commit()} when a connection is returned to the pool.
* Default is false
*/
public void setCommitOnReturn(boolean commitOnReturn);
/**
* @see PoolConfiguration#setCommitOnReturn(boolean)
*/
public boolean getCommitOnReturn();
/**
* Set to true if you want the connection pool to rollback any pending transaction when a connection is returned.
* The default value is false, as this could result in committing data.
* This parameter is only looked at if the {@link #getDefaultAutoCommit()} returns false
* @param rollbackOnReturn set to true if the pool should call {@link java.sql.Connection#rollback()} when a connection is returned to the pool.
* Default is false
*/
public void setRollbackOnReturn(boolean rollbackOnReturn);
/**
* @see PoolConfiguration#setRollbackOnReturn(boolean)
*/
public boolean getRollbackOnReturn();
/**
* If set to true, the connection will be wrapped with facade that will disallow the connection to be used after
* {@link java.sql.Connection#close()} is called. If set to true, after {@link java.sql.Connection#close()} all calls except
* {@link java.sql.Connection#close()} and {@link java.sql.Connection#isClosed()} will throw an exception.
* @param useDisposableConnectionFacade
*/
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade);
/**
* Returns true if this connection pool is configured to use a connection facade to prevent re-use of connection after
* {@link java.sql.Connection#close()} has been invoked
* @return true if {@link java.sql.Connection#close()} has been invoked.
*/
public boolean getUseDisposableConnectionFacade();
/**
* Set to true if you wish that errors from validation should be logged as error messages.
* @param logValidationErrors set to true to log validation errors
*/
public void setLogValidationErrors(boolean logValidationErrors);
/**
* Returns true if errors that happen during validation will be logged
* @return true if errors that happen during validation will be logged
*/
public boolean getLogValidationErrors();
/**
* Returns true if the pool is configured to propagate interrupt state of a thread.
* A thread waiting for a connection, can have its wait interrupted, and by default
* will clear the interrupt flag and throw a {@link PoolExhaustedException}
* @return true if the pool is configured to propagate and not clear the thread interrupt state
*/
public boolean getPropagateInterruptState();
/**
* Configure the pool to propagate interrupt state for interrupted threads waiting for a connection
* A thread waiting for a connection, can have its wait interrupted, and by default
* will clear the interrupt flag and throw a {@link PoolExhaustedException}
* If set to true, this behavior will change, while the {@link PoolExhaustedException} is still thrown, the threads interrupted state is still set.
* @param propagateInterruptState - set to true to not clear, but propagate, a threads interrupted state.
*/
public void setPropagateInterruptState(boolean propagateInterruptState);
/**
* Set to true if you want to ignore error of connection creation while initializing the pool.
* Set to false if you want to fail the initialization of the pool by throwing exception.
* @param ignoreExceptionOnPreLoad set to true if you want to ignore error of connection creation while initializing the pool.
*/
public void setIgnoreExceptionOnPreLoad(boolean ignoreExceptionOnPreLoad);
/**
* @see PoolConfiguration#setIgnoreExceptionOnPreLoad(boolean)
*/
public boolean isIgnoreExceptionOnPreLoad();
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java
|
/*
* 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.jdbc.pool;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* @author Filip Hanik
*
*/
public class PoolProperties implements PoolConfiguration, Cloneable, Serializable {
private static final long serialVersionUID = -8519283440854213745L;
private static final Log log = LogFactory.getLog(PoolProperties.class);
public static final int DEFAULT_MAX_ACTIVE = 100;
protected static AtomicInteger poolCounter = new AtomicInteger(0);
private volatile Properties dbProperties = new Properties();
private volatile String url = null;
private volatile String driverClassName = null;
private volatile Boolean defaultAutoCommit = null;
private volatile Boolean defaultReadOnly = null;
private volatile int defaultTransactionIsolation = DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION;
private volatile String defaultCatalog = null;
private volatile String connectionProperties;
private volatile int initialSize = 10;
private volatile int maxActive = DEFAULT_MAX_ACTIVE;
private volatile int maxIdle = maxActive;
private volatile int minIdle = initialSize;
private volatile int maxWait = 30000;
private volatile String validationQuery;
private volatile String validatorClassName;
private volatile Validator validator;
private volatile boolean testOnBorrow = false;
private volatile boolean testOnReturn = false;
private volatile boolean testWhileIdle = false;
private volatile int timeBetweenEvictionRunsMillis = 5000;
private volatile int numTestsPerEvictionRun;
private volatile int minEvictableIdleTimeMillis = 60000;
private volatile boolean accessToUnderlyingConnectionAllowed = true;
private volatile boolean removeAbandoned = false;
private volatile int removeAbandonedTimeout = 60;
private volatile boolean logAbandoned = false;
private volatile String name = "Tomcat Connection Pool["+(poolCounter.addAndGet(1))+"-"+System.identityHashCode(PoolProperties.class)+"]";
private volatile String password;
private volatile String username;
private volatile long validationInterval = 30000;
private volatile boolean jmxEnabled = true;
private volatile String initSQL;
private volatile boolean testOnConnect =false;
private volatile String jdbcInterceptors=null;
private volatile boolean fairQueue = true;
private volatile boolean useEquals = true;
private volatile int abandonWhenPercentageFull = 0;
private volatile long maxAge = 0;
private volatile boolean useLock = false;
private volatile InterceptorDefinition[] interceptors = null;
private volatile int suspectTimeout = 0;
private volatile Object dataSource = null;
private volatile String dataSourceJNDI = null;
private volatile boolean alternateUsernameAllowed = false;
private volatile boolean commitOnReturn = false;
private volatile boolean rollbackOnReturn = false;
private volatile boolean useDisposableConnectionFacade = true;
private volatile boolean logValidationErrors = false;
private volatile boolean propagateInterruptState = false;
private volatile boolean ignoreExceptionOnPreLoad = false;
/**
* {@inheritDoc}
*/
@Override
public void setAbandonWhenPercentageFull(int percentage) {
if (percentage<0) abandonWhenPercentageFull = 0;
else if (percentage>100) abandonWhenPercentageFull = 100;
else abandonWhenPercentageFull = percentage;
}
/**
* {@inheritDoc}
*/
@Override
public int getAbandonWhenPercentageFull() {
return abandonWhenPercentageFull;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFairQueue() {
return fairQueue;
}
/**
* {@inheritDoc}
*/
@Override
public void setFairQueue(boolean fairQueue) {
this.fairQueue = fairQueue;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAccessToUnderlyingConnectionAllowed() {
return accessToUnderlyingConnectionAllowed;
}
/**
* {@inheritDoc}
*/
@Override
public String getConnectionProperties() {
return connectionProperties;
}
/**
* {@inheritDoc}
*/
@Override
public Properties getDbProperties() {
return dbProperties;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultCatalog() {
return defaultCatalog;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isDefaultReadOnly() {
return defaultReadOnly;
}
/**
* {@inheritDoc}
*/
@Override
public int getDefaultTransactionIsolation() {
return defaultTransactionIsolation;
}
/**
* {@inheritDoc}
*/
@Override
public String getDriverClassName() {
return driverClassName;
}
/**
* {@inheritDoc}
*/
@Override
public int getInitialSize() {
return initialSize;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLogAbandoned() {
return logAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxActive() {
return maxActive;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxIdle() {
return maxIdle;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxWait() {
return maxWait;
}
/**
* {@inheritDoc}
*/
@Override
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
/**
* {@inheritDoc}
*/
@Override
public int getMinIdle() {
return minIdle;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return name;
}
/**
* {@inheritDoc}
*/
@Override
public int getNumTestsPerEvictionRun() {
return numTestsPerEvictionRun;
}
/**
* {@inheritDoc}
*/
@Override
public String getPassword() {
return password;
}
/**
* {@inheritDoc}
*/
@Override
public String getPoolName() {
return getName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRemoveAbandoned() {
return removeAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public int getRemoveAbandonedTimeout() {
return removeAbandonedTimeout;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnBorrow() {
return testOnBorrow;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnReturn() {
return testOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestWhileIdle() {
return testWhileIdle;
}
/**
* {@inheritDoc}
*/
@Override
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
/**
* {@inheritDoc}
*/
@Override
public String getUrl() {
return url;
}
/**
* {@inheritDoc}
*/
@Override
public String getUsername() {
return username;
}
/**
* {@inheritDoc}
*/
@Override
public String getValidationQuery() {
return validationQuery;
}
/**
* {@inheritDoc}
*/
@Override
public String getValidatorClassName() {
return validatorClassName;
}
/**
* {@inheritDoc}
*/
@Override
public Validator getValidator() {
return validator;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidator(Validator validator) {
this.validator = validator;
if (validator!=null) {
this.validatorClassName = validator.getClass().getName();
} else {
this.validatorClassName = null;
}
}
/**
* {@inheritDoc}
*/
@Override
public long getValidationInterval() {
return validationInterval;
}
/**
* {@inheritDoc}
*/
@Override
public String getInitSQL() {
return initSQL;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTestOnConnect() {
return testOnConnect;
}
/**
* {@inheritDoc}
*/
@Override
public String getJdbcInterceptors() {
return jdbcInterceptors;
}
/**
* {@inheritDoc}
*/
@Override
public InterceptorDefinition[] getJdbcInterceptorsAsArray() {
if (interceptors == null) {
if (jdbcInterceptors==null) {
interceptors = new InterceptorDefinition[0];
} else {
String[] interceptorValues = jdbcInterceptors.split(";");
InterceptorDefinition[] definitions = new InterceptorDefinition[interceptorValues.length+1];
//always add the trap interceptor to the mix
definitions[0] = new InterceptorDefinition(TrapException.class);
for (int i=0; i<interceptorValues.length; i++) {
int propIndex = interceptorValues[i].indexOf("(");
int endIndex = interceptorValues[i].indexOf(")");
if (propIndex<0 || endIndex<0 || endIndex <= propIndex) {
definitions[i+1] = new InterceptorDefinition(interceptorValues[i].trim());
} else {
String name = interceptorValues[i].substring(0,propIndex).trim();
definitions[i+1] = new InterceptorDefinition(name);
String propsAsString = interceptorValues[i].substring(propIndex+1, interceptorValues[i].length()-1);
String[] props = propsAsString.split(",");
for (int j=0; j<props.length; j++) {
int pidx = props[j].indexOf("=");
String propName = props[j].substring(0,pidx).trim();
String propValue = props[j].substring(pidx+1).trim();
definitions[i+1].addProperty(new InterceptorProperty(propName,propValue));
}
}
}
interceptors = definitions;
}
}
return interceptors;
}
/**
* {@inheritDoc}
*/
@Override
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) {
// NOOP
}
/**
* {@inheritDoc}
*/
@Override
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
getProperties(connectionProperties, getDbProperties());
}
/**
* {@inheritDoc}
*/
@Override
public void setDbProperties(Properties dbProperties) {
this.dbProperties = dbProperties;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultAutoCommit(Boolean defaultAutoCommit) {
this.defaultAutoCommit = defaultAutoCommit;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultCatalog(String defaultCatalog) {
this.defaultCatalog = defaultCatalog;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultReadOnly(Boolean defaultReadOnly) {
this.defaultReadOnly = defaultReadOnly;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
this.defaultTransactionIsolation = defaultTransactionIsolation;
}
/**
* {@inheritDoc}
*/
@Override
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
/**
* {@inheritDoc}
*/
@Override
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
/**
* {@inheritDoc}
*/
@Override
public void setLogAbandoned(boolean logAbandoned) {
this.logAbandoned = logAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
/**
* {@inheritDoc}
*/
@Override
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* {@inheritDoc}
*/
@Override
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* {@inheritDoc}
*/
@Override
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* {@inheritDoc}
*/
@Override
public void setPassword(String password) {
this.password = password;
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandoned(boolean removeAbandoned) {
this.removeAbandoned = removeAbandoned;
}
/**
* {@inheritDoc}
*/
@Override
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
this.removeAbandonedTimeout = removeAbandonedTimeout;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public void setTimeBetweenEvictionRunsMillis(int
timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* {@inheritDoc}
*/
@Override
public void setUrl(String url) {
this.url = url;
}
/**
* {@inheritDoc}
*/
@Override
public void setUsername(String username) {
this.username = username;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationInterval(long validationInterval) {
this.validationInterval = validationInterval;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
/**
* {@inheritDoc}
*/
@Override
public void setValidatorClassName(String className) {
this.validatorClassName = className;
validator = null;
if (className == null) {
return;
}
try {
@SuppressWarnings("unchecked")
Class<Validator> validatorClass = (Class<Validator>)Class.forName(className);
validator = validatorClass.newInstance();
} catch (ClassNotFoundException e) {
log.warn("The class "+className+" cannot be found.", e);
} catch (ClassCastException e) {
log.warn("The class "+className+" does not implement the Validator interface.", e);
} catch (InstantiationException e) {
log.warn("An object of class "+className+" cannot be instantiated. Make sure that "+
"it includes an implicit or explicit no-arg constructor.", e);
} catch (IllegalAccessException e) {
log.warn("The class "+className+" or its no-arg constructor are inaccessible.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setInitSQL(String initSQL) {
this.initSQL = initSQL;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestOnConnect(boolean testOnConnect) {
this.testOnConnect = testOnConnect;
}
/**
* {@inheritDoc}
*/
@Override
public void setJdbcInterceptors(String jdbcInterceptors) {
this.jdbcInterceptors = jdbcInterceptors;
this.interceptors = null;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("ConnectionPool[");
try {
String[] fields = DataSourceFactory.ALL_PROPERTIES;
for (String field: fields) {
final String[] prefix = new String[] {"get","is"};
for (int j=0; j<prefix.length; j++) {
String name = prefix[j]
+ field.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ field.substring(1);
Method m = null;
try {
m = getClass().getMethod(name);
}catch (NoSuchMethodException nm) {
continue;
}
buf.append(field);
buf.append("=");
if (DataSourceFactory.PROP_PASSWORD.equals(field)) {
buf.append("********");
} else {
buf.append(m.invoke(this, new Object[0]));
}
buf.append("; ");
break;
}
}
}catch (Exception x) {
//shouldn't happen
log.debug("toString() call failed", x);
}
return buf.toString();
}
public static int getPoolCounter() {
return poolCounter.get();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isJmxEnabled() {
return jmxEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public void setJmxEnabled(boolean jmxEnabled) {
this.jmxEnabled = jmxEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getDefaultReadOnly() {
return defaultReadOnly;
}
/**
* {@inheritDoc}
*/
@Override
public int getSuspectTimeout() {
return this.suspectTimeout;
}
/**
* {@inheritDoc}
*/
@Override
public void setSuspectTimeout(int seconds) {
this.suspectTimeout = seconds;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPoolSweeperEnabled() {
boolean timer = getTimeBetweenEvictionRunsMillis()>0;
boolean result = timer && (isRemoveAbandoned() && getRemoveAbandonedTimeout()>0);
result = result || (timer && getSuspectTimeout()>0);
result = result || (timer && isTestWhileIdle() && getValidationQuery()!=null);
result = result || (timer && getMinEvictableIdleTimeMillis()>0);
return result;
}
public static class InterceptorDefinition implements Serializable {
private static final long serialVersionUID = 1L;
protected String className;
protected Map<String,InterceptorProperty> properties = new HashMap<>();
protected volatile Class<?> clazz = null;
public InterceptorDefinition(String className) {
this.className = className;
}
public InterceptorDefinition(Class<?> cl) {
this(cl.getName());
clazz = cl;
}
public String getClassName() {
return className;
}
public void addProperty(String name, String value) {
InterceptorProperty p = new InterceptorProperty(name,value);
addProperty(p);
}
public void addProperty(InterceptorProperty p) {
properties.put(p.getName(), p);
}
public Map<String,InterceptorProperty> getProperties() {
return properties;
}
@SuppressWarnings("unchecked")
public Class<? extends JdbcInterceptor> getInterceptorClass() throws ClassNotFoundException {
if (clazz==null) {
if (getClassName().indexOf(".")<0) {
if (log.isDebugEnabled()) {
log.debug("Loading interceptor class:"+PoolConfiguration.PKG_PREFIX+getClassName());
}
clazz = Class.forName(PoolConfiguration.PKG_PREFIX+getClassName(), true, this.getClass().getClassLoader());
} else {
if (log.isDebugEnabled()) {
log.debug("Loading interceptor class:"+getClassName());
}
clazz = Class.forName(getClassName(), true, this.getClass().getClassLoader());
}
}
return (Class<? extends JdbcInterceptor>)clazz;
}
}
public static class InterceptorProperty implements Serializable {
private static final long serialVersionUID = 1L;
String name;
String value;
public InterceptorProperty(String name, String value) {
assert(name!=null);
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public boolean getValueAsBoolean(boolean def) {
if (value==null) return def;
if ("true".equals(value)) return true;
if ("false".equals(value)) return false;
return def;
}
public int getValueAsInt(int def) {
if (value==null) return def;
try {
int v = Integer.parseInt(value);
return v;
}catch (NumberFormatException nfe) {
return def;
}
}
public long getValueAsLong(long def) {
if (value==null) return def;
try {
return Long.parseLong(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public byte getValueAsByte(byte def) {
if (value==null) return def;
try {
return Byte.parseByte(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public short getValueAsShort(short def) {
if (value==null) return def;
try {
return Short.parseShort(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public float getValueAsFloat(float def) {
if (value==null) return def;
try {
return Float.parseFloat(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public double getValueAsDouble(double def) {
if (value==null) return def;
try {
return Double.parseDouble(value);
}catch (NumberFormatException nfe) {
return def;
}
}
public char getValueAschar(char def) {
if (value==null) return def;
try {
return value.charAt(0);
}catch (StringIndexOutOfBoundsException nfe) {
return def;
}
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object o) {
if (o==this) return true;
if (o instanceof InterceptorProperty) {
InterceptorProperty other = (InterceptorProperty)o;
return other.name.equals(this.name);
}
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUseEquals() {
return useEquals;
}
/**
* {@inheritDoc}
*/
@Override
public void setUseEquals(boolean useEquals) {
this.useEquals = useEquals;
}
/**
* {@inheritDoc}
*/
@Override
public long getMaxAge() {
return maxAge;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxAge(long maxAge) {
this.maxAge = maxAge;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseLock() {
return useLock;
}
/**
* {@inheritDoc}
*/
@Override
public void setUseLock(boolean useLock) {
this.useLock = useLock;
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSource(Object ds) {
this.dataSource = ds;
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataSource() {
return dataSource;
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSourceJNDI(String jndiDS) {
this.dataSourceJNDI = jndiDS;
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSourceJNDI() {
return this.dataSourceJNDI;
}
public static Properties getProperties(String propText, Properties props) {
if (props==null) props = new Properties();
if (propText != null) {
try {
props.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes()));
}catch (IOException x) {
throw new RuntimeException(x);
}
}
return props;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlternateUsernameAllowed() {
return alternateUsernameAllowed;
}
/**
* {@inheritDoc}
*/
@Override
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) {
this.alternateUsernameAllowed = alternateUsernameAllowed;
}
/**
* {@inheritDoc}
*/
@Override
public void setCommitOnReturn(boolean commitOnReturn) {
this.commitOnReturn = commitOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCommitOnReturn() {
return this.commitOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public void setRollbackOnReturn(boolean rollbackOnReturn) {
this.rollbackOnReturn = rollbackOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getRollbackOnReturn() {
return this.rollbackOnReturn;
}
/**
* {@inheritDoc}
*/
@Override
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) {
this.useDisposableConnectionFacade = useDisposableConnectionFacade;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseDisposableConnectionFacade() {
return useDisposableConnectionFacade;
}
/**
* {@inheritDoc}
*/
@Override
public void setLogValidationErrors(boolean logValidationErrors) {
this.logValidationErrors = logValidationErrors;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getLogValidationErrors() {
return this.logValidationErrors;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getPropagateInterruptState() {
return propagateInterruptState;
}
/**
* {@inheritDoc}
*/
@Override
public void setPropagateInterruptState(boolean propagateInterruptState) {
this.propagateInterruptState = propagateInterruptState;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIgnoreExceptionOnPreLoad() {
return ignoreExceptionOnPreLoad;
}
/**
* {@inheritDoc}
*/
@Override
public void setIgnoreExceptionOnPreLoad(boolean ignoreExceptionOnPreLoad) {
this.ignoreExceptionOnPreLoad = ignoreExceptionOnPreLoad;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PooledConnection.java
|
/*
* 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.jdbc.pool;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
/**
* Represents a pooled connection
* and holds a reference to the {@link java.sql.Connection} object
* @author Filip Hanik
* @version 1.0
*/
public class PooledConnection {
/**
* Logger
*/
private static final Log log = LogFactory.getLog(PooledConnection.class);
public static final String PROP_USER = PoolUtilities.PROP_USER;
public static final String PROP_PASSWORD = PoolUtilities.PROP_PASSWORD;
/**
* Validate when connection is borrowed flag
*/
public static final int VALIDATE_BORROW = 1;
/**
* Validate when connection is returned flag
*/
public static final int VALIDATE_RETURN = 2;
/**
* Validate when connection is idle flag
*/
public static final int VALIDATE_IDLE = 3;
/**
* Validate when connection is initialized flag
*/
public static final int VALIDATE_INIT = 4;
/**
* The properties for the connection pool
*/
protected PoolConfiguration poolProperties;
/**
* The underlying database connection
*/
private volatile java.sql.Connection connection;
/**
* If using a XAConnection underneath.
*/
protected volatile javax.sql.XAConnection xaConnection;
/**
* When we track abandon traces, this string holds the thread dump
*/
private String abandonTrace = null;
/**
* Timestamp the connection was last 'touched' by the pool
*/
private volatile long timestamp;
/**
* Lock for this connection only
*/
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(false);
/**
* Set to true if this connection has been discarded by the pool
*/
private volatile boolean discarded = false;
/**
* The Timestamp when the last time the connect() method was called successfully
*/
private volatile long lastConnected = -1;
/**
* timestamp to keep track of validation intervals
*/
private volatile long lastValidated = System.currentTimeMillis();
/**
* The parent
*/
protected ConnectionPool parent;
private HashMap<Object, Object> attributes = new HashMap<>();
private volatile long connectionVersion=0;
/**
* Weak reference to cache the list of interceptors for this connection
* so that we don't create a new list of interceptors each time we borrow
* the connection
*/
private volatile JdbcInterceptor handler = null;
private AtomicBoolean released = new AtomicBoolean(false);
private volatile boolean suspect = false;
private java.sql.Driver driver = null;
/**
* Constructor
* @param prop - pool properties
* @param parent - the parent connection pool
*/
public PooledConnection(PoolConfiguration prop, ConnectionPool parent) {
poolProperties = prop;
this.parent = parent;
connectionVersion = parent.getPoolVersion();
}
public long getConnectionVersion() {
return connectionVersion;
}
public boolean checkUser(String username, String password) {
if (!getPoolProperties().isAlternateUsernameAllowed()) return true;
if (username==null) username = poolProperties.getUsername();
if (password==null) password = poolProperties.getPassword();
String storedUsr = (String)getAttributes().get(PROP_USER);
String storedPwd = (String)getAttributes().get(PROP_PASSWORD);
boolean result = (username==null && storedUsr==null);
result = (result || (username!=null && username.equals(storedUsr)));
result = result && ((password==null && storedPwd==null) || (password!=null && password.equals(storedPwd)));
if (username==null) getAttributes().remove(PROP_USER); else getAttributes().put(PROP_USER, username);
if (password==null) getAttributes().remove(PROP_PASSWORD); else getAttributes().put(PROP_PASSWORD, password);
return result;
}
/**
* Connects the underlying connection to the database.
* @throws SQLException if the method {@link #release()} has been called.
* @throws SQLException if driver instantiation fails
* @throws SQLException if a call to {@link java.sql.Driver#connect(String, java.util.Properties)} fails.
* @throws SQLException if default properties are configured and a call to
* {@link java.sql.Connection#setAutoCommit(boolean)}, {@link java.sql.Connection#setCatalog(String)},
* {@link java.sql.Connection#setTransactionIsolation(int)} or {@link java.sql.Connection#setReadOnly(boolean)} fails.
*/
public void connect() throws SQLException {
if (released.get()) throw new SQLException("A connection once released, can't be reestablished.");
if (connection != null) {
try {
this.disconnect(false);
} catch (Exception x) {
log.debug("Unable to disconnect previous connection.", x);
} //catch
} //end if
if (poolProperties.getDataSource()==null && poolProperties.getDataSourceJNDI()!=null) {
//TODO lookup JNDI name
}
if (poolProperties.getDataSource()!=null) {
connectUsingDataSource();
} else {
connectUsingDriver();
}
//set up the default state, unless we expect the interceptor to do it
if (poolProperties.getJdbcInterceptors()==null || poolProperties.getJdbcInterceptors().indexOf(ConnectionState.class.getName())<0 ||
poolProperties.getJdbcInterceptors().indexOf(ConnectionState.class.getSimpleName())<0) {
if (poolProperties.getDefaultTransactionIsolation()!=DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION) connection.setTransactionIsolation(poolProperties.getDefaultTransactionIsolation());
if (poolProperties.getDefaultReadOnly()!=null) connection.setReadOnly(poolProperties.getDefaultReadOnly().booleanValue());
if (poolProperties.getDefaultAutoCommit()!=null) connection.setAutoCommit(poolProperties.getDefaultAutoCommit().booleanValue());
if (poolProperties.getDefaultCatalog()!=null) connection.setCatalog(poolProperties.getDefaultCatalog());
}
this.discarded = false;
this.lastConnected = System.currentTimeMillis();
}
protected void connectUsingDataSource() throws SQLException {
String usr = null;
String pwd = null;
if (getAttributes().containsKey(PROP_USER)) {
usr = (String) getAttributes().get(PROP_USER);
} else {
usr = poolProperties.getUsername();
getAttributes().put(PROP_USER, usr);
}
if (getAttributes().containsKey(PROP_PASSWORD)) {
pwd = (String) getAttributes().get(PROP_PASSWORD);
} else {
pwd = poolProperties.getPassword();
getAttributes().put(PROP_PASSWORD, pwd);
}
if (poolProperties.getDataSource() instanceof javax.sql.XADataSource) {
javax.sql.XADataSource xds = (javax.sql.XADataSource)poolProperties.getDataSource();
if (usr!=null && pwd!=null) {
xaConnection = xds.getXAConnection(usr, pwd);
connection = xaConnection.getConnection();
} else {
xaConnection = xds.getXAConnection();
connection = xaConnection.getConnection();
}
} else if (poolProperties.getDataSource() instanceof javax.sql.DataSource){
javax.sql.DataSource ds = (javax.sql.DataSource)poolProperties.getDataSource();
if (usr!=null && pwd!=null) {
connection = ds.getConnection(usr, pwd);
} else {
connection = ds.getConnection();
}
} else if (poolProperties.getDataSource() instanceof javax.sql.ConnectionPoolDataSource){
javax.sql.ConnectionPoolDataSource ds = (javax.sql.ConnectionPoolDataSource)poolProperties.getDataSource();
if (usr!=null && pwd!=null) {
connection = ds.getPooledConnection(usr, pwd).getConnection();
} else {
connection = ds.getPooledConnection().getConnection();
}
} else {
throw new SQLException("DataSource is of unknown class:"+(poolProperties.getDataSource()!=null?poolProperties.getDataSource().getClass():"null"));
}
}
protected void connectUsingDriver() throws SQLException {
try {
if (driver==null) {
if (log.isDebugEnabled()) {
log.debug("Instantiating driver using class: "+poolProperties.getDriverClassName()+" [url="+poolProperties.getUrl()+"]");
}
driver = (java.sql.Driver) Class.forName(poolProperties.getDriverClassName(),
true, PooledConnection.class.getClassLoader()
).newInstance();
}
} catch (java.lang.Exception cn) {
if (log.isDebugEnabled()) {
log.debug("Unable to instantiate JDBC driver.", cn);
}
SQLException ex = new SQLException(cn.getMessage());
ex.initCause(cn);
throw ex;
}
String driverURL = poolProperties.getUrl();
String usr = null;
String pwd = null;
if (getAttributes().containsKey(PROP_USER)) {
usr = (String) getAttributes().get(PROP_USER);
} else {
usr = poolProperties.getUsername();
getAttributes().put(PROP_USER, usr);
}
if (getAttributes().containsKey(PROP_PASSWORD)) {
pwd = (String) getAttributes().get(PROP_PASSWORD);
} else {
pwd = poolProperties.getPassword();
getAttributes().put(PROP_PASSWORD, pwd);
}
Properties properties = PoolUtilities.clone(poolProperties.getDbProperties());
if (usr != null) properties.setProperty(PROP_USER, usr);
if (pwd != null) properties.setProperty(PROP_PASSWORD, pwd);
try {
connection = driver.connect(driverURL, properties);
} catch (Exception x) {
if (log.isDebugEnabled()) {
log.debug("Unable to connect to database.", x);
}
if (parent.jmxPool!=null) {
parent.jmxPool.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_CONNECT,
ConnectionPool.getStackTrace(x));
}
if (x instanceof SQLException) {
throw (SQLException)x;
} else {
SQLException ex = new SQLException(x.getMessage());
ex.initCause(x);
throw ex;
}
}
if (connection==null) {
throw new SQLException("Driver:"+driver+" returned null for URL:"+driverURL);
}
}
/**
*
* @return true if connect() was called successfully and disconnect has not yet been called
*/
public boolean isInitialized() {
return connection!=null;
}
/**
* Issues a call to {@link #disconnect(boolean)} with the argument false followed by a call to
* {@link #connect()}
* @throws SQLException if the call to {@link #connect()} fails.
*/
public void reconnect() throws SQLException {
this.disconnect(false);
this.connect();
} //reconnect
/**
* Disconnects the connection. All exceptions are logged using debug level.
* @param finalize if set to true, a call to {@link ConnectionPool#finalize(PooledConnection)} is called.
*/
private void disconnect(boolean finalize) {
if (isDiscarded() && connection == null) {
return;
}
setDiscarded(true);
if (connection != null) {
try {
parent.disconnectEvent(this, finalize);
if (xaConnection == null) {
connection.close();
} else {
xaConnection.close();
}
}catch (Exception ignore) {
if (log.isDebugEnabled()) {
log.debug("Unable to close underlying SQL connection",ignore);
}
}
}
connection = null;
xaConnection = null;
lastConnected = -1;
if (finalize) parent.finalize(this);
}
//============================================================================
//
//============================================================================
/**
* Returns abandon timeout in milliseconds
* @return abandon timeout in milliseconds
*/
public long getAbandonTimeout() {
if (poolProperties.getRemoveAbandonedTimeout() <= 0) {
return Long.MAX_VALUE;
} else {
return poolProperties.getRemoveAbandonedTimeout()*1000;
} //end if
}
/**
* Returns true if the connection pool is configured
* to do validation for a certain action.
* @param action
*/
private boolean doValidate(int action) {
if (action == PooledConnection.VALIDATE_BORROW &&
poolProperties.isTestOnBorrow())
return true;
else if (action == PooledConnection.VALIDATE_RETURN &&
poolProperties.isTestOnReturn())
return true;
else if (action == PooledConnection.VALIDATE_IDLE &&
poolProperties.isTestWhileIdle())
return true;
else if (action == PooledConnection.VALIDATE_INIT &&
poolProperties.isTestOnConnect())
return true;
else if (action == PooledConnection.VALIDATE_INIT &&
poolProperties.getInitSQL()!=null)
return true;
else
return false;
}
/**Returns true if the object is still valid. if not
* the pool will call the getExpiredAction() and follow up with one
* of the four expired methods
*/
public boolean validate(int validateAction) {
return validate(validateAction,null);
}
/**
* Validates a connection.
* @param validateAction the action used. One of {@link #VALIDATE_BORROW}, {@link #VALIDATE_IDLE},
* {@link #VALIDATE_INIT} or {@link #VALIDATE_RETURN}
* @param sql the SQL to be used during validation. If the {@link PoolConfiguration#setInitSQL(String)} has been called with a non null
* value and the action is {@link #VALIDATE_INIT} the init SQL will be used for validation.
*
* @return true if the connection was validated successfully. It returns true even if validation was not performed, such as when
* {@link PoolConfiguration#setValidationInterval(long)} has been called with a positive value.
* <p>
* false if the validation failed. The caller should close the connection if false is returned since a session could have been left in
* an unknown state during initialization.
*/
public boolean validate(int validateAction,String sql) {
if (this.isDiscarded()) {
return false;
}
if (!doValidate(validateAction)) {
//no validation required, no init sql and props not set
return true;
}
//Don't bother validating if already have recently enough
long now = System.currentTimeMillis();
if (validateAction!=VALIDATE_INIT &&
poolProperties.getValidationInterval() > 0 &&
(now - this.lastValidated) <
poolProperties.getValidationInterval()) {
return true;
}
if (poolProperties.getValidator() != null) {
if (poolProperties.getValidator().validate(connection, validateAction)) {
this.lastValidated = now;
return true;
} else {
if (getPoolProperties().getLogValidationErrors()) {
log.error("Custom validation through "+poolProperties.getValidator()+" failed.");
}
return false;
}
}
String query = sql;
if (validateAction == VALIDATE_INIT && poolProperties.getInitSQL() != null) {
query = poolProperties.getInitSQL();
}
if (query == null) {
query = poolProperties.getValidationQuery();
}
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.execute(query);
stmt.close();
this.lastValidated = now;
return true;
} catch (Exception ex) {
if (getPoolProperties().getLogValidationErrors()) {
log.warn("SQL Validation error", ex);
} else if (log.isDebugEnabled()) {
log.debug("Unable to validate object:",ex);
}
if (stmt!=null)
try { stmt.close();} catch (Exception ignore2){/*NOOP*/}
}
return false;
} //validate
/**
* The time limit for how long the object
* can remain unused before it is released
* @return {@link PoolConfiguration#getMinEvictableIdleTimeMillis()}
*/
public long getReleaseTime() {
return this.poolProperties.getMinEvictableIdleTimeMillis();
}
/**
* This method is called if (Now - timeCheckedIn > getReleaseTime())
* This method disconnects the connection, logs an error in debug mode if it happens
* then sets the {@link #released} flag to false. Any attempts to connect this cached object again
* will fail per {@link #connect()}
* The connection pool uses the atomic return value to decrement the pool size counter.
* @return true if this is the first time this method has been called. false if this method has been called before.
*/
public boolean release() {
try {
disconnect(true);
} catch (Exception x) {
if (log.isDebugEnabled()) {
log.debug("Unable to close SQL connection",x);
}
}
return released.compareAndSet(false, true);
}
/**
* The pool will set the stack trace when it is check out and
* checked in
* @param trace the stack trace for this connection
*/
public void setStackTrace(String trace) {
abandonTrace = trace;
}
/**
* Returns the stack trace from when this connection was borrowed. Can return null if no stack trace was set.
* @return the stack trace or null of no trace was set
*/
public String getStackTrace() {
return abandonTrace;
}
/**
* Sets a timestamp on this connection. A timestamp usually means that some operation
* performed successfully.
* @param timestamp the timestamp as defined by {@link System#currentTimeMillis()}
*/
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
setSuspect(false);
}
public boolean isSuspect() {
return suspect;
}
public void setSuspect(boolean suspect) {
this.suspect = suspect;
}
/**
* An interceptor can call this method with the value true, and the connection will be closed when it is returned to the pool.
* @param discarded - only valid value is true
* @throws IllegalStateException if this method is called with the value false and the value true has already been set.
*/
public void setDiscarded(boolean discarded) {
if (this.discarded && !discarded) throw new IllegalStateException("Unable to change the state once the connection has been discarded");
this.discarded = discarded;
}
/**
* Set the timestamp the connection was last validated.
* This flag is used to keep track when we are using a {@link PoolConfiguration#setValidationInterval(long) validation-interval}.
* @param lastValidated a timestamp as defined by {@link System#currentTimeMillis()}
*/
public void setLastValidated(long lastValidated) {
this.lastValidated = lastValidated;
}
/**
* Sets the pool configuration for this connection and connection pool.
* Object is shared with the {@link ConnectionPool}
* @param poolProperties
*/
public void setPoolProperties(PoolConfiguration poolProperties) {
this.poolProperties = poolProperties;
}
/**
* Return the timestamps of last pool action. Timestamps are typically set when connections
* are borrowed from the pool. It is used to keep track of {@link PoolConfiguration#setRemoveAbandonedTimeout(int) abandon-timeouts}.
* This timestamp can also be reset by the {@link org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer#invoke(Object, java.lang.reflect.Method, Object[])}
* @return the timestamp of the last pool action as defined by {@link System#currentTimeMillis()}
*/
public long getTimestamp() {
return timestamp;
}
/**
* Returns the discarded flag.
* @return the discarded flag. If the value is true,
* either {@link #disconnect(boolean)} has been called or it will be called when the connection is returned to the pool.
*/
public boolean isDiscarded() {
return discarded;
}
/**
* Returns the timestamp of the last successful validation query execution.
* @return the timestamp of the last successful validation query execution as defined by {@link System#currentTimeMillis()}
*/
public long getLastValidated() {
return lastValidated;
}
/**
* Returns the configuration for this connection and pool
* @return the configuration for this connection and pool
*/
public PoolConfiguration getPoolProperties() {
return poolProperties;
}
/**
* Locks the connection only if either {@link PoolConfiguration#isPoolSweeperEnabled()} or
* {@link PoolConfiguration#getUseLock()} return true. The per connection lock ensures thread safety is
* multiple threads are performing operations on the connection.
* Otherwise this is a noop for performance
*/
public void lock() {
if (poolProperties.getUseLock() || this.poolProperties.isPoolSweeperEnabled()) {
//optimized, only use a lock when there is concurrency
lock.writeLock().lock();
}
}
/**
* Unlocks the connection only if the sweeper is enabled
* Otherwise this is a noop for performance
*/
public void unlock() {
if (poolProperties.getUseLock() || this.poolProperties.isPoolSweeperEnabled()) {
//optimized, only use a lock when there is concurrency
lock.writeLock().unlock();
}
}
/**
* Returns the underlying connection
* @return the underlying JDBC connection as it was returned from the JDBC driver
* @see javax.sql.PooledConnection#getConnection()
*/
public java.sql.Connection getConnection() {
return this.connection;
}
/**
* Returns the underlying XA connection
* @return the underlying XA connection as it was returned from the Datasource
*/
public javax.sql.XAConnection getXAConnection() {
return this.xaConnection;
}
/**
* Returns the timestamp of when the connection was last connected to the database.
* ie, a successful call to {@link java.sql.Driver#connect(String, java.util.Properties)}.
* @return the timestamp when this connection was created as defined by {@link System#currentTimeMillis()}
*/
public long getLastConnected() {
return lastConnected;
}
/**
* Returns the first handler in the interceptor chain
* @return the first interceptor for this connection
*/
public JdbcInterceptor getHandler() {
return handler;
}
public void setHandler(JdbcInterceptor handler) {
if (this.handler!=null && this.handler!=handler) {
JdbcInterceptor interceptor = this.handler;
while (interceptor!=null) {
interceptor.reset(null, null);
interceptor = interceptor.getNext();
}//while
}//end if
this.handler = handler;
}
@Override
public String toString() {
return "PooledConnection["+(connection!=null?connection.toString():"null")+"]";
}
/**
* Returns true if this connection has been released and wont be reused.
* @return true if the method {@link #release()} has been called
*/
public boolean isReleased() {
return released.get();
}
public HashMap<Object,Object> getAttributes() {
return attributes;
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java
|
/* 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.jdbc.pool.jmx;
/**
* @author Filip Hanik
*/
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jdbc.pool.PoolConfiguration;
import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition;
import org.apache.tomcat.jdbc.pool.PoolUtilities;
import org.apache.tomcat.jdbc.pool.Validator;
public class ConnectionPool extends NotificationBroadcasterSupport implements ConnectionPoolMBean {
/**
* logger
*/
private static final Log log = LogFactory.getLog(ConnectionPool.class);
/**
* the connection pool
*/
protected org.apache.tomcat.jdbc.pool.ConnectionPool pool = null;
/**
* sequence for JMX notifications
*/
protected AtomicInteger sequence = new AtomicInteger(0);
/**
* Listeners that are local and interested in our notifications, no need for JMX
*/
protected ConcurrentLinkedQueue<NotificationListener> listeners =
new ConcurrentLinkedQueue<>();
public ConnectionPool(org.apache.tomcat.jdbc.pool.ConnectionPool pool) {
super();
this.pool = pool;
}
public org.apache.tomcat.jdbc.pool.ConnectionPool getPool() {
return pool;
}
public PoolConfiguration getPoolProperties() {
return pool.getPoolProperties();
}
//=================================================================
// NOTIFICATION INFO
//=================================================================
public static final String NOTIFY_INIT = "INIT FAILED";
public static final String NOTIFY_CONNECT = "CONNECTION FAILED";
public static final String NOTIFY_ABANDON = "CONNECTION ABANDONED";
public static final String SLOW_QUERY_NOTIFICATION = "SLOW QUERY";
public static final String FAILED_QUERY_NOTIFICATION = "FAILED QUERY";
public static final String SUSPECT_ABANDONED_NOTIFICATION = "SUSPECT CONNETION ABANDONED";
public static final String POOL_EMPTY = "POOL EMPTY";
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
MBeanNotificationInfo[] pres = super.getNotificationInfo();
MBeanNotificationInfo[] loc = getDefaultNotificationInfo();
MBeanNotificationInfo[] aug = new MBeanNotificationInfo[pres.length + loc.length];
if (pres.length>0) System.arraycopy(pres, 0, aug, 0, pres.length);
if (loc.length >0) System.arraycopy(loc, 0, aug, pres.length, loc.length);
return aug;
}
public static MBeanNotificationInfo[] getDefaultNotificationInfo() {
String[] types = new String[] {NOTIFY_INIT, NOTIFY_CONNECT, NOTIFY_ABANDON, SLOW_QUERY_NOTIFICATION, FAILED_QUERY_NOTIFICATION, SUSPECT_ABANDONED_NOTIFICATION};
String name = Notification.class.getName();
String description = "A connection pool error condition was met.";
MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description);
return new MBeanNotificationInfo[] {info};
}
/**
* Return true if the notification was sent successfully, false otherwise.
* @param type
* @param message
* @return true if the notification succeeded
*/
public boolean notify(final String type, String message) {
try {
Notification n = new Notification(
type,
this,
sequence.incrementAndGet(),
System.currentTimeMillis(),
"["+type+"] "+message);
sendNotification(n);
for (NotificationListener listener : listeners) {
listener.handleNotification(n,this);
}
return true;
}catch (Exception x) {
if (log.isDebugEnabled()) {
log.debug("Notify failed. Type="+type+"; Message="+message,x);
}
return false;
}
}
public void addListener(NotificationListener list) {
listeners.add(list);
}
public boolean removeListener(NotificationListener list) {
return listeners.remove(list);
}
//=================================================================
// POOL STATS
//=================================================================
@Override
public int getSize() {
return pool.getSize();
}
@Override
public int getIdle() {
return pool.getIdle();
}
@Override
public int getActive() {
return pool.getActive();
}
@Override
public int getNumIdle() {
return getIdle();
}
@Override
public int getNumActive() {
return getActive();
}
@Override
public int getWaitCount() {
return pool.getWaitCount();
}
//=================================================================
// POOL OPERATIONS
//=================================================================
@Override
public void checkIdle() {
pool.checkIdle();
}
@Override
public void checkAbandoned() {
pool.checkAbandoned();
}
@Override
public void testIdle() {
pool.testAllIdle();
}
//=================================================================
// POOL PROPERTIES
//=================================================================
//=========================================================
// PROPERTIES / CONFIGURATION
//=========================================================
@Override
public String getConnectionProperties() {
return getPoolProperties().getConnectionProperties();
}
@Override
public Properties getDbProperties() {
return PoolUtilities.cloneWithoutPassword(getPoolProperties().getDbProperties());
}
@Override
public String getDefaultCatalog() {
return getPoolProperties().getDefaultCatalog();
}
@Override
public int getDefaultTransactionIsolation() {
return getPoolProperties().getDefaultTransactionIsolation();
}
@Override
public String getDriverClassName() {
return getPoolProperties().getDriverClassName();
}
@Override
public int getInitialSize() {
return getPoolProperties().getInitialSize();
}
@Override
public String getInitSQL() {
return getPoolProperties().getInitSQL();
}
@Override
public String getJdbcInterceptors() {
return getPoolProperties().getJdbcInterceptors();
}
@Override
public int getMaxActive() {
return getPoolProperties().getMaxActive();
}
@Override
public int getMaxIdle() {
return getPoolProperties().getMaxIdle();
}
@Override
public int getMaxWait() {
return getPoolProperties().getMaxWait();
}
@Override
public int getMinEvictableIdleTimeMillis() {
return getPoolProperties().getMinEvictableIdleTimeMillis();
}
@Override
public int getMinIdle() {
return getPoolProperties().getMinIdle();
}
@Override
public long getMaxAge() {
return getPoolProperties().getMaxAge();
}
@Override
public String getName() {
return this.getPoolName();
}
@Override
public int getNumTestsPerEvictionRun() {
return getPoolProperties().getNumTestsPerEvictionRun();
}
/**
* @return DOES NOT RETURN THE PASSWORD, IT WOULD SHOW UP IN JMX
*/
@Override
public String getPassword() {
return "Password not available as DataSource/JMX operation.";
}
@Override
public int getRemoveAbandonedTimeout() {
return getPoolProperties().getRemoveAbandonedTimeout();
}
@Override
public int getTimeBetweenEvictionRunsMillis() {
return getPoolProperties().getTimeBetweenEvictionRunsMillis();
}
@Override
public String getUrl() {
return getPoolProperties().getUrl();
}
@Override
public String getUsername() {
return getPoolProperties().getUsername();
}
@Override
public long getValidationInterval() {
return getPoolProperties().getValidationInterval();
}
@Override
public String getValidationQuery() {
return getPoolProperties().getValidationQuery();
}
/**
* {@inheritDoc}
*/
@Override
public String getValidatorClassName() {
return getPoolProperties().getValidatorClassName();
}
/**
* {@inheritDoc}
*/
@Override
public Validator getValidator() {
return getPoolProperties().getValidator();
}
@Override
public boolean isAccessToUnderlyingConnectionAllowed() {
return getPoolProperties().isAccessToUnderlyingConnectionAllowed();
}
@Override
public Boolean isDefaultAutoCommit() {
return getPoolProperties().isDefaultAutoCommit();
}
@Override
public Boolean isDefaultReadOnly() {
return getPoolProperties().isDefaultReadOnly();
}
@Override
public boolean isLogAbandoned() {
return getPoolProperties().isLogAbandoned();
}
@Override
public boolean isPoolSweeperEnabled() {
return getPoolProperties().isPoolSweeperEnabled();
}
@Override
public boolean isRemoveAbandoned() {
return getPoolProperties().isRemoveAbandoned();
}
@Override
public int getAbandonWhenPercentageFull() {
return getPoolProperties().getAbandonWhenPercentageFull();
}
@Override
public boolean isTestOnBorrow() {
return getPoolProperties().isTestOnBorrow();
}
@Override
public boolean isTestOnConnect() {
return getPoolProperties().isTestOnConnect();
}
@Override
public boolean isTestOnReturn() {
return getPoolProperties().isTestOnReturn();
}
@Override
public boolean isTestWhileIdle() {
return getPoolProperties().isTestWhileIdle();
}
@Override
public Boolean getDefaultAutoCommit() {
return getPoolProperties().getDefaultAutoCommit();
}
@Override
public Boolean getDefaultReadOnly() {
return getPoolProperties().getDefaultReadOnly();
}
@Override
public InterceptorDefinition[] getJdbcInterceptorsAsArray() {
return getPoolProperties().getJdbcInterceptorsAsArray();
}
@Override
public boolean getUseLock() {
return getPoolProperties().getUseLock();
}
@Override
public boolean isFairQueue() {
return getPoolProperties().isFairQueue();
}
@Override
public boolean isJmxEnabled() {
return getPoolProperties().isJmxEnabled();
}
@Override
public boolean isUseEquals() {
return getPoolProperties().isUseEquals();
}
@Override
public void setAbandonWhenPercentageFull(int percentage) {
getPoolProperties().setAbandonWhenPercentageFull(percentage);
}
@Override
public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) {
getPoolProperties().setAccessToUnderlyingConnectionAllowed(accessToUnderlyingConnectionAllowed);
}
@Override
public void setDbProperties(Properties dbProperties) {
getPoolProperties().setDbProperties(dbProperties);
}
@Override
public void setDefaultReadOnly(Boolean defaultReadOnly) {
getPoolProperties().setDefaultReadOnly(defaultReadOnly);
}
@Override
public void setMaxAge(long maxAge) {
getPoolProperties().setMaxAge(maxAge);
}
@Override
public void setName(String name) {
getPoolProperties().setName(name);
}
@Override
public String getPoolName() {
return getPoolProperties().getName();
}
@Override
public void setConnectionProperties(String connectionProperties) {
getPoolProperties().setConnectionProperties(connectionProperties);
}
@Override
public void setDefaultAutoCommit(Boolean defaultAutoCommit) {
getPoolProperties().setDefaultAutoCommit(defaultAutoCommit);
}
@Override
public void setDefaultCatalog(String defaultCatalog) {
getPoolProperties().setDefaultCatalog(defaultCatalog);
}
@Override
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
getPoolProperties().setDefaultTransactionIsolation(defaultTransactionIsolation);
}
@Override
public void setDriverClassName(String driverClassName) {
getPoolProperties().setDriverClassName(driverClassName);
}
@Override
public void setFairQueue(boolean fairQueue) {
getPoolProperties().setFairQueue(fairQueue);
}
@Override
public void setInitialSize(int initialSize) {
// noop - this pool is already running
throw new UnsupportedOperationException();
}
@Override
public void setInitSQL(String initSQL) {
getPoolProperties().setInitSQL(initSQL);
}
@Override
public void setJdbcInterceptors(String jdbcInterceptors) {
// noop - this pool is already running
throw new UnsupportedOperationException();
}
@Override
public void setJmxEnabled(boolean jmxEnabled) {
// noop - this pool is already running and obviously jmx enabled
throw new UnsupportedOperationException();
}
@Override
public void setLogAbandoned(boolean logAbandoned) {
getPoolProperties().setLogAbandoned(logAbandoned);
}
@Override
public void setMaxActive(int maxActive) {
getPoolProperties().setMaxActive(maxActive);
}
@Override
public void setMaxIdle(int maxIdle) {
getPoolProperties().setMaxIdle(maxIdle);
}
@Override
public void setMaxWait(int maxWait) {
getPoolProperties().setMaxWait(maxWait);
}
@Override
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setMinIdle(int minIdle) {
getPoolProperties().setMinIdle(minIdle);
}
@Override
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
getPoolProperties().setNumTestsPerEvictionRun(numTestsPerEvictionRun);
}
@Override
public void setPassword(String password) {
getPoolProperties().setPassword(password);
}
@Override
public void setRemoveAbandoned(boolean removeAbandoned) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setRemoveAbandoned(removeAbandoned);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setRemoveAbandonedTimeout(removeAbandonedTimeout);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setTestOnBorrow(boolean testOnBorrow) {
getPoolProperties().setTestOnBorrow(testOnBorrow);
}
@Override
public void setTestOnConnect(boolean testOnConnect) {
getPoolProperties().setTestOnConnect(testOnConnect);
}
@Override
public void setTestOnReturn(boolean testOnReturn) {
getPoolProperties().setTestOnReturn(testOnReturn);
}
@Override
public void setTestWhileIdle(boolean testWhileIdle) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setTestWhileIdle(testWhileIdle);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
boolean wasEnabled = getPoolProperties().isPoolSweeperEnabled();
getPoolProperties().setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
boolean shouldBeEnabled = getPoolProperties().isPoolSweeperEnabled();
//make sure pool cleaner starts when it should
if (!wasEnabled && shouldBeEnabled) pool.initializePoolCleaner(getPoolProperties());
}
@Override
public void setUrl(String url) {
getPoolProperties().setUrl(url);
}
@Override
public void setUseEquals(boolean useEquals) {
getPoolProperties().setUseEquals(useEquals);
}
@Override
public void setUseLock(boolean useLock) {
getPoolProperties().setUseLock(useLock);
}
@Override
public void setUsername(String username) {
getPoolProperties().setUsername(username);
}
@Override
public void setValidationInterval(long validationInterval) {
getPoolProperties().setValidationInterval(validationInterval);
}
@Override
public void setValidationQuery(String validationQuery) {
getPoolProperties().setValidationQuery(validationQuery);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidatorClassName(String className) {
getPoolProperties().setValidatorClassName(className);
}
/**
* {@inheritDoc}
*/
@Override
public int getSuspectTimeout() {
return getPoolProperties().getSuspectTimeout();
}
/**
* {@inheritDoc}
*/
@Override
public void setSuspectTimeout(int seconds) {
getPoolProperties().setSuspectTimeout(seconds);
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSource(Object ds) {
getPoolProperties().setDataSource(ds);
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataSource() {
return getPoolProperties().getDataSource();
}
/**
* {@inheritDoc}
*/
@Override
public void setDataSourceJNDI(String jndiDS) {
getPoolProperties().setDataSourceJNDI(jndiDS);
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSourceJNDI() {
return getPoolProperties().getDataSourceJNDI();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlternateUsernameAllowed() {
return getPoolProperties().isAlternateUsernameAllowed();
}
/**
* {@inheritDoc}
*/
@Override
public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) {
getPoolProperties().setAlternateUsernameAllowed(alternateUsernameAllowed);
}
/**
* {@inheritDoc}
*/
@Override
public void setValidator(Validator validator) {
getPoolProperties().setValidator(validator);
}
/**
* {@inheritDoc}
*/
@Override
public void setCommitOnReturn(boolean commitOnReturn) {
getPoolProperties().setCommitOnReturn(commitOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCommitOnReturn() {
return getPoolProperties().getCommitOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setRollbackOnReturn(boolean rollbackOnReturn) {
getPoolProperties().setRollbackOnReturn(rollbackOnReturn);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getRollbackOnReturn() {
return getPoolProperties().getRollbackOnReturn();
}
/**
* {@inheritDoc}
*/
@Override
public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) {
getPoolProperties().setUseDisposableConnectionFacade(useDisposableConnectionFacade);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getUseDisposableConnectionFacade() {
return getPoolProperties().getUseDisposableConnectionFacade();
}
/**
* {@inheritDoc}
*/
@Override
public void setLogValidationErrors(boolean logValidationErrors) {
getPoolProperties().setLogValidationErrors(logValidationErrors);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getLogValidationErrors() {
return getPoolProperties().getLogValidationErrors();
}
/**
* {@inheritDoc}
*/
@Override
public boolean getPropagateInterruptState() {
return getPoolProperties().getPropagateInterruptState();
}
/**
* {@inheritDoc}
*/
@Override
public void setPropagateInterruptState(boolean propagateInterruptState) {
getPoolProperties().setPropagateInterruptState(propagateInterruptState);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIgnoreExceptionOnPreLoad() {
return getPoolProperties().isIgnoreExceptionOnPreLoad();
}
/**
* {@inheritDoc}
*/
@Override
public void setIgnoreExceptionOnPreLoad(boolean ignoreExceptionOnPreLoad) {
getPoolProperties().setIgnoreExceptionOnPreLoad(ignoreExceptionOnPreLoad);
}
/**
* {@inheritDoc}
*/
@Override
public void purge() {
pool.purge();
}
/**
* {@inheritDoc}
*/
@Override
public void purgeOnReturn() {
pool.purgeOnReturn();
}
}
|
54,693
|
Bug 54693 Add a validationQueryTimeout property
| null |
resolved fixed
|
b022c57
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-09T10:11:07Z
| 2013-03-14T00:13:20Z
|
modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/test/TestValidationQueryTimeout.java
| |
55,552
|
Bug 55552 Potential NullPointerException in compiled JSPs if expected EL result is of primitive type
| null |
resolved fixed
|
66932c4
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-12T10:06:16Z
| 2013-09-12T10:00:00Z
|
java/org/apache/jasper/compiler/JspUtil.java
|
/*
* 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.jasper.compiler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
import org.xml.sax.Attributes;
/**
* This class has all the utility method(s). Ideally should move all the bean
* containers here.
*
* @author Mandar Raje.
* @author Rajiv Mordani.
* @author Danno Ferrin
* @author Pierre Delisle
* @author Shawn Bayern
* @author Mark Roth
*/
public class JspUtil {
private static final String WEB_INF_TAGS = "/WEB-INF/tags/";
private static final String META_INF_TAGS = "/META-INF/tags/";
// Delimiters for request-time expressions (JSP and XML syntax)
private static final String OPEN_EXPR = "<%=";
private static final String CLOSE_EXPR = "%>";
private static final String javaKeywords[] = { "abstract", "assert",
"boolean", "break", "byte", "case", "catch", "char", "class",
"const", "continue", "default", "do", "double", "else", "enum",
"extends", "final", "finally", "float", "for", "goto", "if",
"implements", "import", "instanceof", "int", "interface", "long",
"native", "new", "package", "private", "protected", "public",
"return", "short", "static", "strictfp", "super", "switch",
"synchronized", "this", "throw", "throws", "transient", "try",
"void", "volatile", "while" };
public static final int CHUNKSIZE = 1024;
/**
* Takes a potential expression and converts it into XML form
*/
public static String getExprInXml(String expression) {
String returnString;
int length = expression.length();
if (expression.startsWith(OPEN_EXPR) &&
expression.endsWith(CLOSE_EXPR)) {
returnString = expression.substring(1, length - 1);
} else {
returnString = expression;
}
return escapeXml(returnString);
}
/**
* Checks to see if the given scope is valid.
*
* @param scope
* The scope to be checked
* @param n
* The Node containing the 'scope' attribute whose value is to be
* checked
* @param err
* error dispatcher
*
* @throws JasperException
* if scope is not null and different from "page",
* "request", "session", and
* "application"
*/
public static void checkScope(String scope, Node n, ErrorDispatcher err)
throws JasperException {
if (scope != null && !scope.equals("page") && !scope.equals("request")
&& !scope.equals("session") && !scope.equals("application")) {
err.jspError(n, "jsp.error.invalid.scope", scope);
}
}
/**
* Checks if all mandatory attributes are present and if all attributes
* present have valid names. Checks attributes specified as XML-style
* attributes as well as attributes specified using the jsp:attribute
* standard action.
*/
public static void checkAttributes(String typeOfTag, Node n,
ValidAttribute[] validAttributes, ErrorDispatcher err)
throws JasperException {
Attributes attrs = n.getAttributes();
Mark start = n.getStart();
boolean valid = true;
// AttributesImpl.removeAttribute is broken, so we do this...
int tempLength = (attrs == null) ? 0 : attrs.getLength();
Vector<String> temp = new Vector<>(tempLength, 1);
for (int i = 0; i < tempLength; i++) {
@SuppressWarnings("null") // If attrs==null, tempLength == 0
String qName = attrs.getQName(i);
if ((!qName.equals("xmlns")) && (!qName.startsWith("xmlns:"))) {
temp.addElement(qName);
}
}
// Add names of attributes specified using jsp:attribute
Node.Nodes tagBody = n.getBody();
if (tagBody != null) {
int numSubElements = tagBody.size();
for (int i = 0; i < numSubElements; i++) {
Node node = tagBody.getNode(i);
if (node instanceof Node.NamedAttribute) {
String attrName = node.getAttributeValue("name");
temp.addElement(attrName);
// Check if this value appear in the attribute of the node
if (n.getAttributeValue(attrName) != null) {
err.jspError(n,
"jsp.error.duplicate.name.jspattribute",
attrName);
}
} else {
// Nothing can come before jsp:attribute, and only
// jsp:body can come after it.
break;
}
}
}
/*
* First check to see if all the mandatory attributes are present. If so
* only then proceed to see if the other attributes are valid for the
* particular tag.
*/
String missingAttribute = null;
for (int i = 0; i < validAttributes.length; i++) {
int attrPos;
if (validAttributes[i].mandatory) {
attrPos = temp.indexOf(validAttributes[i].name);
if (attrPos != -1) {
temp.remove(attrPos);
valid = true;
} else {
valid = false;
missingAttribute = validAttributes[i].name;
break;
}
}
}
// If mandatory attribute is missing then the exception is thrown
if (!valid) {
err.jspError(start, "jsp.error.mandatory.attribute", typeOfTag,
missingAttribute);
}
// Check to see if there are any more attributes for the specified tag.
int attrLeftLength = temp.size();
if (attrLeftLength == 0) {
return;
}
// Now check to see if the rest of the attributes are valid too.
String attribute = null;
for (int j = 0; j < attrLeftLength; j++) {
valid = false;
attribute = temp.elementAt(j);
for (int i = 0; i < validAttributes.length; i++) {
if (attribute.equals(validAttributes[i].name)) {
valid = true;
break;
}
}
if (!valid) {
err.jspError(start, "jsp.error.invalid.attribute", typeOfTag,
attribute);
}
}
// XXX *could* move EL-syntax validation here... (sb)
}
/**
* Escape the 5 entities defined by XML.
*/
public static String escapeXml(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<') {
sb.append("<");
} else if (c == '>') {
sb.append(">");
} else if (c == '\'') {
sb.append("'");
} else if (c == '&') {
sb.append("&");
} else if (c == '"') {
sb.append(""");
} else {
sb.append(c);
}
}
return sb.toString();
}
public static class ValidAttribute {
private final String name;
private final boolean mandatory;
public ValidAttribute(String name, boolean mandatory) {
this.name = name;
this.mandatory = mandatory;
}
public ValidAttribute(String name) {
this(name, false);
}
}
/**
* Convert a String value to 'boolean'. Besides the standard conversions
* done by Boolean.valueOf(s).booleanValue(), the value "yes" (ignore case)
* is also converted to 'true'. If 's' is null, then 'false' is returned.
*
* @param s
* the string to be converted
* @return the boolean value associated with the string s
*/
public static boolean booleanValue(String s) {
boolean b = false;
if (s != null) {
if (s.equalsIgnoreCase("yes")) {
b = true;
} else {
b = Boolean.valueOf(s).booleanValue();
}
}
return b;
}
/**
* Returns the <tt>Class</tt> object associated with the class or
* interface with the given string name.
*
* <p>
* The <tt>Class</tt> object is determined by passing the given string
* name to the <tt>Class.forName()</tt> method, unless the given string
* name represents a primitive type, in which case it is converted to a
* <tt>Class</tt> object by appending ".class" to it (e.g., "int.class").
*/
public static Class<?> toClass(String type, ClassLoader loader)
throws ClassNotFoundException {
Class<?> c = null;
int i0 = type.indexOf('[');
int dims = 0;
if (i0 > 0) {
// This is an array. Count the dimensions
for (int i = 0; i < type.length(); i++) {
if (type.charAt(i) == '[') {
dims++;
}
}
type = type.substring(0, i0);
}
if ("boolean".equals(type)) {
c = boolean.class;
} else if ("char".equals(type)) {
c = char.class;
} else if ("byte".equals(type)) {
c = byte.class;
} else if ("short".equals(type)) {
c = short.class;
} else if ("int".equals(type)) {
c = int.class;
} else if ("long".equals(type)) {
c = long.class;
} else if ("float".equals(type)) {
c = float.class;
} else if ("double".equals(type)) {
c = double.class;
} else if ("void".equals(type)) {
c = void.class;
} else if (type.indexOf('[') < 0) {
c = loader.loadClass(type);
}
if (dims == 0) {
return c;
}
if (dims == 1) {
return java.lang.reflect.Array.newInstance(c, 1).getClass();
}
// Array of more than i dimension
return java.lang.reflect.Array.newInstance(c, new int[dims]).getClass();
}
/**
* Produces a String representing a call to the EL interpreter.
*
* @param expression
* a String containing zero or more "${}" expressions
* @param expectedType
* the expected type of the interpreted result
* @param fnmapvar
* Variable pointing to a function map.
* @param XmlEscape
* True if the result should do XML escaping
* @return a String representing a call to the EL interpreter.
*/
public static String interpreterCall(boolean isTagFile, String expression,
Class<?> expectedType, String fnmapvar, boolean XmlEscape) {
/*
* Determine which context object to use.
*/
String jspCtxt = null;
if (isTagFile) {
jspCtxt = "this.getJspContext()";
} else {
jspCtxt = "_jspx_page_context";
}
/*
* Determine whether to use the expected type's textual name or, if it's
* a primitive, the name of its correspondent boxed type.
*/
String targetType = expectedType.getCanonicalName();
String primitiveConverterMethod = null;
if (expectedType.isPrimitive()) {
if (expectedType.equals(Boolean.TYPE)) {
targetType = Boolean.class.getName();
primitiveConverterMethod = "booleanValue";
} else if (expectedType.equals(Byte.TYPE)) {
targetType = Byte.class.getName();
primitiveConverterMethod = "byteValue";
} else if (expectedType.equals(Character.TYPE)) {
targetType = Character.class.getName();
primitiveConverterMethod = "charValue";
} else if (expectedType.equals(Short.TYPE)) {
targetType = Short.class.getName();
primitiveConverterMethod = "shortValue";
} else if (expectedType.equals(Integer.TYPE)) {
targetType = Integer.class.getName();
primitiveConverterMethod = "intValue";
} else if (expectedType.equals(Long.TYPE)) {
targetType = Long.class.getName();
primitiveConverterMethod = "longValue";
} else if (expectedType.equals(Float.TYPE)) {
targetType = Float.class.getName();
primitiveConverterMethod = "floatValue";
} else if (expectedType.equals(Double.TYPE)) {
targetType = Double.class.getName();
primitiveConverterMethod = "doubleValue";
}
}
if (primitiveConverterMethod != null) {
XmlEscape = false;
}
/*
* Build up the base call to the interpreter.
*/
// XXX - We use a proprietary call to the interpreter for now
// as the current standard machinery is inefficient and requires
// lots of wrappers and adapters. This should all clear up once
// the EL interpreter moves out of JSTL and into its own project.
// In the future, this should be replaced by code that calls
// ExpressionEvaluator.parseExpression() and then cache the resulting
// expression objects. The interpreterCall would simply select
// one of the pre-cached expressions and evaluate it.
// Note that PageContextImpl implements VariableResolver and
// the generated Servlet/SimpleTag implements FunctionMapper, so
// that machinery is already in place (mroth).
targetType = toJavaSourceType(targetType);
StringBuilder call = new StringBuilder(
"("
+ targetType
+ ") "
+ "org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate"
+ "(" + Generator.quote(expression) + ", " + targetType
+ ".class, " + "(javax.servlet.jsp.PageContext)" + jspCtxt + ", "
+ fnmapvar + ", " + XmlEscape + ")");
/*
* Add the primitive converter method if we need to.
*/
if (primitiveConverterMethod != null) {
call.insert(0, "(");
call.append(")." + primitiveConverterMethod + "()");
}
return call.toString();
}
public static String coerceToPrimitiveBoolean(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToBoolean("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "false";
} else {
return Boolean.valueOf(s).toString();
}
}
}
public static String coerceToBoolean(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Boolean) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Boolean.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Boolean(false)";
} else {
// Detect format error at translation time
return "new java.lang.Boolean(" + Boolean.valueOf(s).toString() + ")";
}
}
}
public static String coerceToPrimitiveByte(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToByte("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "(byte) 0";
} else {
return "((byte)" + Byte.valueOf(s).toString() + ")";
}
}
}
public static String coerceToByte(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Byte) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Byte.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Byte((byte) 0)";
} else {
// Detect format error at translation time
return "new java.lang.Byte((byte)" + Byte.valueOf(s).toString() + ")";
}
}
}
public static String coerceToChar(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToChar("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "(char) 0";
} else {
char ch = s.charAt(0);
// this trick avoids escaping issues
return "((char) " + (int) ch + ")";
}
}
}
public static String coerceToCharacter(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Character) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Character.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Character((char) 0)";
} else {
char ch = s.charAt(0);
// this trick avoids escaping issues
return "new java.lang.Character((char) " + (int) ch + ")";
}
}
}
public static String coerceToPrimitiveDouble(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToDouble("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "(double) 0";
} else {
return Double.valueOf(s).toString();
}
}
}
public static String coerceToDouble(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Double) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", Double.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Double(0)";
} else {
// Detect format error at translation time
return "new java.lang.Double(" + Double.valueOf(s).toString() + ")";
}
}
}
public static String coerceToPrimitiveFloat(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToFloat("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "(float) 0";
} else {
return Float.valueOf(s).toString() + "f";
}
}
}
public static String coerceToFloat(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Float) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Float.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Float(0)";
} else {
// Detect format error at translation time
return "new java.lang.Float(" + Float.valueOf(s).toString() + "f)";
}
}
}
public static String coerceToInt(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToInt("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "0";
} else {
return Integer.valueOf(s).toString();
}
}
}
public static String coerceToInteger(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Integer) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Integer.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Integer(0)";
} else {
// Detect format error at translation time
return "new java.lang.Integer(" + Integer.valueOf(s).toString() + ")";
}
}
}
public static String coerceToPrimitiveShort(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToShort("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "(short) 0";
} else {
return "((short) " + Short.valueOf(s).toString() + ")";
}
}
}
public static String coerceToShort(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Short) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Short.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Short((short) 0)";
} else {
// Detect format error at translation time
return "new java.lang.Short(\"" + Short.valueOf(s).toString() + "\")";
}
}
}
public static String coerceToPrimitiveLong(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.coerceToLong("
+ s + ")";
} else {
if (s == null || s.length() == 0) {
return "(long) 0";
} else {
return Long.valueOf(s).toString() + "l";
}
}
}
public static String coerceToLong(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(java.lang.Long) org.apache.jasper.runtime.JspRuntimeLibrary.coerce("
+ s + ", java.lang.Long.class)";
} else {
if (s == null || s.length() == 0) {
return "new java.lang.Long(0)";
} else {
// Detect format error at translation time
return "new java.lang.Long(" + Long.valueOf(s).toString() + "l)";
}
}
}
public static InputStream getInputStream(String fname, JarFile jarFile,
JspCompilationContext ctxt) throws IOException {
InputStream in = null;
if (jarFile != null) {
String jarEntryName = fname.substring(1, fname.length());
ZipEntry jarEntry = jarFile.getEntry(jarEntryName);
if (jarEntry == null) {
throw new FileNotFoundException(Localizer.getMessage(
"jsp.error.file.not.found", fname));
}
in = jarFile.getInputStream(jarEntry);
} else {
in = ctxt.getResourceAsStream(fname);
}
if (in == null) {
throw new FileNotFoundException(Localizer.getMessage(
"jsp.error.file.not.found", fname));
}
return in;
}
/**
* Gets the fully-qualified class name of the tag handler corresponding to
* the given tag file path.
*
* @param path
* Tag file path
* @param err
* Error dispatcher
*
* @return Fully-qualified class name of the tag handler corresponding to
* the given tag file path
*/
public static String getTagHandlerClassName(String path, String urn,
ErrorDispatcher err) throws JasperException {
String className = null;
int begin = 0;
int index;
index = path.lastIndexOf(".tag");
if (index == -1) {
err.jspError("jsp.error.tagfile.badSuffix", path);
}
// It's tempting to remove the ".tag" suffix here, but we can't.
// If we remove it, the fully-qualified class name of this tag
// could conflict with the package name of other tags.
// For instance, the tag file
// /WEB-INF/tags/foo.tag
// would have fully-qualified class name
// org.apache.jsp.tag.web.foo
// which would conflict with the package name of the tag file
// /WEB-INF/tags/foo/bar.tag
index = path.indexOf(WEB_INF_TAGS);
if (index != -1) {
className = Constants.TAG_FILE_PACKAGE_NAME + ".web";
begin = index + WEB_INF_TAGS.length();
} else {
index = path.indexOf(META_INF_TAGS);
if (index != -1) {
className = getClassNameBase(urn);
begin = index + META_INF_TAGS.length();
} else {
err.jspError("jsp.error.tagfile.illegalPath", path);
}
}
className += makeJavaPackage(path.substring(begin));
return className;
}
private static String getClassNameBase(String urn) {
StringBuilder base =
new StringBuilder(Constants.TAG_FILE_PACKAGE_NAME + ".meta.");
if (urn != null) {
base.append(makeJavaPackage(urn));
base.append('.');
}
return base.toString();
}
/**
* Converts the given path to a Java package or fully-qualified class name
*
* @param path
* Path to convert
*
* @return Java package corresponding to the given path
*/
public static final String makeJavaPackage(String path) {
String classNameComponents[] = split(path, "/");
StringBuilder legalClassNames = new StringBuilder();
for (int i = 0; i < classNameComponents.length; i++) {
legalClassNames.append(makeJavaIdentifier(classNameComponents[i]));
if (i < classNameComponents.length - 1) {
legalClassNames.append('.');
}
}
return legalClassNames.toString();
}
/**
* Splits a string into it's components.
*
* @param path
* String to split
* @param pat
* Pattern to split at
* @return the components of the path
*/
private static final String[] split(String path, String pat) {
Vector<String> comps = new Vector<>();
int pos = path.indexOf(pat);
int start = 0;
while (pos >= 0) {
if (pos > start) {
String comp = path.substring(start, pos);
comps.add(comp);
}
start = pos + pat.length();
pos = path.indexOf(pat, start);
}
if (start < path.length()) {
comps.add(path.substring(start));
}
String[] result = new String[comps.size()];
for (int i = 0; i < comps.size(); i++) {
result[i] = comps.elementAt(i);
}
return result;
}
/**
* Converts the given identifier to a legal Java identifier
*
* @param identifier
* Identifier to convert
*
* @return Legal Java identifier corresponding to the given identifier
*/
public static final String makeJavaIdentifier(String identifier) {
return makeJavaIdentifier(identifier, true);
}
/**
* Converts the given identifier to a legal Java identifier
* to be used for JSP Tag file attribute names.
*
* @param identifier
* Identifier to convert
*
* @return Legal Java identifier corresponding to the given identifier
*/
public static final String makeJavaIdentifierForAttribute(String identifier) {
return makeJavaIdentifier(identifier, false);
}
/**
* Converts the given identifier to a legal Java identifier.
*
* @param identifier
* Identifier to convert
*
* @return Legal Java identifier corresponding to the given identifier
*/
private static final String makeJavaIdentifier(String identifier,
boolean periodToUnderscore) {
StringBuilder modifiedIdentifier = new StringBuilder(identifier.length());
if (!Character.isJavaIdentifierStart(identifier.charAt(0))) {
modifiedIdentifier.append('_');
}
for (int i = 0; i < identifier.length(); i++) {
char ch = identifier.charAt(i);
if (Character.isJavaIdentifierPart(ch) &&
(ch != '_' || !periodToUnderscore)) {
modifiedIdentifier.append(ch);
} else if (ch == '.' && periodToUnderscore) {
modifiedIdentifier.append('_');
} else {
modifiedIdentifier.append(mangleChar(ch));
}
}
if (isJavaKeyword(modifiedIdentifier.toString())) {
modifiedIdentifier.append('_');
}
return modifiedIdentifier.toString();
}
/**
* Mangle the specified character to create a legal Java class name.
*/
public static final String mangleChar(char ch) {
char[] result = new char[5];
result[0] = '_';
result[1] = Character.forDigit((ch >> 12) & 0xf, 16);
result[2] = Character.forDigit((ch >> 8) & 0xf, 16);
result[3] = Character.forDigit((ch >> 4) & 0xf, 16);
result[4] = Character.forDigit(ch & 0xf, 16);
return new String(result);
}
/**
* Test whether the argument is a Java keyword
*/
public static boolean isJavaKeyword(String key) {
int i = 0;
int j = javaKeywords.length;
while (i < j) {
int k = (i + j) / 2;
int result = javaKeywords[k].compareTo(key);
if (result == 0) {
return true;
}
if (result < 0) {
i = k + 1;
} else {
j = k;
}
}
return false;
}
static InputStreamReader getReader(String fname, String encoding,
JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err)
throws JasperException, IOException {
return getReader(fname, encoding, jarFile, ctxt, err, 0);
}
static InputStreamReader getReader(String fname, String encoding,
JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err,
int skip) throws JasperException, IOException {
InputStreamReader reader = null;
InputStream in = getInputStream(fname, jarFile, ctxt);
for (int i = 0; i < skip; i++) {
in.read();
}
try {
reader = new InputStreamReader(in, encoding);
} catch (UnsupportedEncodingException ex) {
err.jspError("jsp.error.unsupported.encoding", encoding);
}
return reader;
}
/**
* Handles taking input from TLDs 'java.lang.Object' ->
* 'java.lang.Object.class' 'int' -> 'int.class' 'void' -> 'Void.TYPE'
* 'int[]' -> 'int[].class'
*
* @param type
*/
public static String toJavaSourceTypeFromTld(String type) {
if (type == null || "void".equals(type)) {
return "java.lang.Void.TYPE";
}
return type + ".class";
}
/**
* Class.getName() return arrays in the form "[[[<et>", where et, the
* element type can be one of ZBCDFIJS or L<classname>;. It is
* converted into forms that can be understood by javac.
*/
public static String toJavaSourceType(String type) {
if (type.charAt(0) != '[') {
return type;
}
int dims = 1;
String t = null;
for (int i = 1; i < type.length(); i++) {
if (type.charAt(i) == '[') {
dims++;
} else {
switch (type.charAt(i)) {
case 'Z': t = "boolean"; break;
case 'B': t = "byte"; break;
case 'C': t = "char"; break;
case 'D': t = "double"; break;
case 'F': t = "float"; break;
case 'I': t = "int"; break;
case 'J': t = "long"; break;
case 'S': t = "short"; break;
case 'L': t = type.substring(i+1, type.indexOf(';')); break;
}
break;
}
}
if (t == null) {
// Should never happen
throw new IllegalArgumentException("Unable to extract type from [" +
type + "]");
}
StringBuilder resultType = new StringBuilder(t);
for (; dims > 0; dims--) {
resultType.append("[]");
}
return resultType.toString();
}
}
|
52,558
|
Bug 52558 CometConnectionManagerValve is adding non-serializable Request[] to Session
|
CometConnectionManagerValve is adding HttpServletRequest[] to HttpSession which is preventing the Session being serialized in a Clustered setup. We're resolving this locally using a serializable ConnectionList class with a transient Request[] i.e. public class ConnectionList implements Serializable { transient Request[] connectionList = null; ConnectionList(Request[] connectionList){ this.connectionList = connectionList; } public Request[] get(){ return connectionList; } }
|
resolved fixed
|
b284611
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-12T11:16:15Z
| 2012-01-30T16:13:20Z
|
java/org/apache/catalina/valves/CometConnectionManagerValve.java
|
/*
* 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.valves;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.comet.CometEvent;
import org.apache.catalina.comet.CometProcessor;
import org.apache.catalina.connector.CometEventImpl;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
/**
* <p>Implementation of a Valve that tracks Comet connections, and closes them
* when the associated session expires or the webapp is reloaded.</p>
*
* <p>This Valve should be attached to a Context.</p>
*
* @author Remy Maucherat
* @version $Id$
*/
public class CometConnectionManagerValve extends ValveBase
implements HttpSessionListener, LifecycleListener {
//------------------------------------------------------ Constructor
public CometConnectionManagerValve() {
super(false);
}
// ----------------------------------------------------- Instance Variables
/**
* List of current Comet connections.
*/
protected final List<Request> cometRequests =
Collections.synchronizedList(new ArrayList<Request>());
/**
* Name of session attribute used to store list of comet connections.
*/
protected final String cometRequestsAttribute =
"org.apache.tomcat.comet.connectionList";
/**
* Start this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void startInternal() throws LifecycleException {
if (container instanceof Context) {
container.addLifecycleListener(this);
}
setState(LifecycleState.STARTING);
}
/**
* Stop this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void stopInternal() throws LifecycleException {
setState(LifecycleState.STOPPING);
if (container instanceof Context) {
container.removeLifecycleListener(this);
}
}
@Override
public void lifecycleEvent(LifecycleEvent event) {
if (Lifecycle.BEFORE_STOP_EVENT.equals(event.getType())) {
// The container is getting stopped, close all current connections
Iterator<Request> iterator = cometRequests.iterator();
while (iterator.hasNext()) {
Request request = iterator.next();
// Remove the session tracking attribute as it isn't
// serializable or required.
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(cometRequestsAttribute);
}
// Close the comet connection
CometEventImpl cometEvent = request.getEvent();
try {
cometEvent.setEventType(CometEvent.EventType.END);
cometEvent.setEventSubType(
CometEvent.EventSubType.WEBAPP_RELOAD);
getNext().event(request, request.getResponse(), cometEvent);
} catch (Exception e) {
container.getLogger().warn(
sm.getString("cometConnectionManagerValve.event"),
e);
} finally {
try {
cometEvent.close();
} catch (IOException e) {
container.getLogger().warn(sm.getString(
"cometConnectionManagerValve.event"), e);
}
}
}
cometRequests.clear();
}
}
// --------------------------------------------------------- Public Methods
/**
* Register requests for tracking, whenever needed.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
public void invoke(Request request, Response response)
throws IOException, ServletException {
// Perform the request
getNext().invoke(request, response);
if (request.isComet() && !response.isClosed()) {
// Start tracking this connection, since this is a
// begin event, and Comet mode is on
HttpSession session = request.getSession(true);
// Track the connection for webapp reload
cometRequests.add(request);
// Track the connection for session expiration
synchronized (session) {
Request[] requests = (Request[])
session.getAttribute(cometRequestsAttribute);
if (requests == null) {
requests = new Request[1];
requests[0] = request;
session.setAttribute(cometRequestsAttribute,
requests);
} else {
Request[] newRequests =
new Request[requests.length + 1];
for (int i = 0; i < requests.length; i++) {
newRequests[i] = requests[i];
}
newRequests[requests.length] = request;
session.setAttribute(cometRequestsAttribute, newRequests);
}
}
}
}
/**
* Use events to update the connection state.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
public void event(Request request, Response response, CometEvent event)
throws IOException, ServletException {
// Perform the request
boolean ok = false;
try {
getNext().event(request, response, event);
ok = true;
} finally {
if (!ok || response.isClosed()
|| (event.getEventType() == CometEvent.EventType.END)
|| (event.getEventType() == CometEvent.EventType.ERROR
&& !(event.getEventSubType() ==
CometEvent.EventSubType.TIMEOUT))) {
// Remove the connection from webapp reload tracking
cometRequests.remove(request);
// Remove connection from session expiration tracking
// Note: can't get the session if it has been invalidated but
// OK since session listener will have done clean-up
HttpSession session = request.getSession(false);
if (session != null) {
synchronized (session) {
Request[] reqs = null;
try {
reqs = (Request[])
session.getAttribute(cometRequestsAttribute);
} catch (IllegalStateException ise) {
// Ignore - session has been invalidated
// Listener will have cleaned up
}
if (reqs != null) {
boolean found = false;
for (int i = 0; !found && (i < reqs.length); i++) {
found = (reqs[i] == request);
}
if (found) {
if (reqs.length > 1) {
Request[] newConnectionInfos =
new Request[reqs.length - 1];
int pos = 0;
for (int i = 0; i < reqs.length; i++) {
if (reqs[i] != request) {
newConnectionInfos[pos++] = reqs[i];
}
}
try {
session.setAttribute(
cometRequestsAttribute,
newConnectionInfos);
} catch (IllegalStateException ise) {
// Ignore - session has been invalidated
// Listener will have cleaned up
}
} else {
try {
session.removeAttribute(
cometRequestsAttribute);
} catch (IllegalStateException ise) {
// Ignore - session has been invalidated
// Listener will have cleaned up
}
}
}
}
}
}
}
}
}
@Override
public void sessionCreated(HttpSessionEvent se) {
// NOOP
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// Close all Comet connections associated with this session
Request[] reqs = (Request[])
se.getSession().getAttribute(cometRequestsAttribute);
if (reqs != null) {
for (int i = 0; i < reqs.length; i++) {
Request req = reqs[i];
try {
CometEventImpl event = req.getEvent();
event.setEventType(CometEvent.EventType.END);
event.setEventSubType(CometEvent.EventSubType.SESSION_END);
((CometProcessor)
req.getWrapper().getServlet()).event(event);
event.close();
} catch (Exception e) {
req.getWrapper().getParent().getLogger().warn(sm.getString(
"cometConnectionManagerValve.listenerEvent"), e);
}
}
}
}
}
|
46,727
|
Bug 46727 DefaultServlet - serving multiple encodings
| null |
resolved fixed
|
f74257e
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-18T13:21:08Z
| 2009-02-17T19:46:40Z
|
java/org/apache/catalina/servlets/DefaultServlet.java
|
/*
* 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.servlets;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.catalina.Globals;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.connector.RequestFacade;
import org.apache.catalina.connector.ResponseFacade;
import org.apache.catalina.util.RequestUtil;
import org.apache.catalina.util.ServerInfo;
import org.apache.catalina.util.URLEncoder;
import org.apache.tomcat.util.res.StringManager;
/**
* <p>The default resource-serving servlet for most web applications,
* used to serve static resources such as HTML pages and images.
* </p>
* <p>
* This servlet is intended to be mapped to <em>/</em> e.g.:
* </p>
* <pre>
* <servlet-mapping>
* <servlet-name>default</servlet-name>
* <url-pattern>/</url-pattern>
* </servlet-mapping>
* </pre>
* <p>It can be mapped to sub-paths, however in all cases resources are served
* from the web appplication resource root using the full path from the root
* of the web application context.
* <br/>e.g. given a web application structure:
*</p>
* <pre>
* /context
* /images
* tomcat2.jpg
* /static
* /images
* tomcat.jpg
* </pre>
* <p>
* ... and a servlet mapping that maps only <code>/static/*</code> to the default servlet:
* </p>
* <pre>
* <servlet-mapping>
* <servlet-name>default</servlet-name>
* <url-pattern>/static/*</url-pattern>
* </servlet-mapping>
* </pre>
* <p>
* Then a request to <code>/context/static/images/tomcat.jpg</code> will succeed
* while a request to <code>/context/images/tomcat2.jpg</code> will fail.
* </p>
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Id$
*/
public class DefaultServlet
extends HttpServlet {
private static final long serialVersionUID = 1L;
// ----------------------------------------------------- Instance Variables
/**
* The debugging detail level for this servlet.
*/
protected int debug = 0;
/**
* The input buffer size to use when serving resources.
*/
protected int input = 2048;
/**
* Should we generate directory listings?
*/
protected boolean listings = false;
/**
* Read only flag. By default, it's set to true.
*/
protected boolean readOnly = true;
/**
* The output buffer size to use when serving resources.
*/
protected int output = 2048;
/**
* Array containing the safe characters set.
*/
protected static final URLEncoder urlEncoder;
/**
* Allow customized directory listing per directory.
*/
protected String localXsltFile = null;
/**
* Allow customized directory listing per context.
*/
protected String contextXsltFile = null;
/**
* Allow customized directory listing per instance.
*/
protected String globalXsltFile = null;
/**
* Allow a readme file to be included.
*/
protected String readmeFile = null;
/**
* The complete set of web application resources
*/
protected transient WebResourceRoot resources = null;
/**
* File encoding to be used when reading static files. If none is specified
* the platform default is used.
*/
protected String fileEncoding = null;
/**
* Minimum size for sendfile usage in bytes.
*/
protected int sendfileSize = 48 * 1024;
/**
* Should the Accept-Ranges: bytes header be send with static resources?
*/
protected boolean useAcceptRanges = true;
/**
* Full range marker.
*/
protected static final ArrayList<Range> FULL = new ArrayList<>();
// ----------------------------------------------------- Static Initializer
/**
* GMT timezone - all HTTP dates are on GMT
*/
static {
urlEncoder = new URLEncoder();
urlEncoder.addSafeCharacter('-');
urlEncoder.addSafeCharacter('_');
urlEncoder.addSafeCharacter('.');
urlEncoder.addSafeCharacter('*');
urlEncoder.addSafeCharacter('/');
}
/**
* MIME multipart separation string
*/
protected static final String mimeSeparation = "CATALINA_MIME_BOUNDARY";
/**
* JNDI resources name.
*/
protected static final String RESOURCES_JNDI_NAME = "java:/comp/Resources";
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Size of file transfer buffer in bytes.
*/
protected static final int BUFFER_SIZE = 4096;
// --------------------------------------------------------- Public Methods
/**
* Finalize this servlet.
*/
@Override
public void destroy() {
// NOOP
}
/**
* Initialize this servlet.
*/
@Override
public void init() throws ServletException {
if (getServletConfig().getInitParameter("debug") != null)
debug = Integer.parseInt(getServletConfig().getInitParameter("debug"));
if (getServletConfig().getInitParameter("input") != null)
input = Integer.parseInt(getServletConfig().getInitParameter("input"));
if (getServletConfig().getInitParameter("output") != null)
output = Integer.parseInt(getServletConfig().getInitParameter("output"));
listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings"));
if (getServletConfig().getInitParameter("readonly") != null)
readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly"));
if (getServletConfig().getInitParameter("sendfileSize") != null)
sendfileSize =
Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024;
fileEncoding = getServletConfig().getInitParameter("fileEncoding");
globalXsltFile = getServletConfig().getInitParameter("globalXsltFile");
contextXsltFile = getServletConfig().getInitParameter("contextXsltFile");
localXsltFile = getServletConfig().getInitParameter("localXsltFile");
readmeFile = getServletConfig().getInitParameter("readmeFile");
if (getServletConfig().getInitParameter("useAcceptRanges") != null)
useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges"));
// Sanity check on the specified buffer sizes
if (input < 256)
input = 256;
if (output < 256)
output = 256;
if (debug > 0) {
log("DefaultServlet.init: input buffer size=" + input +
", output buffer size=" + output);
}
// Load the web resources
resources = (WebResourceRoot) getServletContext().getAttribute(
Globals.RESOURCES_ATTR);
if (resources == null) {
throw new UnavailableException("No resources");
}
}
// ------------------------------------------------------ Protected Methods
/**
* Return the relative path associated with this servlet.
*
* @param request The servlet request we are processing
*/
protected String getRelativePath(HttpServletRequest request) {
// IMPORTANT: DefaultServlet can be mapped to '/' or '/path/*' but always
// serves resources from the web app root with context rooted paths.
// i.e. it can not be used to mount the web app root under a sub-path
// This method must construct a complete context rooted path, although
// subclasses can change this behaviour.
// Are we being processed by a RequestDispatcher.include()?
if (request.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
String result = (String) request.getAttribute(
RequestDispatcher.INCLUDE_PATH_INFO);
if (result == null) {
result = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
} else {
result = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH) + result;
}
if ((result == null) || (result.equals(""))) {
result = "/";
}
return (result);
}
// No, extract the desired path directly from the request
String result = request.getPathInfo();
if (result == null) {
result = request.getServletPath();
} else {
result = request.getServletPath() + result;
}
if ((result == null) || (result.equals(""))) {
result = "/";
}
return (result);
}
/**
* Determines the appropriate path to prepend resources with
* when generating directory listings. Depending on the behaviour of
* {@link #getRelativePath(HttpServletRequest)} this will change.
* @param request the request to determine the path for
* @return the prefix to apply to all resources in the listing.
*/
protected String getPathPrefix(final HttpServletRequest request) {
return request.getContextPath();
}
/**
* Process a GET request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Serve the requested resource, including the data content
serveResource(request, response, true);
}
/**
* Process a HEAD request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doHead(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Serve the requested resource, without the data content
serveResource(request, response, false);
}
/**
* Override default implementation to ensure that TRACE is correctly
* handled.
*
* @param req the {@link HttpServletRequest} object that
* contains the request the client made of
* the servlet
*
* @param resp the {@link HttpServletResponse} object that
* contains the response the servlet returns
* to the client
*
* @exception IOException if an input or output error occurs
* while the servlet is handling the
* OPTIONS request
*
* @exception ServletException if the request for the
* OPTIONS cannot be handled
*/
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
StringBuilder allow = new StringBuilder();
// There is a doGet method
allow.append("GET, HEAD");
// There is a doPost
allow.append(", POST");
// There is a doPut
allow.append(", PUT");
// There is a doDelete
allow.append(", DELETE");
// Trace - assume disabled unless we can prove otherwise
if (req instanceof RequestFacade &&
((RequestFacade) req).getAllowTrace()) {
allow.append(", TRACE");
}
// Always allow options
allow.append(", OPTIONS");
resp.setHeader("Allow", allow.toString());
}
/**
* Process a POST request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
/**
* Process a PUT request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
WebResource resource = resources.getResource(path);
Range range = parseContentRange(req, resp);
InputStream resourceInputStream = null;
try {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
// Assume just one range is specified for now
if (range != null) {
File contentFile = executePartialPut(req, range, path);
resourceInputStream = new FileInputStream(contentFile);
} else {
resourceInputStream = req.getInputStream();
}
if (resources.write(path, resourceInputStream, true)) {
if (resource.exists()) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
}
} else {
resp.sendError(HttpServletResponse.SC_CONFLICT);
}
} finally {
if (resourceInputStream != null) {
try {
resourceInputStream.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
/**
* Handle a partial PUT. New content specified in request is appended to
* existing content in oldRevisionContent (if present). This code does
* not support simultaneous partial updates to the same resource.
*/
protected File executePartialPut(HttpServletRequest req, Range range,
String path)
throws IOException {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
File tempDir = (File) getServletContext().getAttribute
(ServletContext.TEMPDIR);
// Convert all '/' characters to '.' in resourcePath
String convertedResourcePath = path.replace('/', '.');
File contentFile = new File(tempDir, convertedResourcePath);
if (contentFile.createNewFile()) {
// Clean up contentFile when Tomcat is terminated
contentFile.deleteOnExit();
}
RandomAccessFile randAccessContentFile =
new RandomAccessFile(contentFile, "rw");
WebResource oldResource = resources.getResource(path);
// Copy data in oldRevisionContent to contentFile
if (oldResource.isFile()) {
BufferedInputStream bufOldRevStream =
new BufferedInputStream(oldResource.getInputStream(),
BUFFER_SIZE);
int numBytesRead;
byte[] copyBuffer = new byte[BUFFER_SIZE];
while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) {
randAccessContentFile.write(copyBuffer, 0, numBytesRead);
}
bufOldRevStream.close();
}
randAccessContentFile.setLength(range.length);
// Append data in request input stream to contentFile
randAccessContentFile.seek(range.start);
int numBytesRead;
byte[] transferBuffer = new byte[BUFFER_SIZE];
BufferedInputStream requestBufInStream =
new BufferedInputStream(req.getInputStream(), BUFFER_SIZE);
while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
randAccessContentFile.write(transferBuffer, 0, numBytesRead);
}
randAccessContentFile.close();
requestBufInStream.close();
return contentFile;
}
/**
* Process a DELETE request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
WebResource resource = resources.getResource(path);
if (resource.exists()) {
if (resource.delete()) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
} else {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Check if the conditions specified in the optional If headers are
* satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets all the specified conditions,
* and false if any of the conditions is not satisfied, in which case
* request processing is stopped
*/
protected boolean checkIfHeaders(HttpServletRequest request,
HttpServletResponse response,
WebResource resource)
throws IOException {
return checkIfMatch(request, response, resource)
&& checkIfModifiedSince(request, response, resource)
&& checkIfNoneMatch(request, response, resource)
&& checkIfUnmodifiedSince(request, response, resource);
}
/**
* URL rewriter.
*
* @param path Path which has to be rewritten
*/
protected String rewriteUrl(String path) {
return urlEncoder.encode( path );
}
/**
* Serve the specified resource, optionally including the data content.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param content Should the content be included?
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
protected void serveResource(HttpServletRequest request,
HttpServletResponse response,
boolean content)
throws IOException, ServletException {
boolean serveContent = content;
// Identify the requested resource path
String path = getRelativePath(request);
if (debug > 0) {
if (serveContent)
log("DefaultServlet.serveResource: Serving resource '" +
path + "' headers and data");
else
log("DefaultServlet.serveResource: Serving resource '" +
path + "' headers only");
}
WebResource resource = resources.getResource(path);
if (!resource.exists()) {
// Check if we're included so we can return the appropriate
// missing resource name in the error
String requestUri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI);
if (requestUri == null) {
requestUri = request.getRequestURI();
} else {
// We're included
// SRV.9.3 says we must throw a FNFE
throw new FileNotFoundException(
sm.getString("defaultServlet.missingResource",
requestUri));
}
response.sendError(HttpServletResponse.SC_NOT_FOUND,
requestUri);
return;
}
// If the resource is not a collection, and the resource path
// ends with "/" or "\", return NOT FOUND
if (resource.isFile()) {
if (path.endsWith("/") || (path.endsWith("\\"))) {
// Check if we're included so we can return the appropriate
// missing resource name in the error
String requestUri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI);
if (requestUri == null) {
requestUri = request.getRequestURI();
}
response.sendError(HttpServletResponse.SC_NOT_FOUND,
requestUri);
return;
}
}
boolean isError =
response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
// Check if the conditions specified in the optional If headers are
// satisfied.
if (resource.isFile()) {
// Checking If headers
boolean included = (request.getAttribute(
RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
if (!included && !isError &&
!checkIfHeaders(request, response, resource)) {
return;
}
}
// Find content type.
String contentType = resource.getMimeType();
if (contentType == null) {
contentType = getServletContext().getMimeType(resource.getName());
resource.setMimeType(contentType);
}
ArrayList<Range> ranges = null;
long contentLength = -1L;
if (resource.isDirectory()) {
// Skip directory listings if we have been configured to
// suppress them
if (!listings) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
request.getRequestURI());
return;
}
contentType = "text/html;charset=UTF-8";
} else {
if (!isError) {
if (useAcceptRanges) {
// Accept ranges header
response.setHeader("Accept-Ranges", "bytes");
}
// Parse range specifier
ranges = parseRange(request, response, resource);
// ETag header
response.setHeader("ETag", resource.getETag());
// Last-Modified header
response.setHeader("Last-Modified",
resource.getLastModifiedHttp());
}
// Get content length
contentLength = resource.getContentLength();
// Special case for zero length files, which would cause a
// (silent) ISE when setting the output buffer size
if (contentLength == 0L) {
serveContent = false;
}
}
ServletOutputStream ostream = null;
PrintWriter writer = null;
if (serveContent) {
// Trying to retrieve the servlet output stream
try {
ostream = response.getOutputStream();
} catch (IllegalStateException e) {
// If it fails, we try to get a Writer instead if we're
// trying to serve a text file
if ( (contentType == null)
|| (contentType.startsWith("text"))
|| (contentType.endsWith("xml"))
|| (contentType.contains("/javascript")) ) {
writer = response.getWriter();
// Cannot reliably serve partial content with a Writer
ranges = FULL;
} else {
throw e;
}
}
}
// Check to see if a Filter, Valve of wrapper has written some content.
// If it has, disable range requests and setting of a content length
// since neither can be done reliably.
ServletResponse r = response;
long contentWritten = 0;
while (r instanceof ServletResponseWrapper) {
r = ((ServletResponseWrapper) r).getResponse();
}
if (r instanceof ResponseFacade) {
contentWritten = ((ResponseFacade) r).getContentWritten();
}
if (contentWritten > 0) {
ranges = FULL;
}
if (resource.isDirectory() ||
isError ||
( (ranges == null || ranges.isEmpty())
&& request.getHeader("Range") == null ) ||
ranges == FULL ) {
// Set the appropriate output headers
if (contentType != null) {
if (debug > 0)
log("DefaultServlet.serveFile: contentType='" +
contentType + "'");
response.setContentType(contentType);
}
if (resource.isFile() && contentLength >= 0 &&
(!serveContent || ostream != null)) {
if (debug > 0)
log("DefaultServlet.serveFile: contentLength=" +
contentLength);
// Don't set a content length if something else has already
// written to the response.
if (contentWritten == 0) {
response.setContentLengthLong(contentLength);
}
}
InputStream renderResult = null;
if (resource.isDirectory()) {
if (serveContent) {
// Serve the directory browser
renderResult = render(getPathPrefix(request), resource);
}
}
// Copy the input stream to our output stream (if requested)
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
if (!checkSendfile(request, response, resource,
contentLength, null))
copy(resource, renderResult, ostream);
} else {
copy(resource, renderResult, writer);
}
}
} else {
if ((ranges == null) || (ranges.isEmpty()))
return;
// Partial content response.
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (ranges.size() == 1) {
Range range = ranges.get(0);
response.addHeader("Content-Range", "bytes "
+ range.start
+ "-" + range.end + "/"
+ range.length);
long length = range.end - range.start + 1;
response.setContentLengthLong(length);
if (contentType != null) {
if (debug > 0)
log("DefaultServlet.serveFile: contentType='" +
contentType + "'");
response.setContentType(contentType);
}
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
if (!checkSendfile(request, response, resource,
range.end - range.start + 1, range))
copy(resource, ostream, range);
} else {
// we should not get here
throw new IllegalStateException();
}
}
} else {
response.setContentType("multipart/byteranges; boundary="
+ mimeSeparation);
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
copy(resource, ostream, ranges.iterator(),
contentType);
} else {
// we should not get here
throw new IllegalStateException();
}
}
}
}
}
/**
* Parse the content-range header.
*
* @param request The servlet request we a)re processing
* @param response The servlet response we are creating
* @return Range
*/
protected Range parseContentRange(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
// Retrieving the content-range header (if any is specified
String rangeHeader = request.getHeader("Content-Range");
if (rangeHeader == null)
return null;
// bytes is the only range unit supported
if (!rangeHeader.startsWith("bytes")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
rangeHeader = rangeHeader.substring(6).trim();
int dashPos = rangeHeader.indexOf('-');
int slashPos = rangeHeader.indexOf('/');
if (dashPos == -1) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
if (slashPos == -1) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
Range range = new Range();
try {
range.start = Long.parseLong(rangeHeader.substring(0, dashPos));
range.end =
Long.parseLong(rangeHeader.substring(dashPos + 1, slashPos));
range.length = Long.parseLong
(rangeHeader.substring(slashPos + 1, rangeHeader.length()));
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
if (!range.validate()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
return range;
}
/**
* Parse the range header.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return Vector of ranges
*/
protected ArrayList<Range> parseRange(HttpServletRequest request,
HttpServletResponse response,
WebResource resource) throws IOException {
// Checking If-Range
String headerValue = request.getHeader("If-Range");
if (headerValue != null) {
long headerValueTime = (-1L);
try {
headerValueTime = request.getDateHeader("If-Range");
} catch (IllegalArgumentException e) {
// Ignore
}
String eTag = resource.getETag();
long lastModified = resource.getLastModified();
if (headerValueTime == (-1L)) {
// If the ETag the client gave does not match the entity
// etag, then the entire entity is returned.
if (!eTag.equals(headerValue.trim()))
return FULL;
} else {
// If the timestamp of the entity the client got is older than
// the last modification date of the entity, the entire entity
// is returned.
if (lastModified > (headerValueTime + 1000))
return FULL;
}
}
long fileLength = resource.getContentLength();
if (fileLength == 0)
return null;
// Retrieving the range header (if any is specified
String rangeHeader = request.getHeader("Range");
if (rangeHeader == null)
return null;
// bytes is the only range unit supported (and I don't see the point
// of adding new ones).
if (!rangeHeader.startsWith("bytes")) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
rangeHeader = rangeHeader.substring(6);
// Vector which will contain all the ranges which are successfully
// parsed.
ArrayList<Range> result = new ArrayList<>();
StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ",");
// Parsing the range list
while (commaTokenizer.hasMoreTokens()) {
String rangeDefinition = commaTokenizer.nextToken().trim();
Range currentRange = new Range();
currentRange.length = fileLength;
int dashPos = rangeDefinition.indexOf('-');
if (dashPos == -1) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
if (dashPos == 0) {
try {
long offset = Long.parseLong(rangeDefinition);
currentRange.start = fileLength + offset;
currentRange.end = fileLength - 1;
} catch (NumberFormatException e) {
response.addHeader("Content-Range",
"bytes */" + fileLength);
response.sendError
(HttpServletResponse
.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
} else {
try {
currentRange.start = Long.parseLong
(rangeDefinition.substring(0, dashPos));
if (dashPos < rangeDefinition.length() - 1)
currentRange.end = Long.parseLong
(rangeDefinition.substring
(dashPos + 1, rangeDefinition.length()));
else
currentRange.end = fileLength - 1;
} catch (NumberFormatException e) {
response.addHeader("Content-Range",
"bytes */" + fileLength);
response.sendError
(HttpServletResponse
.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
}
if (!currentRange.validate()) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
result.add(currentRange);
}
return result;
}
/**
* Decide which way to render. HTML or XML.
*/
protected InputStream render(String contextPath, WebResource resource)
throws IOException, ServletException {
InputStream xsltInputStream =
findXsltInputStream(resource);
if (xsltInputStream==null) {
return renderHtml(contextPath, resource);
}
return renderXml(contextPath, resource, xsltInputStream);
}
/**
* Return an InputStream to an HTML representation of the contents
* of this directory.
*
* @param contextPath Context path to which our internal paths are
* relative
*/
protected InputStream renderXml(String contextPath,
WebResource resource,
InputStream xsltInputStream)
throws IOException, ServletException {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<listing ");
sb.append(" contextPath='");
sb.append(contextPath);
sb.append("'");
sb.append(" directory='");
sb.append(resource.getName());
sb.append("' ");
sb.append(" hasParent='").append(!resource.getName().equals("/"));
sb.append("'>");
sb.append("<entries>");
String[] entries = resources.list(resource.getWebappPath());
// rewriteUrl(contextPath) is expensive. cache result for later reuse
String rewrittenContextPath = rewriteUrl(contextPath);
String directoryWebappPath = resource.getWebappPath();
for (String entry : entries) {
if (entry.equalsIgnoreCase("WEB-INF") ||
entry.equalsIgnoreCase("META-INF") ||
entry.equalsIgnoreCase(localXsltFile))
continue;
if ((directoryWebappPath + entry).equals(contextXsltFile))
continue;
WebResource childResource =
resources.getResource(directoryWebappPath + entry);
if (!childResource.exists()) {
continue;
}
sb.append("<entry");
sb.append(" type='")
.append(childResource.isDirectory()?"dir":"file")
.append("'");
sb.append(" urlPath='")
.append(rewrittenContextPath)
.append(rewriteUrl(directoryWebappPath + entry))
.append(childResource.isDirectory()?"/":"")
.append("'");
if (childResource.isFile()) {
sb.append(" size='")
.append(renderSize(childResource.getContentLength()))
.append("'");
}
sb.append(" date='")
.append(childResource.getLastModifiedHttp())
.append("'");
sb.append(">");
sb.append(RequestUtil.filter(entry));
if (childResource.isDirectory())
sb.append("/");
sb.append("</entry>");
}
sb.append("</entries>");
String readme = getReadme(resource);
if (readme!=null) {
sb.append("<readme><![CDATA[");
sb.append(readme);
sb.append("]]></readme>");
}
sb.append("</listing>");
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xmlSource = new StreamSource(new StringReader(sb.toString()));
Source xslSource = new StreamSource(xsltInputStream);
Transformer transformer = tFactory.newTransformer(xslSource);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
StreamResult out = new StreamResult(osWriter);
transformer.transform(xmlSource, out);
osWriter.flush();
return (new ByteArrayInputStream(stream.toByteArray()));
} catch (TransformerException e) {
throw new ServletException("XSL transformer error", e);
}
}
/**
* Return an InputStream to an HTML representation of the contents
* of this directory.
*
* @param contextPath Context path to which our internal paths are
* relative
*/
protected InputStream renderHtml(String contextPath, WebResource resource)
throws IOException {
String name = resource.getName();
// Prepare a writer to a buffered area
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
PrintWriter writer = new PrintWriter(osWriter);
StringBuilder sb = new StringBuilder();
String[] entries = resources.list(resource.getWebappPath());
// rewriteUrl(contextPath) is expensive. cache result for later reuse
String rewrittenContextPath = rewriteUrl(contextPath);
String directoryWebappPath = resource.getWebappPath();
// Render the page header
sb.append("<html>\r\n");
sb.append("<head>\r\n");
sb.append("<title>");
sb.append(sm.getString("directory.title", name));
sb.append("</title>\r\n");
sb.append("<STYLE><!--");
sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS);
sb.append("--></STYLE> ");
sb.append("</head>\r\n");
sb.append("<body>");
sb.append("<h1>");
sb.append(sm.getString("directory.title", name));
// Render the link to our parent (if required)
String parentDirectory = name;
if (parentDirectory.endsWith("/")) {
parentDirectory =
parentDirectory.substring(0, parentDirectory.length() - 1);
}
int slash = parentDirectory.lastIndexOf('/');
if (slash >= 0) {
String parent = name.substring(0, slash);
sb.append(" - <a href=\"");
sb.append(rewrittenContextPath);
if (parent.equals(""))
parent = "/";
sb.append(rewriteUrl(parent));
if (!parent.endsWith("/"))
sb.append("/");
sb.append("\">");
sb.append("<b>");
sb.append(sm.getString("directory.parent", parent));
sb.append("</b>");
sb.append("</a>");
}
sb.append("</h1>");
sb.append("<HR size=\"1\" noshade=\"noshade\">");
sb.append("<table width=\"100%\" cellspacing=\"0\"" +
" cellpadding=\"5\" align=\"center\">\r\n");
// Render the column headings
sb.append("<tr>\r\n");
sb.append("<td align=\"left\"><font size=\"+1\"><strong>");
sb.append(sm.getString("directory.filename"));
sb.append("</strong></font></td>\r\n");
sb.append("<td align=\"center\"><font size=\"+1\"><strong>");
sb.append(sm.getString("directory.size"));
sb.append("</strong></font></td>\r\n");
sb.append("<td align=\"right\"><font size=\"+1\"><strong>");
sb.append(sm.getString("directory.lastModified"));
sb.append("</strong></font></td>\r\n");
sb.append("</tr>");
boolean shade = false;
for (String entry : entries) {
if (entry.equalsIgnoreCase("WEB-INF") ||
entry.equalsIgnoreCase("META-INF"))
continue;
WebResource childResource =
resources.getResource(directoryWebappPath + entry);
if (!childResource.exists()) {
continue;
}
sb.append("<tr");
if (shade)
sb.append(" bgcolor=\"#eeeeee\"");
sb.append(">\r\n");
shade = !shade;
sb.append("<td align=\"left\"> \r\n");
sb.append("<a href=\"");
sb.append(rewrittenContextPath);
sb.append(rewriteUrl(directoryWebappPath + entry));
if (childResource.isDirectory())
sb.append("/");
sb.append("\"><tt>");
sb.append(RequestUtil.filter(entry));
if (childResource.isDirectory())
sb.append("/");
sb.append("</tt></a></td>\r\n");
sb.append("<td align=\"right\"><tt>");
if (childResource.isDirectory())
sb.append(" ");
else
sb.append(renderSize(childResource.getContentLength()));
sb.append("</tt></td>\r\n");
sb.append("<td align=\"right\"><tt>");
sb.append(childResource.getLastModifiedHttp());
sb.append("</tt></td>\r\n");
sb.append("</tr>\r\n");
}
// Render the page footer
sb.append("</table>\r\n");
sb.append("<HR size=\"1\" noshade=\"noshade\">");
String readme = getReadme(resource);
if (readme!=null) {
sb.append(readme);
sb.append("<HR size=\"1\" noshade=\"noshade\">");
}
sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");
sb.append("</body>\r\n");
sb.append("</html>\r\n");
// Return an input stream to the underlying bytes
writer.write(sb.toString());
writer.flush();
return (new ByteArrayInputStream(stream.toByteArray()));
}
/**
* Render the specified file size (in bytes).
*
* @param size File size (in bytes)
*/
protected String renderSize(long size) {
long leftSide = size / 1024;
long rightSide = (size % 1024) / 103; // Makes 1 digit
if ((leftSide == 0) && (rightSide == 0) && (size > 0))
rightSide = 1;
return ("" + leftSide + "." + rightSide + " kb");
}
/**
* Get the readme file as a string.
*/
protected String getReadme(WebResource directory) {
if (readmeFile != null) {
WebResource resource = resources.getResource(
directory.getWebappPath() + readmeFile);
if (resource.isFile()) {
StringWriter buffer = new StringWriter();
InputStream is = resource.getInputStream();
copyRange(new InputStreamReader(is),
new PrintWriter(buffer));
return buffer.toString();
} else {
if (debug > 10)
log("readme '" + readmeFile + "' not found");
return null;
}
}
return null;
}
/**
* Return the xsl template inputstream (if possible)
*/
protected InputStream findXsltInputStream(WebResource directory)
throws IOException {
if (localXsltFile != null) {
WebResource resource = resources.getResource(
directory.getWebappPath() + localXsltFile);
if (resource.isFile()) {
InputStream is = resource.getInputStream();
if (is != null) {
return is;
}
}
if (debug > 10) {
log("localXsltFile '" + localXsltFile + "' not found");
}
}
if (contextXsltFile != null) {
InputStream is =
getServletContext().getResourceAsStream(contextXsltFile);
if (is != null)
return is;
if (debug > 10)
log("contextXsltFile '" + contextXsltFile + "' not found");
}
/* Open and read in file in one fell swoop to reduce chance
* chance of leaving handle open.
*/
if (globalXsltFile!=null) {
FileInputStream fis = null;
try {
File f = new File(globalXsltFile);
if (f.exists()){
fis =new FileInputStream(f);
byte b[] = new byte[(int)f.length()]; /* danger! */
fis.read(b);
return new ByteArrayInputStream(b);
}
} finally {
if (fis!=null)
fis.close();
}
}
return null;
}
// -------------------------------------------------------- protected Methods
/**
* Check if sendfile can be used.
*/
protected boolean checkSendfile(HttpServletRequest request,
HttpServletResponse response,
WebResource resource,
long length, Range range) {
if (sendfileSize > 0
&& resource.isFile()
&& length > sendfileSize
&& (resource.getCanonicalPath() != null)
&& (Boolean.TRUE == request.getAttribute(Globals.SENDFILE_SUPPORTED_ATTR))
&& (request.getClass().getName().equals("org.apache.catalina.connector.RequestFacade"))
&& (response.getClass().getName().equals("org.apache.catalina.connector.ResponseFacade"))) {
request.setAttribute(Globals.SENDFILE_FILENAME_ATTR, resource.getCanonicalPath());
if (range == null) {
request.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(0L));
request.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(length));
} else {
request.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(range.start));
request.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(range.end + 1));
}
return true;
}
return false;
}
/**
* Check if the if-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfMatch(HttpServletRequest request,
HttpServletResponse response, WebResource resource)
throws IOException {
String eTag = resource.getETag();
String headerValue = request.getHeader("If-Match");
if (headerValue != null) {
if (headerValue.indexOf('*') == -1) {
StringTokenizer commaTokenizer = new StringTokenizer
(headerValue, ",");
boolean conditionSatisfied = false;
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
// If none of the given ETags match, 412 Precodition failed is
// sent back
if (!conditionSatisfied) {
response.sendError
(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
}
return true;
}
/**
* Check if the if-modified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfModifiedSince(HttpServletRequest request,
HttpServletResponse response, WebResource resource) {
try {
long headerValue = request.getDateHeader("If-Modified-Since");
long lastModified = resource.getLastModified();
if (headerValue != -1) {
// If an If-None-Match header has been specified, if modified since
// is ignored.
if ((request.getHeader("If-None-Match") == null)
&& (lastModified < headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", resource.getETag());
return false;
}
}
} catch (IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Check if the if-none-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfNoneMatch(HttpServletRequest request,
HttpServletResponse response, WebResource resource)
throws IOException {
String eTag = resource.getETag();
String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!headerValue.equals("*")) {
StringTokenizer commaTokenizer =
new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
// For GET and HEAD, we should respond with
// 304 Not Modified.
// For every other method, 412 Precondition Failed is sent
// back.
if ( ("GET".equals(request.getMethod()))
|| ("HEAD".equals(request.getMethod())) ) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", eTag);
return false;
}
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
return true;
}
/**
* Check if the if-unmodified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfUnmodifiedSince(HttpServletRequest request,
HttpServletResponse response, WebResource resource)
throws IOException {
try {
long lastModified = resource.getLastModified();
long headerValue = request.getDateHeader("If-Unmodified-Since");
if (headerValue != -1) {
if ( lastModified >= (headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
} catch(IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param is The input stream to read the source resource from
* @param ostream The output stream to write to
*
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, InputStream is,
ServletOutputStream ostream)
throws IOException {
IOException exception = null;
InputStream resourceInputStream = null;
// Optimization: If the binary content has already been loaded, send
// it directly
if (resource.isFile()) {
byte buffer[] = resource.getContent();
if (buffer != null) {
ostream.write(buffer, 0, buffer.length);
return;
}
resourceInputStream = resource.getInputStream();
} else {
resourceInputStream = is;
}
InputStream istream = new BufferedInputStream
(resourceInputStream, input);
// Copy the input stream to the output stream
exception = copyRange(istream, ostream);
// Clean up the input stream
istream.close();
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param is The input stream to read the source resource from
* @param writer The writer to write to
*
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, InputStream is, PrintWriter writer)
throws IOException {
IOException exception = null;
InputStream resourceInputStream = null;
if (resource.isFile()) {
resourceInputStream = resource.getInputStream();
} else {
resourceInputStream = is;
}
Reader reader;
if (fileEncoding == null) {
reader = new InputStreamReader(resourceInputStream);
} else {
reader = new InputStreamReader(resourceInputStream,
fileEncoding);
}
// Copy the input stream to the output stream
exception = copyRange(reader, writer);
// Clean up the reader
reader.close();
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param ostream The output stream to write to
* @param range Range the client wanted to retrieve
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, ServletOutputStream ostream,
Range range)
throws IOException {
IOException exception = null;
InputStream resourceInputStream = resource.getInputStream();
InputStream istream =
new BufferedInputStream(resourceInputStream, input);
exception = copyRange(istream, ostream, range.start, range.end);
// Clean up the input stream
istream.close();
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param ostream The output stream to write to
* @param ranges Enumeration of the ranges the client wanted to
* retrieve
* @param contentType Content type of the resource
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, ServletOutputStream ostream,
Iterator<Range> ranges, String contentType)
throws IOException {
IOException exception = null;
while ( (exception == null) && (ranges.hasNext()) ) {
InputStream resourceInputStream = resource.getInputStream();
InputStream istream =
new BufferedInputStream(resourceInputStream, input);
Range currentRange = ranges.next();
// Writing MIME header.
ostream.println();
ostream.println("--" + mimeSeparation);
if (contentType != null)
ostream.println("Content-Type: " + contentType);
ostream.println("Content-Range: bytes " + currentRange.start
+ "-" + currentRange.end + "/"
+ currentRange.length);
ostream.println();
// Printing content
exception = copyRange(istream, ostream, currentRange.start,
currentRange.end);
istream.close();
}
ostream.println();
ostream.print("--" + mimeSeparation + "--");
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param istream The input stream to read from
* @param ostream The output stream to write to
* @return Exception which occurred during processing
*/
protected IOException copyRange(InputStream istream,
ServletOutputStream ostream) {
// Copy the input stream to the output stream
IOException exception = null;
byte buffer[] = new byte[input];
int len = buffer.length;
while (true) {
try {
len = istream.read(buffer);
if (len == -1)
break;
ostream.write(buffer, 0, len);
} catch (IOException e) {
exception = e;
len = -1;
break;
}
}
return exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param reader The reader to read from
* @param writer The writer to write to
* @return Exception which occurred during processing
*/
protected IOException copyRange(Reader reader, PrintWriter writer) {
// Copy the input stream to the output stream
IOException exception = null;
char buffer[] = new char[input];
int len = buffer.length;
while (true) {
try {
len = reader.read(buffer);
if (len == -1)
break;
writer.write(buffer, 0, len);
} catch (IOException e) {
exception = e;
len = -1;
break;
}
}
return exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param istream The input stream to read from
* @param ostream The output stream to write to
* @param start Start of the range which will be copied
* @param end End of the range which will be copied
* @return Exception which occurred during processing
*/
protected IOException copyRange(InputStream istream,
ServletOutputStream ostream,
long start, long end) {
if (debug > 10)
log("Serving bytes:" + start + "-" + end);
long skipped = 0;
try {
skipped = istream.skip(start);
} catch (IOException e) {
return e;
}
if (skipped < start) {
return new IOException(sm.getString("defaultservlet.skipfail",
Long.valueOf(skipped), Long.valueOf(start)));
}
IOException exception = null;
long bytesToRead = end - start + 1;
byte buffer[] = new byte[input];
int len = buffer.length;
while ( (bytesToRead > 0) && (len >= buffer.length)) {
try {
len = istream.read(buffer);
if (bytesToRead >= len) {
ostream.write(buffer, 0, len);
bytesToRead -= len;
} else {
ostream.write(buffer, 0, (int) bytesToRead);
bytesToRead = 0;
}
} catch (IOException e) {
exception = e;
len = -1;
}
if (len < buffer.length)
break;
}
return exception;
}
// ------------------------------------------------------ Range Inner Class
protected static class Range {
public long start;
public long end;
public long length;
/**
* Validate range.
*/
public boolean validate() {
if (end >= length)
end = length - 1;
return (start >= 0) && (end >= 0) && (start <= end) && (length > 0);
}
}
}
|
55,570
|
Bug 55570 SpnegoAuthenticator: Resource file is missing placeholders for exceptions.
|
In java/org/apache/catalina/authenticator/SpnegoAuthenticator.java problems are logged with an exception. The exception does not show up in the logging. The exception only shows up if I hack java/org/apache/catalina/authenticator/LocalStrings.properties in catalina.jar, and add a placeholder. REPRODUCE: - Configure SP-NEGO with Kerberos. - Mess up your principal in com.sun.security.jgss.krb5.accept in jaas.config. - Try to login. - See that you get something like: FINE [org.apache.catalina.authenticator.SpnegoAuthenticator authenticate] Failed to validate client supplied ticket FIX: In java/org/apache/catalina/authenticator/LocalStrings.properties please add [{0}] to the following lines: spnegoAuthenticator.ticketValidateFail=Failed to validate client supplied ticket spnegoAuthenticator.serviceLoginFail=Unable to login as the service principal In SpnegoAuthenticator.java you can verify that exceptions are indeed passed to the log. VALIDATE: - Reproduce again - See that you now get Failed to validate client supplied ticket [GSSException: Failure unspecified at GSS-API level (Mechanism level: Invalid argument (400) - Cannot find key of appropriate type to decrypt AP REP - RC4 with HMAC)] The exception is not super-helpful, but at least it's something.
|
resolved fixed
|
910d4d9
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-19T14:50:06Z
| 2013-09-19T17:00:00Z
|
java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
|
/*
* 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.authenticator;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.regex.Pattern;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Request;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.codec.binary.Base64;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.Oid;
/**
* A SPNEGO authenticator that uses the SPENGO/Kerberos support built in to Java
* 6. Successful Kerberos authentication depends on the correct configuration of
* multiple components. If the configuration is invalid, the error messages are
* often cryptic although a Google search will usually point you in the right
* direction.
*/
public class SpnegoAuthenticator extends AuthenticatorBase {
private static final Log log = LogFactory.getLog(SpnegoAuthenticator.class);
private String loginConfigName = Constants.DEFAULT_LOGIN_MODULE_NAME;
public String getLoginConfigName() {
return loginConfigName;
}
public void setLoginConfigName(String loginConfigName) {
this.loginConfigName = loginConfigName;
}
private boolean storeDelegatedCredential = true;
public boolean isStoreDelegatedCredential() {
return storeDelegatedCredential;
}
public void setStoreDelegatedCredential(
boolean storeDelegatedCredential) {
this.storeDelegatedCredential = storeDelegatedCredential;
}
private Pattern noKeepAliveUserAgents = null;
public String getNoKeepAliveUserAgents() {
Pattern p = noKeepAliveUserAgents;
if (p == null) {
return null;
} else {
return p.pattern();
}
}
public void setNoKeepAliveUserAgents(String noKeepAliveUserAgents) {
if (noKeepAliveUserAgents == null ||
noKeepAliveUserAgents.length() == 0) {
this.noKeepAliveUserAgents = null;
} else {
this.noKeepAliveUserAgents = Pattern.compile(noKeepAliveUserAgents);
}
}
@Override
protected String getAuthMethod() {
return Constants.SPNEGO_METHOD;
}
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
// Kerberos configuration file location
String krb5Conf = System.getProperty(Constants.KRB5_CONF_PROPERTY);
if (krb5Conf == null) {
// System property not set, use the Tomcat default
File krb5ConfFile = new File(container.getCatalinaBase(),
Constants.DEFAULT_KRB5_CONF);
System.setProperty(Constants.KRB5_CONF_PROPERTY,
krb5ConfFile.getAbsolutePath());
}
// JAAS configuration file location
String jaasConf = System.getProperty(Constants.JAAS_CONF_PROPERTY);
if (jaasConf == null) {
// System property not set, use the Tomcat default
File jaasConfFile = new File(container.getCatalinaBase(),
Constants.DEFAULT_JAAS_CONF);
System.setProperty(Constants.JAAS_CONF_PROPERTY,
jaasConfFile.getAbsolutePath());
}
// This property must be false for SPNEGO to work
System.setProperty(Constants.USE_SUBJECT_CREDS_ONLY_PROPERTY, "false");
}
@Override
public boolean authenticate(Request request, HttpServletResponse response)
throws IOException {
// Have we already authenticated someone?
Principal principal = request.getUserPrincipal();
String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
if (principal != null) {
if (log.isDebugEnabled()) {
log.debug("Already authenticated '" + principal.getName() + "'");
}
// Associate the session with any existing SSO session
if (ssoId != null) {
associate(ssoId, request.getSessionInternal(true));
}
return true;
}
// Is there an SSO session against which we can try to reauthenticate?
if (ssoId != null) {
if (log.isDebugEnabled()) {
log.debug("SSO Id " + ssoId + " set; attempting " +
"reauthentication");
}
/* Try to reauthenticate using data cached by SSO. If this fails,
either the original SSO logon was of DIGEST or SSL (which
we can't reauthenticate ourselves because there is no
cached username and password), or the realm denied
the user's reauthentication for some reason.
In either case we have to prompt the user for a logon */
if (reauthenticateFromSSO(ssoId, request)) {
return true;
}
}
MessageBytes authorization =
request.getCoyoteRequest().getMimeHeaders()
.getValue("authorization");
if (authorization == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.noAuthHeader"));
}
response.setHeader("WWW-Authenticate", "Negotiate");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
authorization.toBytes();
ByteChunk authorizationBC = authorization.getByteChunk();
if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"spnegoAuthenticator.authHeaderNotNego"));
}
response.setHeader("WWW-Authenticate", "Negotiate");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
authorizationBC.setOffset(authorizationBC.getOffset() + 10);
byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(),
authorizationBC.getOffset(),
authorizationBC.getLength());
if (decoded.length == 0) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"spnegoAuthenticator.authHeaderNoToken"));
}
response.setHeader("WWW-Authenticate", "Negotiate");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
LoginContext lc = null;
GSSContext gssContext = null;
byte[] outToken = null;
try {
try {
lc = new LoginContext(getLoginConfigName());
lc.login();
} catch (LoginException e) {
log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"),
e);
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return false;
}
// Assume the GSSContext is stateless
// TODO: Confirm this assumption
final GSSManager manager = GSSManager.getInstance();
final PrivilegedExceptionAction<GSSCredential> action =
new PrivilegedExceptionAction<GSSCredential>() {
@Override
public GSSCredential run() throws GSSException {
return manager.createCredential(null,
GSSCredential.DEFAULT_LIFETIME,
new Oid("1.3.6.1.5.5.2"),
GSSCredential.ACCEPT_ONLY);
}
};
gssContext = manager.createContext(Subject.doAs(lc.getSubject(), action));
outToken = gssContext.acceptSecContext(decoded, 0, decoded.length);
if (outToken == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"spnegoAuthenticator.ticketValidateFail"));
}
// Start again
response.setHeader("WWW-Authenticate", "Negotiate");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
principal = context.getRealm().authenticate(gssContext,
isStoreDelegatedCredential());
} catch (GSSException e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail",
e));
}
response.setHeader("WWW-Authenticate", "Negotiate");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
} catch (PrivilegedActionException e) {
log.error(sm.getString("spnegoAuthenticator.serviceLoginFail", e));
response.setHeader("WWW-Authenticate", "Negotiate");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
} finally {
if (gssContext != null) {
try {
gssContext.dispose();
} catch (GSSException e) {
// Ignore
}
}
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
// Ignore
}
}
}
// Send response token on success and failure
response.setHeader("WWW-Authenticate", "Negotiate "
+ Base64.encodeBase64String(outToken));
if (principal != null) {
register(request, response, principal, Constants.SPNEGO_METHOD,
principal.getName(), null);
Pattern p = noKeepAliveUserAgents;
if (p != null) {
MessageBytes ua =
request.getCoyoteRequest().getMimeHeaders().getValue(
"user-agent");
if (ua != null && p.matcher(ua.toString()).matches()) {
response.setHeader("Connection", "close");
}
}
return true;
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
|
55,582
|
Bug 55582 Concurrent issue of TagFileProcessor
| null |
resolved fixed
|
f627cc8
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-23T13:54:31Z
| 2013-09-22T14:26:40Z
|
java/org/apache/jasper/compiler/TagFileProcessor.java
|
/*
* 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.jasper.compiler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Vector;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagFileInfo;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import javax.servlet.jsp.tagext.TagVariableInfo;
import javax.servlet.jsp.tagext.VariableInfo;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
import org.apache.jasper.runtime.JspSourceDependent;
import org.apache.jasper.servlet.JspServletWrapper;
/**
* 1. Processes and extracts the directive info in a tag file. 2. Compiles and
* loads tag files used in a JSP file.
*
* @author Kin-man Chung
*/
class TagFileProcessor {
private Vector<Compiler> tempVector;
/**
* A visitor the tag file
*/
private static class TagFileDirectiveVisitor extends Node.Visitor {
private static final JspUtil.ValidAttribute[] tagDirectiveAttrs = {
new JspUtil.ValidAttribute("display-name"),
new JspUtil.ValidAttribute("body-content"),
new JspUtil.ValidAttribute("dynamic-attributes"),
new JspUtil.ValidAttribute("small-icon"),
new JspUtil.ValidAttribute("large-icon"),
new JspUtil.ValidAttribute("description"),
new JspUtil.ValidAttribute("example"),
new JspUtil.ValidAttribute("pageEncoding"),
new JspUtil.ValidAttribute("language"),
new JspUtil.ValidAttribute("import"),
new JspUtil.ValidAttribute("deferredSyntaxAllowedAsLiteral"), // JSP 2.1
new JspUtil.ValidAttribute("trimDirectiveWhitespaces"), // JSP 2.1
new JspUtil.ValidAttribute("isELIgnored") };
private static final JspUtil.ValidAttribute[] attributeDirectiveAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("required"),
new JspUtil.ValidAttribute("fragment"),
new JspUtil.ValidAttribute("rtexprvalue"),
new JspUtil.ValidAttribute("type"),
new JspUtil.ValidAttribute("deferredValue"), // JSP 2.1
new JspUtil.ValidAttribute("deferredValueType"), // JSP 2.1
new JspUtil.ValidAttribute("deferredMethod"), // JSP 2
new JspUtil.ValidAttribute("deferredMethodSignature"), // JSP 21
new JspUtil.ValidAttribute("description") };
private static final JspUtil.ValidAttribute[] variableDirectiveAttrs = {
new JspUtil.ValidAttribute("name-given"),
new JspUtil.ValidAttribute("name-from-attribute"),
new JspUtil.ValidAttribute("alias"),
new JspUtil.ValidAttribute("variable-class"),
new JspUtil.ValidAttribute("scope"),
new JspUtil.ValidAttribute("declare"),
new JspUtil.ValidAttribute("description") };
private ErrorDispatcher err;
private TagLibraryInfo tagLibInfo;
private String name = null;
private String path = null;
private String bodycontent = null;
private String description = null;
private String displayName = null;
private String smallIcon = null;
private String largeIcon = null;
private String dynamicAttrsMapName;
private String example = null;
private Vector<TagAttributeInfo> attributeVector;
private Vector<TagVariableInfo> variableVector;
private static final String ATTR_NAME = "the name attribute of the attribute directive";
private static final String VAR_NAME_GIVEN = "the name-given attribute of the variable directive";
private static final String VAR_NAME_FROM = "the name-from-attribute attribute of the variable directive";
private static final String VAR_ALIAS = "the alias attribute of the variable directive";
private static final String TAG_DYNAMIC = "the dynamic-attributes attribute of the tag directive";
private HashMap<String,NameEntry> nameTable = new HashMap<>();
private HashMap<String,NameEntry> nameFromTable = new HashMap<>();
public TagFileDirectiveVisitor(Compiler compiler,
TagLibraryInfo tagLibInfo, String name, String path) {
err = compiler.getErrorDispatcher();
this.tagLibInfo = tagLibInfo;
this.name = name;
this.path = path;
attributeVector = new Vector<>();
variableVector = new Vector<>();
}
@Override
public void visit(Node.TagDirective n) throws JasperException {
JspUtil.checkAttributes("Tag directive", n, tagDirectiveAttrs, err);
bodycontent = checkConflict(n, bodycontent, "body-content");
if (bodycontent != null
&& !bodycontent
.equalsIgnoreCase(TagInfo.BODY_CONTENT_EMPTY)
&& !bodycontent
.equalsIgnoreCase(TagInfo.BODY_CONTENT_TAG_DEPENDENT)
&& !bodycontent
.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) {
err.jspError(n, "jsp.error.tagdirective.badbodycontent",
bodycontent);
}
dynamicAttrsMapName = checkConflict(n, dynamicAttrsMapName,
"dynamic-attributes");
if (dynamicAttrsMapName != null) {
checkUniqueName(dynamicAttrsMapName, TAG_DYNAMIC, n);
}
smallIcon = checkConflict(n, smallIcon, "small-icon");
largeIcon = checkConflict(n, largeIcon, "large-icon");
description = checkConflict(n, description, "description");
displayName = checkConflict(n, displayName, "display-name");
example = checkConflict(n, example, "example");
}
private String checkConflict(Node n, String oldAttrValue, String attr)
throws JasperException {
String result = oldAttrValue;
String attrValue = n.getAttributeValue(attr);
if (attrValue != null) {
if (oldAttrValue != null && !oldAttrValue.equals(attrValue)) {
err.jspError(n, "jsp.error.tag.conflict.attr", attr,
oldAttrValue, attrValue);
}
result = attrValue;
}
return result;
}
@Override
public void visit(Node.AttributeDirective n) throws JasperException {
JspUtil.checkAttributes("Attribute directive", n,
attributeDirectiveAttrs, err);
// JSP 2.1 Table JSP.8-3
// handle deferredValue and deferredValueType
boolean deferredValue = false;
boolean deferredValueSpecified = false;
String deferredValueString = n.getAttributeValue("deferredValue");
if (deferredValueString != null) {
deferredValueSpecified = true;
deferredValue = JspUtil.booleanValue(deferredValueString);
}
String deferredValueType = n.getAttributeValue("deferredValueType");
if (deferredValueType != null) {
if (deferredValueSpecified && !deferredValue) {
err.jspError(n, "jsp.error.deferredvaluetypewithoutdeferredvalue");
} else {
deferredValue = true;
}
} else if (deferredValue) {
deferredValueType = "java.lang.Object";
} else {
deferredValueType = "java.lang.String";
}
// JSP 2.1 Table JSP.8-3
// handle deferredMethod and deferredMethodSignature
boolean deferredMethod = false;
boolean deferredMethodSpecified = false;
String deferredMethodString = n.getAttributeValue("deferredMethod");
if (deferredMethodString != null) {
deferredMethodSpecified = true;
deferredMethod = JspUtil.booleanValue(deferredMethodString);
}
String deferredMethodSignature = n
.getAttributeValue("deferredMethodSignature");
if (deferredMethodSignature != null) {
if (deferredMethodSpecified && !deferredMethod) {
err.jspError(n, "jsp.error.deferredmethodsignaturewithoutdeferredmethod");
} else {
deferredMethod = true;
}
} else if (deferredMethod) {
deferredMethodSignature = "void methodname()";
}
if (deferredMethod && deferredValue) {
err.jspError(n, "jsp.error.deferredmethodandvalue");
}
String attrName = n.getAttributeValue("name");
boolean required = JspUtil.booleanValue(n
.getAttributeValue("required"));
boolean rtexprvalue = true;
String rtexprvalueString = n.getAttributeValue("rtexprvalue");
if (rtexprvalueString != null) {
rtexprvalue = JspUtil.booleanValue(rtexprvalueString);
}
boolean fragment = JspUtil.booleanValue(n
.getAttributeValue("fragment"));
String type = n.getAttributeValue("type");
if (fragment) {
// type is fixed to "JspFragment" and a translation error
// must occur if specified.
if (type != null) {
err.jspError(n, "jsp.error.fragmentwithtype");
}
// rtexprvalue is fixed to "true" and a translation error
// must occur if specified.
rtexprvalue = true;
if (rtexprvalueString != null) {
err.jspError(n, "jsp.error.frgmentwithrtexprvalue");
}
} else {
if (type == null)
type = "java.lang.String";
if (deferredValue) {
type = ValueExpression.class.getName();
} else if (deferredMethod) {
type = MethodExpression.class.getName();
}
}
if (("2.0".equals(tagLibInfo.getRequiredVersion()) || ("1.2".equals(tagLibInfo.getRequiredVersion())))
&& (deferredMethodSpecified || deferredMethod
|| deferredValueSpecified || deferredValue)) {
err.jspError("jsp.error.invalid.version", path);
}
TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(attrName,
required, type, rtexprvalue, fragment, null, deferredValue,
deferredMethod, deferredValueType, deferredMethodSignature);
attributeVector.addElement(tagAttributeInfo);
checkUniqueName(attrName, ATTR_NAME, n, tagAttributeInfo);
}
@Override
public void visit(Node.VariableDirective n) throws JasperException {
JspUtil.checkAttributes("Variable directive", n,
variableDirectiveAttrs, err);
String nameGiven = n.getAttributeValue("name-given");
String nameFromAttribute = n
.getAttributeValue("name-from-attribute");
if (nameGiven == null && nameFromAttribute == null) {
err.jspError("jsp.error.variable.either.name");
}
if (nameGiven != null && nameFromAttribute != null) {
err.jspError("jsp.error.variable.both.name");
}
String alias = n.getAttributeValue("alias");
if (nameFromAttribute != null && alias == null
|| nameFromAttribute == null && alias != null) {
err.jspError("jsp.error.variable.alias");
}
String className = n.getAttributeValue("variable-class");
if (className == null)
className = "java.lang.String";
String declareStr = n.getAttributeValue("declare");
boolean declare = true;
if (declareStr != null)
declare = JspUtil.booleanValue(declareStr);
int scope = VariableInfo.NESTED;
String scopeStr = n.getAttributeValue("scope");
if (scopeStr != null) {
if ("NESTED".equals(scopeStr)) {
// Already the default
} else if ("AT_BEGIN".equals(scopeStr)) {
scope = VariableInfo.AT_BEGIN;
} else if ("AT_END".equals(scopeStr)) {
scope = VariableInfo.AT_END;
}
}
if (nameFromAttribute != null) {
/*
* An alias has been specified. We use 'nameGiven' to hold the
* value of the alias, and 'nameFromAttribute' to hold the name
* of the attribute whose value (at invocation-time) denotes the
* name of the variable that is being aliased
*/
nameGiven = alias;
checkUniqueName(nameFromAttribute, VAR_NAME_FROM, n);
checkUniqueName(alias, VAR_ALIAS, n);
} else {
// name-given specified
checkUniqueName(nameGiven, VAR_NAME_GIVEN, n);
}
variableVector.addElement(new TagVariableInfo(nameGiven,
nameFromAttribute, className, declare, scope));
}
public TagInfo getTagInfo() throws JasperException {
if (name == null) {
// XXX Get it from tag file name
}
if (bodycontent == null) {
bodycontent = TagInfo.BODY_CONTENT_SCRIPTLESS;
}
String tagClassName = JspUtil.getTagHandlerClassName(
path, tagLibInfo.getReliableURN(), err);
TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector
.size()];
variableVector.copyInto(tagVariableInfos);
TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector
.size()];
attributeVector.copyInto(tagAttributeInfo);
return new JasperTagInfo(name, tagClassName, bodycontent,
description, tagLibInfo, null, tagAttributeInfo,
displayName, smallIcon, largeIcon, tagVariableInfos,
dynamicAttrsMapName);
}
static class NameEntry {
private String type;
private Node node;
private TagAttributeInfo attr;
NameEntry(String type, Node node, TagAttributeInfo attr) {
this.type = type;
this.node = node;
this.attr = attr;
}
String getType() {
return type;
}
Node getNode() {
return node;
}
TagAttributeInfo getTagAttributeInfo() {
return attr;
}
}
/**
* Reports a translation error if names specified in attributes of
* directives are not unique in this translation unit.
*
* The value of the following attributes must be unique. 1. 'name'
* attribute of an attribute directive 2. 'name-given' attribute of a
* variable directive 3. 'alias' attribute of variable directive 4.
* 'dynamic-attributes' of a tag directive except that
* 'dynamic-attributes' can (and must) have the same value when it
* appears in multiple tag directives.
*
* Also, 'name-from' attribute of a variable directive cannot have the
* same value as that from another variable directive.
*/
private void checkUniqueName(String name, String type, Node n)
throws JasperException {
checkUniqueName(name, type, n, null);
}
private void checkUniqueName(String name, String type, Node n,
TagAttributeInfo attr) throws JasperException {
HashMap<String, NameEntry> table = (type == VAR_NAME_FROM) ? nameFromTable : nameTable;
NameEntry nameEntry = table.get(name);
if (nameEntry != null) {
if (!TAG_DYNAMIC.equals(type) ||
!TAG_DYNAMIC.equals(nameEntry.getType())) {
int line = nameEntry.getNode().getStart().getLineNumber();
err.jspError(n, "jsp.error.tagfile.nameNotUnique", type,
nameEntry.getType(), Integer.toString(line));
}
} else {
table.put(name, new NameEntry(type, n, attr));
}
}
/**
* Perform miscellaneous checks after the nodes are visited.
*/
void postCheck() throws JasperException {
// Check that var.name-from-attributes has valid values.
Iterator<String> iter = nameFromTable.keySet().iterator();
while (iter.hasNext()) {
String nameFrom = iter.next();
NameEntry nameEntry = nameTable.get(nameFrom);
NameEntry nameFromEntry = nameFromTable.get(nameFrom);
Node nameFromNode = nameFromEntry.getNode();
if (nameEntry == null) {
err.jspError(nameFromNode,
"jsp.error.tagfile.nameFrom.noAttribute", nameFrom);
} else {
Node node = nameEntry.getNode();
TagAttributeInfo tagAttr = nameEntry.getTagAttributeInfo();
if (!"java.lang.String".equals(tagAttr.getTypeName())
|| !tagAttr.isRequired()
|| tagAttr.canBeRequestTime()) {
err.jspError(nameFromNode,
"jsp.error.tagfile.nameFrom.badAttribute",
nameFrom, Integer.toString(node.getStart()
.getLineNumber()));
}
}
}
}
}
/**
* Parses the tag file, and collects information on the directives included
* in it. The method is used to obtain the info on the tag file, when the
* handler that it represents is referenced. The tag file is not compiled
* here.
*
* @param pc
* the current ParserController used in this compilation
* @param name
* the tag name as specified in the TLD
* @param path
* the path for the tagfile
* @param jarResource
* the Jar resource containing the tag file
* @param tagLibInfo
* the TagLibraryInfo object associated with this TagInfo
* @return a TagInfo object assembled from the directives in the tag file.
*/
@SuppressWarnings("null") // page can't be null
public static TagInfo parseTagFileDirectives(ParserController pc,
String name, String path, JarResource jarResource, TagLibraryInfo tagLibInfo)
throws JasperException {
ErrorDispatcher err = pc.getCompiler().getErrorDispatcher();
Node.Nodes page = null;
try {
page = pc.parseTagFileDirectives(path, jarResource);
} catch (FileNotFoundException e) {
err.jspError("jsp.error.file.not.found", path);
} catch (IOException e) {
err.jspError("jsp.error.file.not.found", path);
}
TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor(pc
.getCompiler(), tagLibInfo, name, path);
page.visit(tagFileVisitor);
tagFileVisitor.postCheck();
return tagFileVisitor.getTagInfo();
}
/**
* Compiles and loads a tagfile.
*/
private Class<?> loadTagFile(Compiler compiler, String tagFilePath,
TagInfo tagInfo, PageInfo parentPageInfo) throws JasperException {
JarResource tagJarResouce = null;
if (tagFilePath.startsWith("/META-INF/")) {
tagJarResouce =
compiler.getCompilationContext().getTldLocation(
tagInfo.getTagLibrary().getURI()).getJarResource();
}
String wrapperUri;
if (tagJarResouce == null) {
wrapperUri = tagFilePath;
} else {
wrapperUri = tagJarResouce.getEntry(tagFilePath).toString();
}
JspCompilationContext ctxt = compiler.getCompilationContext();
JspRuntimeContext rctxt = ctxt.getRuntimeContext();
JspServletWrapper wrapper = rctxt.getWrapper(wrapperUri);
synchronized (rctxt) {
if (wrapper == null) {
wrapper = new JspServletWrapper(ctxt.getServletContext(), ctxt
.getOptions(), tagFilePath, tagInfo, ctxt
.getRuntimeContext(), tagJarResouce);
rctxt.addWrapper(wrapperUri, wrapper);
// Use same classloader and classpath for compiling tag files
wrapper.getJspEngineContext().setClassLoader(
ctxt.getClassLoader());
wrapper.getJspEngineContext().setClassPath(ctxt.getClassPath());
} else {
// Make sure that JspCompilationContext gets the latest TagInfo
// for the tag file. TagInfo instance was created the last
// time the tag file was scanned for directives, and the tag
// file may have been modified since then.
wrapper.getJspEngineContext().setTagInfo(tagInfo);
}
Class<?> tagClazz;
int tripCount = wrapper.incTripCount();
try {
if (tripCount > 0) {
// When tripCount is greater than zero, a circular
// dependency exists. The circularly dependent tag
// file is compiled in prototype mode, to avoid infinite
// recursion.
JspServletWrapper tempWrapper = new JspServletWrapper(ctxt
.getServletContext(), ctxt.getOptions(),
tagFilePath, tagInfo, ctxt.getRuntimeContext(),
ctxt.getTagFileJarResource(tagFilePath));
// Use same classloader and classpath for compiling tag files
tempWrapper.getJspEngineContext().setClassLoader(
ctxt.getClassLoader());
tempWrapper.getJspEngineContext().setClassPath(ctxt.getClassPath());
tagClazz = tempWrapper.loadTagFilePrototype();
tempVector.add(tempWrapper.getJspEngineContext()
.getCompiler());
} else {
tagClazz = wrapper.loadTagFile();
}
} finally {
wrapper.decTripCount();
}
// Add the dependents for this tag file to its parent's
// Dependent list. The only reliable dependency information
// can only be obtained from the tag instance.
try {
Object tagIns = tagClazz.newInstance();
if (tagIns instanceof JspSourceDependent) {
Iterator<Entry<String,Long>> iter = ((JspSourceDependent)
tagIns).getDependants().entrySet().iterator();
while (iter.hasNext()) {
Entry<String,Long> entry = iter.next();
parentPageInfo.addDependant(entry.getKey(),
entry.getValue());
}
}
} catch (Exception e) {
// ignore errors
}
return tagClazz;
}
}
/*
* Visitor which scans the page and looks for tag handlers that are tag
* files, compiling (if necessary) and loading them.
*/
private class TagFileLoaderVisitor extends Node.Visitor {
private Compiler compiler;
private PageInfo pageInfo;
TagFileLoaderVisitor(Compiler compiler) {
this.compiler = compiler;
this.pageInfo = compiler.getPageInfo();
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
TagFileInfo tagFileInfo = n.getTagFileInfo();
if (tagFileInfo != null) {
String tagFilePath = tagFileInfo.getPath();
if (tagFilePath.startsWith("/META-INF/")) {
// For tags in JARs, add the TLD and the tag as a dependency
TldLocation location =
compiler.getCompilationContext().getTldLocation(
tagFileInfo.getTagInfo().getTagLibrary().getURI());
JarResource jarResource = location.getJarResource();
if (jarResource != null) {
try {
// Add TLD
pageInfo.addDependant(jarResource.getEntry(location.getName()).toString(),
Long.valueOf(jarResource.getJarFile().getEntry(location.getName()).getTime()));
// Add Tag
pageInfo.addDependant(jarResource.getEntry(tagFilePath.substring(1)).toString(),
Long.valueOf(jarResource.getJarFile().getEntry(tagFilePath.substring(1)).getTime()));
} catch (IOException ioe) {
throw new JasperException(ioe);
}
}
else {
pageInfo.addDependant(tagFilePath,
compiler.getCompilationContext().getLastModified(
tagFilePath));
}
} else {
pageInfo.addDependant(tagFilePath,
compiler.getCompilationContext().getLastModified(
tagFilePath));
}
Class<?> c = loadTagFile(compiler, tagFilePath, n.getTagInfo(),
pageInfo);
n.setTagHandlerClass(c);
}
visitBody(n);
}
}
/**
* Implements a phase of the translation that compiles (if necessary) the
* tag files used in a JSP files. The directives in the tag files are
* assumed to have been processed and encapsulated as TagFileInfo in the
* CustomTag nodes.
*/
public void loadTagFiles(Compiler compiler, Node.Nodes page)
throws JasperException {
tempVector = new Vector<>();
page.visit(new TagFileLoaderVisitor(compiler));
}
/**
* Removed the java and class files for the tag prototype generated from the
* current compilation.
*
* @param classFileName
* If non-null, remove only the class file with with this name.
*/
public void removeProtoTypeFiles(String classFileName) {
Iterator<Compiler> iter = tempVector.iterator();
while (iter.hasNext()) {
Compiler c = iter.next();
if (classFileName == null) {
c.removeGeneratedClassFiles();
} else if (classFileName.equals(c.getCompilationContext()
.getClassFileName())) {
c.removeGeneratedClassFiles();
tempVector.remove(c);
return;
}
}
}
}
|
55,576
|
Bug 55576 Order of ServletRequest parameters is not preserved
|
The ServletRequest interface provides two methods to iterate through request parameters: Enumeration<String> getParameterNames(), and Map<String, String[]> getParameterMap() Unfortunately, the underlying implementation in Tomcat is a HashMap, which fails to preserve the order of parameters as they are specified in the request. An alternate implementation should be used to preserve request order. LinkedHashMap, for example, is capable of preserving insertion order. The Servlet Specification (v3.0) speaks only to the relative ordering of query string data and post body data. However, section 17.13.3 of the HTML specification (v4.01) titled "Processing form data", clearly states that "control names/values are listed in the order they appear in the document." Therefore, I do not see a valid interpretation of either specification to rationalize Tomcat's implementation. To receive a request with an ordered list of parameters and represent them in an implementation that is guaranteed not to preserve this order is difficult to rationalize.
|
resolved fixed
|
90556a9
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-23T20:52:58Z
| 2013-09-21T02:20:00Z
|
java/org/apache/catalina/util/ParameterMap.java
|
/*
* 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 java.util.Map;
import org.apache.tomcat.util.res.StringManager;
/**
* Extended implementation of <strong>HashMap</strong> that includes a
* <code>locked</code> property. This class can be used to safely expose
* Catalina internal parameter map objects to user classes without having
* to clone them in order to avoid modifications. When first created, a
* <code>ParmaeterMap</code> instance is not locked.
*
* @author Craig R. McClanahan
* @version $Id$
*/
public final class ParameterMap<K,V> extends HashMap<K,V> {
private static final long serialVersionUID = 1L;
// ----------------------------------------------------------- Constructors
/**
* Construct a new, empty map with the default initial capacity and
* load factor.
*/
public ParameterMap() {
super();
}
/**
* Construct a new, empty map with the specified initial capacity and
* default load factor.
*
* @param initialCapacity The initial capacity of this map
*/
public ParameterMap(int initialCapacity) {
super(initialCapacity);
}
/**
* Construct a new, empty map with the specified initial capacity and
* load factor.
*
* @param initialCapacity The initial capacity of this map
* @param loadFactor The load factor of this map
*/
public ParameterMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Construct a new map with the same mappings as the given map.
*
* @param map Map whose contents are duplicated in the new map
*/
public ParameterMap(Map<K,V> map) {
super(map);
}
// ------------------------------------------------------------- Properties
/**
* The current lock state of this parameter map.
*/
private boolean locked = false;
/**
* Return the locked state of this parameter map.
*/
public boolean isLocked() {
return (this.locked);
}
/**
* Set the locked state of this parameter map.
*
* @param locked The new locked state
*/
public void setLocked(boolean locked) {
this.locked = locked;
}
/**
* The string manager for this package.
*/
private static final StringManager sm =
StringManager.getManager("org.apache.catalina.util");
// --------------------------------------------------------- Public Methods
/**
* Remove all mappings from this map.
*
* @exception IllegalStateException if this map is currently locked
*/
@Override
public void clear() {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
super.clear();
}
/**
* Associate the specified value with the specified key in this map. If
* the map previously contained a mapping for this key, the old value is
* replaced.
*
* @param key Key with which the specified value is to be associated
* @param value Value to be associated with the specified key
*
* @return The previous value associated with the specified key, or
* <code>null</code> if there was no mapping for key
*
* @exception IllegalStateException if this map is currently locked
*/
@Override
public V put(K key, V value) {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
return (super.put(key, value));
}
/**
* Copy all of the mappings from the specified map to this one. These
* mappings replace any mappings that this map had for any of the keys
* currently in the specified Map.
*
* @param map Mappings to be stored into this map
*
* @exception IllegalStateException if this map is currently locked
*/
@Override
public void putAll(Map<? extends K,? extends V> map) {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
super.putAll(map);
}
/**
* Remove the mapping for this key from the map if present.
*
* @param key Key whose mapping is to be removed from the map
*
* @return The previous value associated with the specified key, or
* <code>null</code> if there was no mapping for that key
*
* @exception IllegalStateException if this map is currently locked
*/
@Override
public V remove(Object key) {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
return (super.remove(key));
}
}
|
55,576
|
Bug 55576 Order of ServletRequest parameters is not preserved
|
The ServletRequest interface provides two methods to iterate through request parameters: Enumeration<String> getParameterNames(), and Map<String, String[]> getParameterMap() Unfortunately, the underlying implementation in Tomcat is a HashMap, which fails to preserve the order of parameters as they are specified in the request. An alternate implementation should be used to preserve request order. LinkedHashMap, for example, is capable of preserving insertion order. The Servlet Specification (v3.0) speaks only to the relative ordering of query string data and post body data. However, section 17.13.3 of the HTML specification (v4.01) titled "Processing form data", clearly states that "control names/values are listed in the order they appear in the document." Therefore, I do not see a valid interpretation of either specification to rationalize Tomcat's implementation. To receive a request with an ordered list of parameters and represent them in an implementation that is guaranteed not to preserve this order is difficult to rationalize.
|
resolved fixed
|
90556a9
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-23T20:52:58Z
| 2013-09-21T02:20:00Z
|
java/org/apache/tomcat/util/http/Parameters.java
|
/*
* 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.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.buf.UDecoder;
import org.apache.tomcat.util.log.UserDataHelper;
import org.apache.tomcat.util.res.StringManager;
/**
*
* @author Costin Manolache
*/
public final class Parameters {
private static final org.apache.juli.logging.Log log =
org.apache.juli.logging.LogFactory.getLog(Parameters.class );
private static final UserDataHelper userDataLog = new UserDataHelper(log);
private static final UserDataHelper maxParamCountLog = new UserDataHelper(log);
private static final StringManager sm =
StringManager.getManager("org.apache.tomcat.util.http");
private final HashMap<String,ArrayList<String>> paramHashValues =
new HashMap<>();
private boolean didQueryParameters=false;
private MessageBytes queryMB;
private UDecoder urlDec;
private final MessageBytes decodedQuery = MessageBytes.newInstance();
private String encoding=null;
private String queryStringEncoding=null;
private int limit = -1;
private int parameterCount = 0;
/**
* Is set to <code>true</code> if there were failures during parameter
* parsing.
*/
private boolean parseFailed = false;
public Parameters() {
// NO-OP
}
public void setQuery( MessageBytes queryMB ) {
this.queryMB=queryMB;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getEncoding() {
return encoding;
}
public void setEncoding( String s ) {
encoding=s;
if(log.isDebugEnabled()) {
log.debug( "Set encoding to " + s );
}
}
public void setQueryStringEncoding( String s ) {
queryStringEncoding=s;
if(log.isDebugEnabled()) {
log.debug( "Set query string encoding to " + s );
}
}
public boolean isParseFailed() {
return parseFailed;
}
public void setParseFailed(boolean parseFailed) {
this.parseFailed = parseFailed;
}
public void recycle() {
parameterCount = 0;
paramHashValues.clear();
didQueryParameters=false;
encoding=null;
decodedQuery.recycle();
parseFailed = false;
}
// -------------------- Data access --------------------
// Access to the current name/values, no side effect ( processing ).
// You must explicitly call handleQueryParameters and the post methods.
public String[] getParameterValues(String name) {
handleQueryParameters();
// no "facade"
ArrayList<String> values = paramHashValues.get(name);
if (values == null) {
return null;
}
return values.toArray(new String[values.size()]);
}
public Enumeration<String> getParameterNames() {
handleQueryParameters();
return Collections.enumeration(paramHashValues.keySet());
}
public String getParameter(String name ) {
handleQueryParameters();
ArrayList<String> values = paramHashValues.get(name);
if (values != null) {
if(values.size() == 0) {
return "";
}
return values.get(0);
} else {
return null;
}
}
// -------------------- Processing --------------------
/** Process the query string into parameters
*/
public void handleQueryParameters() {
if( didQueryParameters ) {
return;
}
didQueryParameters=true;
if( queryMB==null || queryMB.isNull() ) {
return;
}
if(log.isDebugEnabled()) {
log.debug("Decoding query " + decodedQuery + " " +
queryStringEncoding);
}
try {
decodedQuery.duplicate( queryMB );
} catch (IOException e) {
// Can't happen, as decodedQuery can't overflow
e.printStackTrace();
}
processParameters( decodedQuery, queryStringEncoding );
}
public void addParameter( String key, String value )
throws IllegalStateException {
if( key==null ) {
return;
}
parameterCount ++;
if (limit > -1 && parameterCount > limit) {
// Processing this parameter will push us over the limit. ISE is
// what Request.parseParts() uses for requests that are too big
parseFailed = true;
throw new IllegalStateException(sm.getString(
"parameters.maxCountFail", Integer.valueOf(limit)));
}
ArrayList<String> values = paramHashValues.get(key);
if (values == null) {
values = new ArrayList<>(1);
paramHashValues.put(key, values);
}
values.add(value);
}
public void setURLDecoder( UDecoder u ) {
urlDec=u;
}
// -------------------- Parameter parsing --------------------
// we are called from a single thread - we can do it the hard way
// if needed
private final ByteChunk tmpName=new ByteChunk();
private final ByteChunk tmpValue=new ByteChunk();
private final ByteChunk origName=new ByteChunk();
private final ByteChunk origValue=new ByteChunk();
public static final String DEFAULT_ENCODING = "ISO-8859-1";
private static final Charset DEFAULT_CHARSET =
StandardCharsets.ISO_8859_1;
public void processParameters( byte bytes[], int start, int len ) {
processParameters(bytes, start, len, getCharset(encoding));
}
private void processParameters(byte bytes[], int start, int len,
Charset charset) {
if(log.isDebugEnabled()) {
log.debug(sm.getString("parameters.bytes",
new String(bytes, start, len, DEFAULT_CHARSET)));
}
int decodeFailCount = 0;
int pos = start;
int end = start + len;
while(pos < end) {
int nameStart = pos;
int nameEnd = -1;
int valueStart = -1;
int valueEnd = -1;
boolean parsingName = true;
boolean decodeName = false;
boolean decodeValue = false;
boolean parameterComplete = false;
do {
switch(bytes[pos]) {
case '=':
if (parsingName) {
// Name finished. Value starts from next character
nameEnd = pos;
parsingName = false;
valueStart = ++pos;
} else {
// Equals character in value
pos++;
}
break;
case '&':
if (parsingName) {
// Name finished. No value.
nameEnd = pos;
} else {
// Value finished
valueEnd = pos;
}
parameterComplete = true;
pos++;
break;
case '%':
case '+':
// Decoding required
if (parsingName) {
decodeName = true;
} else {
decodeValue = true;
}
pos ++;
break;
default:
pos ++;
break;
}
} while (!parameterComplete && pos < end);
if (pos == end) {
if (nameEnd == -1) {
nameEnd = pos;
} else if (valueStart > -1 && valueEnd == -1){
valueEnd = pos;
}
}
if (log.isDebugEnabled() && valueStart == -1) {
log.debug(sm.getString("parameters.noequal",
Integer.valueOf(nameStart), Integer.valueOf(nameEnd),
new String(bytes, nameStart, nameEnd-nameStart,
DEFAULT_CHARSET)));
}
if (nameEnd <= nameStart ) {
if (valueStart == -1) {
// &&
if (log.isDebugEnabled()) {
log.debug(sm.getString("parameters.emptyChunk"));
}
// Do not flag as error
continue;
}
// &=foo&
UserDataHelper.Mode logMode = userDataLog.getNextMode();
if (logMode != null) {
String extract;
if (valueEnd > nameStart) {
extract = new String(bytes, nameStart, valueEnd
- nameStart, DEFAULT_CHARSET);
} else {
extract = "";
}
String message = sm.getString("parameters.invalidChunk",
Integer.valueOf(nameStart),
Integer.valueOf(valueEnd), extract);
switch (logMode) {
case INFO_THEN_DEBUG:
message += sm.getString("parameters.fallToDebug");
//$FALL-THROUGH$
case INFO:
log.info(message);
break;
case DEBUG:
log.debug(message);
}
}
parseFailed = true;
continue;
// invalid chunk - it's better to ignore
}
tmpName.setBytes(bytes, nameStart, nameEnd - nameStart);
if (valueStart >= 0) {
tmpValue.setBytes(bytes, valueStart, valueEnd - valueStart);
} else {
tmpValue.setBytes(bytes, 0, 0);
}
// Take copies as if anything goes wrong originals will be
// corrupted. This means original values can be logged.
// For performance - only done for debug
if (log.isDebugEnabled()) {
try {
origName.append(bytes, nameStart, nameEnd - nameStart);
if (valueStart >= 0) {
origValue.append(bytes, valueStart, valueEnd - valueStart);
} else {
origValue.append(bytes, 0, 0);
}
} catch (IOException ioe) {
// Should never happen...
log.error(sm.getString("parameters.copyFail"), ioe);
}
}
try {
String name;
String value;
if (decodeName) {
urlDecode(tmpName);
}
tmpName.setCharset(charset);
name = tmpName.toString();
if (valueStart >= 0) {
if (decodeValue) {
urlDecode(tmpValue);
}
tmpValue.setCharset(charset);
value = tmpValue.toString();
} else {
value = "";
}
try {
addParameter(name, value);
} catch (IllegalStateException ise) {
// Hitting limit stops processing further params but does
// not cause request to fail.
parseFailed = true;
UserDataHelper.Mode logMode = maxParamCountLog.getNextMode();
if (logMode != null) {
String message = ise.getMessage();
switch (logMode) {
case INFO_THEN_DEBUG:
message += sm.getString(
"parameters.maxCountFail.fallToDebug");
//$FALL-THROUGH$
case INFO:
log.info(message);
break;
case DEBUG:
log.debug(message);
}
}
break;
}
} catch (IOException e) {
parseFailed = true;
decodeFailCount++;
if (decodeFailCount == 1 || log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("parameters.decodeFail.debug",
origName.toString(), origValue.toString()), e);
} else if (log.isInfoEnabled()) {
UserDataHelper.Mode logMode = userDataLog.getNextMode();
if (logMode != null) {
String message = sm.getString(
"parameters.decodeFail.info",
tmpName.toString(), tmpValue.toString());
switch (logMode) {
case INFO_THEN_DEBUG:
message += sm.getString("parameters.fallToDebug");
//$FALL-THROUGH$
case INFO:
log.info(message);
break;
case DEBUG:
log.debug(message);
}
}
}
}
}
tmpName.recycle();
tmpValue.recycle();
// Only recycle copies if we used them
if (log.isDebugEnabled()) {
origName.recycle();
origValue.recycle();
}
}
if (decodeFailCount > 1 && !log.isDebugEnabled()) {
UserDataHelper.Mode logMode = userDataLog.getNextMode();
if (logMode != null) {
String message = sm.getString(
"parameters.multipleDecodingFail",
Integer.valueOf(decodeFailCount));
switch (logMode) {
case INFO_THEN_DEBUG:
message += sm.getString("parameters.fallToDebug");
//$FALL-THROUGH$
case INFO:
log.info(message);
break;
case DEBUG:
log.debug(message);
}
}
}
}
private void urlDecode(ByteChunk bc)
throws IOException {
if( urlDec==null ) {
urlDec=new UDecoder();
}
urlDec.convert(bc, true);
}
public void processParameters( MessageBytes data, String encoding ) {
if( data==null || data.isNull() || data.getLength() <= 0 ) {
return;
}
if( data.getType() != MessageBytes.T_BYTES ) {
data.toBytes();
}
ByteChunk bc=data.getByteChunk();
processParameters( bc.getBytes(), bc.getOffset(),
bc.getLength(), getCharset(encoding));
}
private Charset getCharset(String encoding) {
if (encoding == null) {
return DEFAULT_CHARSET;
}
try {
return B2CConverter.getCharset(encoding);
} catch (UnsupportedEncodingException e) {
return DEFAULT_CHARSET;
}
}
/**
* Debug purpose
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, ArrayList<String>> e : paramHashValues.entrySet()) {
sb.append(e.getKey()).append('=');
ArrayList<String> values = e.getValue();
for (String value : values) {
sb.append(value).append(',');
}
sb.append('\n');
}
return sb.toString();
}
}
|
55,317
|
Bug 55317 Facilitate weaving by allowing ClassFileTransformer to be added to WebppClassLoader
| null |
resolved fixed
|
dd0cba7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-26T22:55:22Z
| 2013-07-28T11:13:20Z
|
java/org/apache/catalina/loader/WebappClassLoader.java
|
/*
* 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.loader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.catalina.Globals;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
* Specialized web application class loader.
* <p>
* This class loader is a full reimplementation of the
* <code>URLClassLoader</code> from the JDK. It is designed to be fully
* compatible with a normal <code>URLClassLoader</code>, although its internal
* behavior may be completely different.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - By default, this class loader follows
* the delegation model required by the specification. The system class
* loader will be queried first, then the local repositories, and only then
* delegation to the parent class loader will occur. This allows the web
* application to override any shared class except the classes from J2SE.
* Special handling is provided from the JAXP XML parser interfaces, the JNDI
* interfaces, and the classes from the servlet API, which are never loaded
* from the webapp repositories. The <code>delegate</code> property
* allows an application to modify this behavior to move the parent class loader
* ahead of the local repositories.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper
* compilation technology, any repository which contains classes from
* the servlet API will be ignored by the class loader.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source
* URLs which include the full JAR URL when a class is loaded from a JAR file,
* which allows setting security permission at the class level, even when a
* class is contained inside a JAR.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in
* the order they are added via the initial constructor and/or any subsequent
* calls to <code>addRepository()</code> or <code>addJar()</code>.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or
* security is made unless a security manager is present.
* <p>
*
* @author Remy Maucherat
* @author Craig R. McClanahan
* @version $Id$
*/
public class WebappClassLoader
extends URLClassLoader
implements Lifecycle
{
private static final org.apache.juli.logging.Log log=
org.apache.juli.logging.LogFactory.getLog( WebappClassLoader.class );
/**
* List of ThreadGroup names to ignore when scanning for web application
* started threads that need to be shut down.
*/
private static final List<String> JVM_THREAD_GROUP_NAMES = new ArrayList<>();
private static final String JVN_THREAD_GROUP_SYSTEM = "system";
static {
JVM_THREAD_GROUP_NAMES.add(JVN_THREAD_GROUP_SYSTEM);
JVM_THREAD_GROUP_NAMES.add("RMI Runtime");
}
protected class PrivilegedFindResourceByName
implements PrivilegedAction<ResourceEntry> {
protected final String name;
protected final String path;
PrivilegedFindResourceByName(String name, String path) {
this.name = name;
this.path = path;
}
@Override
public ResourceEntry run() {
return findResourceInternal(name, path);
}
}
protected static final class PrivilegedGetClassLoader
implements PrivilegedAction<ClassLoader> {
public final Class<?> clazz;
public PrivilegedGetClassLoader(Class<?> clazz){
this.clazz = clazz;
}
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
}
// ------------------------------------------------------- Static Variables
/**
* The set of trigger classes that will cause a proposed repository not
* to be added if this class is visible to the class loader that loaded
* this factory class. Typically, trigger classes will be listed for
* components that have been integrated into the JDK for later versions,
* but where the corresponding JAR files are required to run on
* earlier versions.
*/
protected static final String[] triggers = {
"javax.servlet.Servlet", "javax.el.Expression" // Servlet API
};
/**
* Set of package names which are not allowed to be loaded from a webapp
* class loader without delegating first.
*/
protected static final String[] packageTriggers = {
};
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Use anti JAR locking code, which does URL rerouting when accessing
* resources.
*/
boolean antiJARLocking = false;
// ----------------------------------------------------------- Constructors
/**
* Construct a new ClassLoader with no defined repositories and no
* parent ClassLoader.
*/
public WebappClassLoader() {
super(new URL[0]);
this.parent = getParent();
system = getSystemClassLoader();
securityManager = System.getSecurityManager();
if (securityManager != null) {
refreshPolicy();
}
}
/**
* Construct a new ClassLoader with no defined repositories and the given
* parent ClassLoader.
* <p>
* Method is used via reflection -
* see {@link WebappLoader#createClassLoader()}
*
* @param parent Our parent class loader
*/
public WebappClassLoader(ClassLoader parent) {
super(new URL[0], parent);
this.parent = getParent();
system = getSystemClassLoader();
securityManager = System.getSecurityManager();
if (securityManager != null) {
refreshPolicy();
}
}
// ----------------------------------------------------- Instance Variables
/**
* Associated web resources for this webapp.
* TODO Review the use of resources in this class to see if further
* simplifications can be made.
*/
protected WebResourceRoot resources = null;
/**
* The cache of ResourceEntry for classes and resources we have loaded,
* keyed by resource name.
*/
protected final HashMap<String, ResourceEntry> resourceEntries = new HashMap<>();
/**
* The list of not found resources.
*/
protected final HashMap<String, String> notFoundResources =
new LinkedHashMap<String, String>() {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(
Map.Entry<String, String> eldest) {
return size() > 1000;
}
};
/**
* Should this class loader delegate to the parent class loader
* <strong>before</strong> searching its own repositories (i.e. the
* usual Java2 delegation model)? If set to <code>false</code>,
* this class loader will search its own repositories first, and
* delegate to the parent only if the class or resource is not
* found locally. Note that the default, <code>false</code>, is
* the behavior called for by the servlet specification.
*/
protected boolean delegate = false;
/**
* Last time a JAR was accessed.
*/
protected long lastJarAccessed = 0L;
/**
* The path to the repository for locally loaded classes or resources. This
* would normally be /WEB-INF/classes/.
*/
protected String repositoryPath = null;
/**
* Repositories URLs, used to cache the result of getURLs.
*/
protected URL[] repositoryURLs = null;
/**
* The {@link WebResource} for the repository for locally loaded classes or
* resources. This would normally point to /WEB-INF/classes/.
*/
protected WebResource repository = null;
/**
* The list of JARs, in the order they should be searched
* for locally loaded classes or resources.
*/
protected JarFile[] jarFiles = new JarFile[0];
/**
* The list of JARs, in the order they should be searched
* for locally loaded classes or resources.
*/
protected File[] jarRealFiles = new File[0];
/**
* The path which will be monitored for added Jar files.
*/
protected String jarPath = null;
/**
* The list of JARs, in the order they should be searched
* for locally loaded classes or resources.
*/
protected String[] jarNames = new String[0];
/**
* The list of JARs last modified dates, in the order they should be
* searched for locally loaded classes or resources.
*/
protected long[] lastModifiedDates = new long[0];
/**
* The list of resources which should be checked when checking for
* modifications.
*/
protected String[] paths = new String[0];
/**
* A list of read File and Jndi Permission's required if this loader
* is for a web application context.
*/
protected final ArrayList<Permission> permissionList = new ArrayList<>();
/**
* Path where resources loaded from JARs will be extracted.
*/
protected File loaderDir = null;
protected String canonicalLoaderDir = null;
/**
* The PermissionCollection for each CodeSource for a web
* application context.
*/
protected final HashMap<String, PermissionCollection> loaderPC = new HashMap<>();
/**
* Instance of the SecurityManager installed.
*/
protected final SecurityManager securityManager;
/**
* The parent class loader.
*/
protected ClassLoader parent = null;
/**
* The system class loader.
*/
protected final ClassLoader system;
/**
* Has this component been started?
*/
protected boolean started = false;
/**
* need conversion for properties files
*/
protected boolean needConvert = false;
/**
* All permission.
*/
protected final Permission allPermission = new java.security.AllPermission();
/**
* Should Tomcat attempt to null out any static or final fields from loaded
* classes when a web application is stopped as a work around for apparent
* garbage collection bugs and application coding errors? There have been
* some issues reported with log4j when this option is true. Applications
* without memory leaks using recent JVMs should operate correctly with this
* option set to <code>false</code>. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStatic = false;
/**
* Should Tomcat attempt to terminate threads that have been started by the
* web application? Stopping threads is performed via the deprecated (for
* good reason) <code>Thread.stop()</code> method and is likely to result in
* instability. As such, enabling this should be viewed as an option of last
* resort in a development environment and is not recommended in a
* production environment. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStopThreads = false;
/**
* Should Tomcat attempt to terminate any {@link java.util.TimerThread}s
* that have been started by the web application? If not specified, the
* default value of <code>false</code> will be used.
*/
private boolean clearReferencesStopTimerThreads = false;
/**
* Should Tomcat call {@link org.apache.juli.logging.LogFactory#release()}
* when the class loader is stopped? If not specified, the default value
* of <code>true</code> is used. Changing the default setting is likely to
* lead to memory leaks and other issues.
*/
private boolean clearReferencesLogFactoryRelease = true;
/**
* If an HttpClient keep-alive timer thread has been started by this web
* application and is still running, should Tomcat change the context class
* loader from the current {@link WebappClassLoader} to
* {@link WebappClassLoader#parent} to prevent a memory leak? Note that the
* keep-alive timer thread will stop on its own once the keep-alives all
* expire however, on a busy system that might not happen for some time.
*/
private boolean clearReferencesHttpClientKeepAliveThread = true;
// ------------------------------------------------------------- Properties
/**
* Get associated resources.
*/
public WebResourceRoot getResources() {
return this.resources;
}
/**
* Set associated resources.
*/
public void setResources(WebResourceRoot resources) {
this.resources = resources;
}
/**
* Return the context name for this class loader.
*/
public String getContextName() {
if (resources == null) {
return "Unknown";
} else {
return resources.getContext().getName();
}
}
/**
* Return the "delegate first" flag for this class loader.
*/
public boolean getDelegate() {
return (this.delegate);
}
/**
* Set the "delegate first" flag for this class loader.
* If this flag is true, this class loader delegates
* to the parent class loader
* <strong>before</strong> searching its own repositories, as
* in an ordinary (non-servlet) chain of Java class loaders.
* If set to <code>false</code> (the default),
* this class loader will search its own repositories first, and
* delegate to the parent only if the class or resource is not
* found locally, as per the servlet specification.
*
* @param delegate The new "delegate first" flag
*/
public void setDelegate(boolean delegate) {
this.delegate = delegate;
}
/**
* @return Returns the antiJARLocking.
*/
public boolean getAntiJARLocking() {
return antiJARLocking;
}
/**
* @param antiJARLocking The antiJARLocking to set.
*/
public void setAntiJARLocking(boolean antiJARLocking) {
this.antiJARLocking = antiJARLocking;
}
/**
* If there is a Java SecurityManager create a read FilePermission
* or JndiPermission for the file directory path.
*
* @param filepath file directory path
*/
public void addPermission(String filepath) {
if (filepath == null) {
return;
}
String path = filepath;
if (securityManager != null) {
Permission permission = null;
if (!path.endsWith(File.separator)) {
permission = new FilePermission(path, "read");
addPermission(permission);
path = path + File.separator;
}
permission = new FilePermission(path + "-", "read");
addPermission(permission);
}
}
/**
* If there is a Java SecurityManager create a read FilePermission
* or JndiPermission for URL.
*
* @param url URL for a file or directory on local system
*/
public void addPermission(URL url) {
if (url != null) {
addPermission(url.toString());
}
}
/**
* If there is a Java SecurityManager create a Permission.
*
* @param permission The permission
*/
public void addPermission(Permission permission) {
if ((securityManager != null) && (permission != null)) {
permissionList.add(permission);
}
}
/**
* Return the JAR path.
*/
public String getJarPath() {
return this.jarPath;
}
/**
* Change the Jar path.
*/
public void setJarPath(String jarPath) {
this.jarPath = jarPath;
}
/**
* Change the work directory.
*/
public void setWorkDir(File workDir) {
this.loaderDir = new File(workDir, "loader");
if (loaderDir == null) {
canonicalLoaderDir = null;
} else {
try {
canonicalLoaderDir = loaderDir.getCanonicalPath();
if (!canonicalLoaderDir.endsWith(File.separator)) {
canonicalLoaderDir += File.separator;
}
} catch (IOException ioe) {
canonicalLoaderDir = null;
}
}
}
/**
* Utility method for use in subclasses.
* Must be called before Lifecycle methods to have any effect.
*/
protected void setParentClassLoader(ClassLoader pcl) {
parent = pcl;
}
/**
* Return the clearReferencesStatic flag for this Context.
*/
public boolean getClearReferencesStatic() {
return (this.clearReferencesStatic);
}
/**
* Set the clearReferencesStatic feature for this Context.
*
* @param clearReferencesStatic The new flag value
*/
public void setClearReferencesStatic(boolean clearReferencesStatic) {
this.clearReferencesStatic = clearReferencesStatic;
}
/**
* Return the clearReferencesStopThreads flag for this Context.
*/
public boolean getClearReferencesStopThreads() {
return (this.clearReferencesStopThreads);
}
/**
* Set the clearReferencesStopThreads feature for this Context.
*
* @param clearReferencesStopThreads The new flag value
*/
public void setClearReferencesStopThreads(
boolean clearReferencesStopThreads) {
this.clearReferencesStopThreads = clearReferencesStopThreads;
}
/**
* Return the clearReferencesStopTimerThreads flag for this Context.
*/
public boolean getClearReferencesStopTimerThreads() {
return (this.clearReferencesStopTimerThreads);
}
/**
* Set the clearReferencesStopTimerThreads feature for this Context.
*
* @param clearReferencesStopTimerThreads The new flag value
*/
public void setClearReferencesStopTimerThreads(
boolean clearReferencesStopTimerThreads) {
this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads;
}
/**
* Return the clearReferencesLogFactoryRelease flag for this Context.
*/
public boolean getClearReferencesLogFactoryRelease() {
return (this.clearReferencesLogFactoryRelease);
}
/**
* Set the clearReferencesLogFactoryRelease feature for this Context.
*
* @param clearReferencesLogFactoryRelease The new flag value
*/
public void setClearReferencesLogFactoryRelease(
boolean clearReferencesLogFactoryRelease) {
this.clearReferencesLogFactoryRelease =
clearReferencesLogFactoryRelease;
}
/**
* Return the clearReferencesHttpClientKeepAliveThread flag for this
* Context.
*/
public boolean getClearReferencesHttpClientKeepAliveThread() {
return (this.clearReferencesHttpClientKeepAliveThread);
}
/**
* Set the clearReferencesHttpClientKeepAliveThread feature for this
* Context.
*
* @param clearReferencesHttpClientKeepAliveThread The new flag value
*/
public void setClearReferencesHttpClientKeepAliveThread(
boolean clearReferencesHttpClientKeepAliveThread) {
this.clearReferencesHttpClientKeepAliveThread =
clearReferencesHttpClientKeepAliveThread;
}
// ------------------------------------------------------- Reloader Methods
/**
* Set the place this ClassLoader can look for classes to be loaded.
*
* @param path Path of a source of classes to be loaded, such as a
* directory pathname, a JAR file pathname, or a ZIP file pathname
*
* @exception IllegalArgumentException if the specified repository is
* invalid or does not exist
*/
synchronized void setRepository(String path, WebResource repository) {
if (path == null)
return;
if (log.isDebugEnabled())
log.debug("addRepository(" + path + ")");
this.repositoryPath = path;
this.repository = repository;
}
synchronized void addJar(String jar, JarFile jarFile, File file)
throws IOException {
if (jar == null)
return;
if (jarFile == null)
return;
if (file == null)
return;
if (log.isDebugEnabled())
log.debug("addJar(" + jar + ")");
int i;
if ((jarPath != null) && (jar.startsWith(jarPath))) {
String jarName = jar.substring(jarPath.length());
while (jarName.startsWith("/"))
jarName = jarName.substring(1);
String[] result = new String[jarNames.length + 1];
for (i = 0; i < jarNames.length; i++) {
result[i] = jarNames[i];
}
result[jarNames.length] = jarName;
jarNames = result;
}
// Register the JAR for tracking
long lastModified = resources.getResource(jar).getLastModified();
String[] result = new String[paths.length + 1];
for (i = 0; i < paths.length; i++) {
result[i] = paths[i];
}
result[paths.length] = jar;
paths = result;
long[] result3 = new long[lastModifiedDates.length + 1];
for (i = 0; i < lastModifiedDates.length; i++) {
result3[i] = lastModifiedDates[i];
}
result3[lastModifiedDates.length] = lastModified;
lastModifiedDates = result3;
// If the JAR currently contains invalid classes, don't actually use it
// for classloading
if (!validateJarFile(file))
return;
JarFile[] result2 = new JarFile[jarFiles.length + 1];
for (i = 0; i < jarFiles.length; i++) {
result2[i] = jarFiles[i];
}
result2[jarFiles.length] = jarFile;
jarFiles = result2;
// Add the file to the list
File[] result4 = new File[jarRealFiles.length + 1];
for (i = 0; i < jarRealFiles.length; i++) {
result4[i] = jarRealFiles[i];
}
result4[jarRealFiles.length] = file;
jarRealFiles = result4;
}
/**
* Have one or more classes or resources been modified so that a reload
* is appropriate?
*/
public boolean modified() {
if (log.isDebugEnabled())
log.debug("modified()");
// Checking for modified loaded resources
int length = paths.length;
// A rare race condition can occur in the updates of the two arrays
// It's totally ok if the latest class added is not checked (it will
// be checked the next time
int length2 = lastModifiedDates.length;
if (length > length2)
length = length2;
for (int i = 0; i < length; i++) {
long lastModified =
resources.getResource(paths[i]).getLastModified();
if (lastModified != lastModifiedDates[i]) {
if( log.isDebugEnabled() )
log.debug(" Resource '" + paths[i]
+ "' was modified; Date is now: "
+ new java.util.Date(lastModified) + " Was: "
+ new java.util.Date(lastModifiedDates[i]));
return true;
}
}
length = jarNames.length;
// Check if JARs have been added or removed
if (getJarPath() != null) {
WebResource[] jars = resources.listResources(getJarPath());
int i = 0;
int j = 0;
for (; j < jars.length && i < length; j++) {
// Ignore non JARs present in the lib folder
String name = jars[j].getName();
if (!name.endsWith(".jar"))
continue;
if (!name.equals(jarNames[i])) {
// Missing JAR
log.info(" One or more JARs have been added : '"
+ name + "'");
return true;
}
i++;
}
if (j < jars.length ) {
for (; j < jars.length; j++) {
// Additional non-JAR files are allowed
if (jars[j].getName().endsWith(".jar")) {
// There was more JARs
log.info(" Additional JARs have been added");
return true;
}
}
} else if (i < jarNames.length) {
// There was less JARs
log.info(" One or more JARs have been removed");
return (true);
}
}
// No classes have been modified
return false;
}
/**
* Render a String representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("WebappClassLoader\r\n");
sb.append(" context: ");
sb.append(getContextName());
sb.append("\r\n");
sb.append(" delegate: ");
sb.append(delegate);
sb.append("\r\n");
sb.append(" repositoryPath: ");
sb.append(repositoryPath);
sb.append("\r\n");
if (this.parent != null) {
sb.append("----------> Parent Classloader:\r\n");
sb.append(this.parent.toString());
sb.append("\r\n");
}
return (sb.toString());
}
// ---------------------------------------------------- ClassLoader Methods
/**
* Expose this method for use by the unit tests.
*/
protected final Class<?> doDefineClass(String name, byte[] b, int off, int len,
ProtectionDomain protectionDomain) {
return super.defineClass(name, b, off, len, protectionDomain);
}
/**
* Find the specified class in our local repositories, if possible. If
* not found, throw <code>ClassNotFoundException</code>.
*
* @param name Name of the class to be loaded
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
if (log.isDebugEnabled())
log.debug(" findClass(" + name + ")");
// Cannot load anything from local repositories if class loader is stopped
if (!started) {
throw new ClassNotFoundException(name);
}
// (1) Permission to define this class when using a SecurityManager
if (securityManager != null) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
if (log.isTraceEnabled())
log.trace(" securityManager.checkPackageDefinition");
securityManager.checkPackageDefinition(name.substring(0,i));
} catch (Exception se) {
if (log.isTraceEnabled())
log.trace(" -->Exception-->ClassNotFoundException", se);
throw new ClassNotFoundException(name, se);
}
}
}
// Ask our superclass to locate this class, if possible
// (throws ClassNotFoundException if it is not found)
Class<?> clazz = null;
try {
if (log.isTraceEnabled())
log.trace(" findClassInternal(" + name + ")");
try {
clazz = findClassInternal(name);
} catch(ClassNotFoundException cnfe) {
if (log.isDebugEnabled())
log.debug(" --> Returning ClassNotFoundException");
throw cnfe;
} catch(AccessControlException ace) {
log.warn("WebappClassLoader.findClassInternal(" + name
+ ") security exception: " + ace.getMessage(), ace);
throw new ClassNotFoundException(name, ace);
} catch (RuntimeException e) {
if (log.isTraceEnabled())
log.trace(" -->RuntimeException Rethrown", e);
throw e;
}
} catch (ClassNotFoundException e) {
if (log.isTraceEnabled())
log.trace(" --> Passing on ClassNotFoundException");
throw e;
}
// Return the class we have located
if (log.isTraceEnabled())
log.debug(" Returning class " + clazz);
if (log.isTraceEnabled()) {
ClassLoader cl;
if (Globals.IS_SECURITY_ENABLED){
cl = AccessController.doPrivileged(
new PrivilegedGetClassLoader(clazz));
} else {
cl = clazz.getClassLoader();
}
log.debug(" Loaded by " + cl.toString());
}
return (clazz);
}
/**
* Find the specified resource in our local repository, and return a
* <code>URL</code> referring to it, or <code>null</code> if this resource
* cannot be found.
*
* @param name Name of the resource to be found
*/
@Override
public URL findResource(final String name) {
if (log.isDebugEnabled())
log.debug(" findResource(" + name + ")");
URL url = null;
ResourceEntry entry = resourceEntries.get(name);
if (entry == null) {
if (securityManager != null) {
PrivilegedAction<ResourceEntry> dp =
new PrivilegedFindResourceByName(name, name);
entry = AccessController.doPrivileged(dp);
} else {
entry = findResourceInternal(name, name);
}
}
if (entry != null) {
url = entry.source;
}
if (log.isDebugEnabled()) {
if (url != null)
log.debug(" --> Returning '" + url.toString() + "'");
else
log.debug(" --> Resource not found, returning null");
}
return (url);
}
/**
* Return an enumeration of <code>URLs</code> representing all of the
* resources with the given name. If no resources with this name are
* found, return an empty enumeration.
*
* @param name Name of the resources to be found
*
* @exception IOException if an input/output error occurs
*/
@Override
public Enumeration<URL> findResources(String name) throws IOException {
if (log.isDebugEnabled())
log.debug(" findResources(" + name + ")");
LinkedHashSet<URL> result = new LinkedHashSet<>();
int jarFilesLength = jarFiles.length;
if (repositoryPath != null) {
// Looking at the repository
WebResource[] webResources = resources.getResources(repositoryPath + name);
for (WebResource webResource : webResources) {
if (webResource.exists()) {
result.add(webResource.getURL());
}
}
}
// Looking at the JAR files
synchronized (jarFiles) {
if (openJARs()) {
for (int i = 0; i < jarFilesLength; i++) {
JarEntry jarEntry = jarFiles[i].getJarEntry(name);
if (jarEntry != null) {
try {
String jarFakeUrl = getURI(jarRealFiles[i]).toString();
jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name;
result.add(new URL(jarFakeUrl));
} catch (MalformedURLException e) {
// Ignore
}
}
}
}
}
final Iterator<URL> iterator = result.iterator();
return new Enumeration<URL>() {
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public URL nextElement() {
return iterator.next();
}
};
}
/**
* Find the resource with the given name. A resource is some data
* (images, audio, text, etc.) that can be accessed by class code in a
* way that is independent of the location of the code. The name of a
* resource is a "/"-separated path name that identifies the resource.
* If the resource cannot be found, return <code>null</code>.
* <p>
* This method searches according to the following algorithm, returning
* as soon as it finds the appropriate URL. If the resource cannot be
* found, returns <code>null</code>.
* <ul>
* <li>If the <code>delegate</code> property is set to <code>true</code>,
* call the <code>getResource()</code> method of the parent class
* loader, if any.</li>
* <li>Call <code>findResource()</code> to find this resource in our
* locally defined repositories.</li>
* <li>Call the <code>getResource()</code> method of the parent class
* loader, if any.</li>
* </ul>
*
* @param name Name of the resource to return a URL for
*/
@Override
public URL getResource(String name) {
if (log.isDebugEnabled())
log.debug("getResource(" + name + ")");
URL url = null;
// (1) Delegate to parent if requested
if (delegate) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
url = loader.getResource(name);
if (url != null) {
if (log.isDebugEnabled())
log.debug(" --> Returning '" + url.toString() + "'");
return (url);
}
}
// (2) Search local repositories
url = findResource(name);
if (url != null) {
// Locating the repository for special handling in the case
// of a JAR
if (antiJARLocking) {
ResourceEntry entry = resourceEntries.get(name);
try {
String repository = entry.codeBase.toString();
if ((repository.endsWith(".jar"))
&& (!(name.endsWith(".class")))) {
// Copy binary content to the work directory if not present
File resourceFile = new File(loaderDir, name);
url = getURI(resourceFile);
}
} catch (Exception e) {
// Ignore
}
}
if (log.isDebugEnabled())
log.debug(" --> Returning '" + url.toString() + "'");
return (url);
}
// (3) Delegate to parent unconditionally if not already attempted
if( !delegate ) {
ClassLoader loader = parent;
if (loader == null)
loader = system;
url = loader.getResource(name);
if (url != null) {
if (log.isDebugEnabled())
log.debug(" --> Returning '" + url.toString() + "'");
return (url);
}
}
// (4) Resource was not found
if (log.isDebugEnabled())
log.debug(" --> Resource not found, returning null");
return (null);
}
/**
* Find the resource with the given name, and return an input stream
* that can be used for reading it. The search order is as described
* for <code>getResource()</code>, after checking to see if the resource
* data has been previously cached. If the resource cannot be found,
* return <code>null</code>.
*
* @param name Name of the resource to return an input stream for
*/
@Override
public InputStream getResourceAsStream(String name) {
if (log.isDebugEnabled())
log.debug("getResourceAsStream(" + name + ")");
InputStream stream = null;
// (0) Check for a cached copy of this resource
stream = findLoadedResource(name);
if (stream != null) {
if (log.isDebugEnabled())
log.debug(" --> Returning stream from cache");
return (stream);
}
// (1) Delegate to parent if requested
if (delegate) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
stream = loader.getResourceAsStream(name);
if (stream != null) {
// FIXME - cache???
if (log.isDebugEnabled())
log.debug(" --> Returning stream from parent");
return (stream);
}
}
// (2) Search local repositories
if (log.isDebugEnabled())
log.debug(" Searching local repositories");
URL url = findResource(name);
if (url != null) {
// FIXME - cache???
if (log.isDebugEnabled())
log.debug(" --> Returning stream from local");
stream = findLoadedResource(name);
if (stream != null)
return (stream);
}
// (3) Delegate to parent unconditionally
if (!delegate) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader unconditionally " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
stream = loader.getResourceAsStream(name);
if (stream != null) {
// FIXME - cache???
if (log.isDebugEnabled())
log.debug(" --> Returning stream from parent");
return (stream);
}
}
// (4) Resource was not found
if (log.isDebugEnabled())
log.debug(" --> Resource not found, returning null");
return (null);
}
/**
* Load the class with the specified name. This method searches for
* classes in the same manner as <code>loadClass(String, boolean)</code>
* with <code>false</code> as the second argument.
*
* @param name Name of the class to be loaded
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return (loadClass(name, false));
}
/**
* Load the class with the specified name, searching using the following
* algorithm until it finds and returns the class. If the class cannot
* be found, returns <code>ClassNotFoundException</code>.
* <ul>
* <li>Call <code>findLoadedClass(String)</code> to check if the
* class has already been loaded. If it has, the same
* <code>Class</code> object is returned.</li>
* <li>If the <code>delegate</code> property is set to <code>true</code>,
* call the <code>loadClass()</code> method of the parent class
* loader, if any.</li>
* <li>Call <code>findClass()</code> to find this class in our locally
* defined repositories.</li>
* <li>Call the <code>loadClass()</code> method of our parent
* class loader, if any.</li>
* </ul>
* If the class was found using the above steps, and the
* <code>resolve</code> flag is <code>true</code>, this method will then
* call <code>resolveClass(Class)</code> on the resulting Class object.
*
* @param name Name of the class to be loaded
* @param resolve If <code>true</code> then resolve the class
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (log.isDebugEnabled())
log.debug("loadClass(" + name + ", " + resolve + ")");
Class<?> clazz = null;
// Log access to stopped classloader
if (!started) {
try {
throw new IllegalStateException();
} catch (IllegalStateException e) {
log.info(sm.getString("webappClassLoader.stopped", name), e);
}
}
// (0) Check our previously loaded local class cache
clazz = findLoadedClass0(name);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Returning class from cache");
if (resolve)
resolveClass(clazz);
return (clazz);
}
// (0.1) Check our previously loaded class cache
clazz = findLoadedClass(name);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Returning class from cache");
if (resolve)
resolveClass(clazz);
return (clazz);
}
// (0.2) Try loading the class with the system class loader, to prevent
// the webapp from overriding J2SE classes
try {
clazz = system.loadClass(name);
if (clazz != null) {
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
// (0.5) Permission to access this class when using a SecurityManager
if (securityManager != null) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
securityManager.checkPackageAccess(name.substring(0,i));
} catch (SecurityException se) {
String error = "Security Violation, attempt to use " +
"Restricted Class: " + name;
log.info(error, se);
throw new ClassNotFoundException(error, se);
}
}
}
boolean delegateLoad = delegate || filter(name);
// (1) Delegate to our parent if requested
if (delegateLoad) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader1 " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
try {
clazz = Class.forName(name, false, loader);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Loading class from parent");
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
}
// (2) Search local repositories
if (log.isDebugEnabled())
log.debug(" Searching local repositories");
try {
clazz = findClass(name);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Loading class from local repository");
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
// (3) Delegate to parent unconditionally
if (!delegateLoad) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader at end: " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
try {
clazz = Class.forName(name, false, loader);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Loading class from parent");
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
}
throw new ClassNotFoundException(name);
}
/**
* Get the Permissions for a CodeSource. If this instance
* of WebappClassLoader is for a web application context,
* add read FilePermission or JndiPermissions for the base
* directory (if unpacked),
* the context URL, and jar file resources.
*
* @param codeSource where the code was loaded from
* @return PermissionCollection for CodeSource
*/
@Override
protected PermissionCollection getPermissions(CodeSource codeSource) {
String codeUrl = codeSource.getLocation().toString();
PermissionCollection pc;
if ((pc = loaderPC.get(codeUrl)) == null) {
pc = super.getPermissions(codeSource);
if (pc != null) {
Iterator<Permission> perms = permissionList.iterator();
while (perms.hasNext()) {
Permission p = perms.next();
pc.add(p);
}
loaderPC.put(codeUrl,pc);
}
}
return (pc);
}
/**
* Returns the search path of URLs for loading classes and resources.
* This includes the original list of URLs specified to the constructor,
* along with any URLs subsequently appended by the addURL() method.
* @return the search path of URLs for loading classes and resources.
*/
@Override
public URL[] getURLs() {
if (repositoryURLs != null) {
return repositoryURLs.clone();
}
int resultLength;
if (repository == null) {
resultLength = jarRealFiles.length;
} else {
resultLength = jarRealFiles.length + 1;
}
int off = 0;
try {
URL[] urls = new URL[resultLength];
if (repository != null) {
urls[off ++] = repository.getURL();
}
for (File jarRealFile : jarRealFiles) {
urls[off++] = getURI(jarRealFile);
}
repositoryURLs = urls;
} catch (MalformedURLException e) {
repositoryURLs = new URL[0];
}
return repositoryURLs.clone();
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Add a lifecycle event listener to this component.
*
* @param listener The listener to add
*/
@Override
public void addLifecycleListener(LifecycleListener listener) {
// NOOP
}
/**
* Get the lifecycle listeners associated with this lifecycle. If this
* Lifecycle has no listeners registered, a zero-length array is returned.
*/
@Override
public LifecycleListener[] findLifecycleListeners() {
return new LifecycleListener[0];
}
/**
* Remove a lifecycle event listener from this component.
*
* @param listener The listener to remove
*/
@Override
public void removeLifecycleListener(LifecycleListener listener) {
// NOOP
}
/**
* Obtain the current state of the source component.
*
* @return The current state of the source component.
*/
@Override
public LifecycleState getState() {
return LifecycleState.NEW;
}
/**
* {@inheritDoc}
*/
@Override
public String getStateName() {
return getState().toString();
}
@Override
public void init() {
// NOOP
}
/**
* Start the class loader.
*
* @exception LifecycleException if a lifecycle error occurs
*/
@Override
public void start() throws LifecycleException {
started = true;
String encoding = null;
try {
encoding = System.getProperty("file.encoding");
} catch (SecurityException e) {
return;
}
if (encoding.indexOf("EBCDIC")!=-1) {
needConvert = true;
}
}
public boolean isStarted() {
return started;
}
/**
* Stop the class loader.
*
* @exception LifecycleException if a lifecycle error occurs
*/
@Override
public void stop() throws LifecycleException {
// Clearing references should be done before setting started to
// false, due to possible side effects
clearReferences();
started = false;
int length = jarFiles.length;
for (int i = 0; i < length; i++) {
try {
if (jarFiles[i] != null) {
jarFiles[i].close();
}
} catch (IOException e) {
// Ignore
}
jarFiles[i] = null;
}
notFoundResources.clear();
resourceEntries.clear();
resources = null;
repositoryPath = null;
repositoryURLs = null;
repository = null;
jarFiles = null;
jarRealFiles = null;
jarPath = null;
jarNames = null;
lastModifiedDates = null;
paths = null;
parent = null;
permissionList.clear();
loaderPC.clear();
if (loaderDir != null) {
deleteDir(loaderDir);
}
}
@Override
public void destroy() {
// NOOP
}
/**
* Used to periodically signal to the classloader to release
* JAR resources.
*/
public void closeJARs(boolean force) {
if (jarFiles.length > 0) {
synchronized (jarFiles) {
if (force || (System.currentTimeMillis()
> (lastJarAccessed + 90000))) {
for (int i = 0; i < jarFiles.length; i++) {
try {
if (jarFiles[i] != null) {
jarFiles[i].close();
jarFiles[i] = null;
}
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("Failed to close JAR", e);
}
}
}
}
}
}
}
// ------------------------------------------------------ Protected Methods
/**
* Clear references.
*/
protected void clearReferences() {
// De-register any remaining JDBC drivers
clearReferencesJdbc();
// Stop any threads the web application started
clearReferencesThreads();
// Check for leaks triggered by ThreadLocals loaded by this class loader
checkThreadLocalsForLeaks();
// Clear RMI Targets loaded by this class loader
clearReferencesRmiTargets();
// Null out any static or final fields from loaded classes,
// as a workaround for apparent garbage collection bugs
if (clearReferencesStatic) {
clearReferencesStaticFinal();
}
// Clear the IntrospectionUtils cache.
IntrospectionUtils.clear();
// Clear the classloader reference in common-logging
if (clearReferencesLogFactoryRelease) {
org.apache.juli.logging.LogFactory.release(this);
}
// Clear the resource bundle cache
// This shouldn't be necessary, the cache uses weak references but
// it has caused leaks. Oddly, using the leak detection code in
// standard host allows the class loader to be GC'd. This has been seen
// on Sun but not IBM JREs. Maybe a bug in Sun's GC impl?
clearReferencesResourceBundles();
// Clear the classloader reference in the VM's bean introspector
java.beans.Introspector.flushCaches();
// Clear any custom URLStreamHandlers
TomcatURLStreamHandlerFactory.release(this);
}
/**
* Deregister any JDBC drivers registered by the webapp that the webapp
* forgot. This is made unnecessary complex because a) DriverManager
* checks the class loader of the calling class (it would be much easier
* if it checked the context class loader) b) using reflection would
* create a dependency on the DriverManager implementation which can,
* and has, changed.
*
* We can't just create an instance of JdbcLeakPrevention as it will be
* loaded by the common class loader (since it's .class file is in the
* $CATALINA_HOME/lib directory). This would fail DriverManager's check
* on the class loader of the calling class. So, we load the bytes via
* our parent class loader but define the class with this class loader
* so the JdbcLeakPrevention looks like a webapp class to the
* DriverManager.
*
* If only apps cleaned up after themselves...
*/
private final void clearReferencesJdbc() {
InputStream is = getResourceAsStream(
"org/apache/catalina/loader/JdbcLeakPrevention.class");
// We know roughly how big the class will be (~ 1K) so allow 2k as a
// starting point
byte[] classBytes = new byte[2048];
int offset = 0;
try {
int read = is.read(classBytes, offset, classBytes.length-offset);
while (read > -1) {
offset += read;
if (offset == classBytes.length) {
// Buffer full - double size
byte[] tmp = new byte[classBytes.length * 2];
System.arraycopy(classBytes, 0, tmp, 0, classBytes.length);
classBytes = tmp;
}
read = is.read(classBytes, offset, classBytes.length-offset);
}
Class<?> lpClass =
defineClass("org.apache.catalina.loader.JdbcLeakPrevention",
classBytes, 0, offset, this.getClass().getProtectionDomain());
Object obj = lpClass.newInstance();
@SuppressWarnings("unchecked")
List<String> driverNames = (List<String>) obj.getClass().getMethod(
"clearJdbcDriverRegistrations").invoke(obj);
for (String name : driverNames) {
log.error(sm.getString("webappClassLoader.clearJdbc",
getContextName(), name));
}
} catch (Exception e) {
// So many things to go wrong above...
Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString(
"webappClassLoader.jdbcRemoveFailed", getContextName()), t);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
log.warn(sm.getString(
"webappClassLoader.jdbcRemoveStreamError",
getContextName()), ioe);
}
}
}
}
private final void clearReferencesStaticFinal() {
@SuppressWarnings("unchecked")
Collection<ResourceEntry> values =
((HashMap<String,ResourceEntry>) resourceEntries.clone()).values();
Iterator<ResourceEntry> loadedClasses = values.iterator();
//
// walk through all loaded class to trigger initialization for
// any uninitialized classes, otherwise initialization of
// one class may call a previously cleared class.
while(loadedClasses.hasNext()) {
ResourceEntry entry = loadedClasses.next();
if (entry.loadedClass != null) {
Class<?> clazz = entry.loadedClass;
try {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if(Modifier.isStatic(fields[i].getModifiers())) {
fields[i].get(null);
break;
}
}
} catch(Throwable t) {
// Ignore
}
}
}
loadedClasses = values.iterator();
while (loadedClasses.hasNext()) {
ResourceEntry entry = loadedClasses.next();
if (entry.loadedClass != null) {
Class<?> clazz = entry.loadedClass;
try {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int mods = field.getModifiers();
if (field.getType().isPrimitive()
|| (field.getName().indexOf("$") != -1)) {
continue;
}
if (Modifier.isStatic(mods)) {
try {
field.setAccessible(true);
if (Modifier.isFinal(mods)) {
if (!((field.getType().getName().startsWith("java."))
|| (field.getType().getName().startsWith("javax.")))) {
nullInstance(field.get(null));
}
} else {
field.set(null, null);
if (log.isDebugEnabled()) {
log.debug("Set field " + field.getName()
+ " to null in class " + clazz.getName());
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug("Could not set field " + field.getName()
+ " to null in class " + clazz.getName(), t);
}
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug("Could not clean fields for class " + clazz.getName(), t);
}
}
}
}
}
private void nullInstance(Object instance) {
if (instance == null) {
return;
}
Field[] fields = instance.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int mods = field.getModifiers();
if (field.getType().isPrimitive()
|| (field.getName().indexOf("$") != -1)) {
continue;
}
try {
field.setAccessible(true);
if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
// Doing something recursively is too risky
continue;
}
Object value = field.get(instance);
if (null != value) {
Class<? extends Object> valueClass = value.getClass();
if (!loadedByThisOrChild(valueClass)) {
if (log.isDebugEnabled()) {
log.debug("Not setting field " + field.getName() +
" to null in object of class " +
instance.getClass().getName() +
" because the referenced object was of type " +
valueClass.getName() +
" which was not loaded by this WebappClassLoader.");
}
} else {
field.set(instance, null);
if (log.isDebugEnabled()) {
log.debug("Set field " + field.getName()
+ " to null in class " + instance.getClass().getName());
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug("Could not set field " + field.getName()
+ " to null in object instance of class "
+ instance.getClass().getName(), t);
}
}
}
}
@SuppressWarnings("deprecation") // thread.stop()
private void clearReferencesThreads() {
Thread[] threads = getThreads();
// Iterate over the set of threads
for (Thread thread : threads) {
if (thread != null) {
ClassLoader ccl = thread.getContextClassLoader();
if (ccl == this) {
// Don't warn about this thread
if (thread == Thread.currentThread()) {
continue;
}
// JVM controlled threads
ThreadGroup tg = thread.getThreadGroup();
if (tg != null &&
JVM_THREAD_GROUP_NAMES.contains(tg.getName())) {
// HttpClient keep-alive threads
if (clearReferencesHttpClientKeepAliveThread &&
thread.getName().equals("Keep-Alive-Timer")) {
thread.setContextClassLoader(parent);
log.debug(sm.getString(
"webappClassLoader.checkThreadsHttpClient"));
}
// Don't warn about remaining JVM controlled threads
continue;
}
// Skip threads that have already died
if (!thread.isAlive()) {
continue;
}
// TimerThread can be stopped safely so treat separately
// "java.util.TimerThread" in Sun/Oracle JDK
// "java.util.Timer$TimerImpl" in Apache Harmony and in IBM JDK
if (thread.getClass().getName().startsWith("java.util.Timer") &&
clearReferencesStopTimerThreads) {
clearReferencesStopTimerThread(thread);
continue;
}
if (isRequestThread(thread)) {
log.error(sm.getString("webappClassLoader.warnRequestThread",
getContextName(), thread.getName()));
} else {
log.error(sm.getString("webappClassLoader.warnThread",
getContextName(), thread.getName()));
}
// Don't try an stop the threads unless explicitly
// configured to do so
if (!clearReferencesStopThreads) {
continue;
}
// If the thread has been started via an executor, try
// shutting down the executor
try {
// Runnable wrapped by Thread
// "target" in Sun/Oracle JDK
// "runnable" in IBM JDK
// "action" in Apache Harmony
Object target = null;
for (String fieldName : new String[] { "target",
"runnable", "action" }) {
try {
Field targetField = thread.getClass()
.getDeclaredField(fieldName);
targetField.setAccessible(true);
target = targetField.get(thread);
break;
} catch (NoSuchFieldException nfe) {
continue;
}
}
// "java.util.concurrent" code is in public domain,
// so all implementations are similar
if (target != null &&
target.getClass().getCanonicalName() != null
&& target.getClass().getCanonicalName().equals(
"java.util.concurrent.ThreadPoolExecutor.Worker")) {
Field executorField =
target.getClass().getDeclaredField("this$0");
executorField.setAccessible(true);
Object executor = executorField.get(target);
if (executor instanceof ThreadPoolExecutor) {
((ThreadPoolExecutor) executor).shutdownNow();
}
}
} catch (SecurityException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
} catch (NoSuchFieldException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
} catch (IllegalArgumentException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
} catch (IllegalAccessException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
}
// This method is deprecated and for good reason. This is
// very risky code but is the only option at this point.
// A *very* good reason for apps to do this clean-up
// themselves.
thread.stop();
}
}
}
}
/*
* Look at a threads stack trace to see if it is a request thread or not. It
* isn't perfect, but it should be good-enough for most cases.
*/
private boolean isRequestThread(Thread thread) {
StackTraceElement[] elements = thread.getStackTrace();
if (elements == null || elements.length == 0) {
// Must have stopped already. Too late to ignore it. Assume not a
// request processing thread.
return false;
}
// Step through the methods in reverse order looking for calls to any
// CoyoteAdapter method. All request threads will have this unless
// Tomcat has been heavily modified - in which case there isn't much we
// can do.
for (int i = 0; i < elements.length; i++) {
StackTraceElement element = elements[elements.length - (i+1)];
if ("org.apache.catalina.connector.CoyoteAdapter".equals(
element.getClassName())) {
return true;
}
}
return false;
}
private void clearReferencesStopTimerThread(Thread thread) {
// Need to get references to:
// in Sun/Oracle JDK:
// - newTasksMayBeScheduled field (in java.util.TimerThread)
// - queue field
// - queue.clear()
// in IBM JDK, Apache Harmony:
// - cancel() method (in java.util.Timer$TimerImpl)
try {
try {
Field newTasksMayBeScheduledField =
thread.getClass().getDeclaredField("newTasksMayBeScheduled");
newTasksMayBeScheduledField.setAccessible(true);
Field queueField = thread.getClass().getDeclaredField("queue");
queueField.setAccessible(true);
Object queue = queueField.get(thread);
Method clearMethod = queue.getClass().getDeclaredMethod("clear");
clearMethod.setAccessible(true);
synchronized(queue) {
newTasksMayBeScheduledField.setBoolean(thread, false);
clearMethod.invoke(queue);
queue.notify(); // In case queue was already empty.
}
}catch (NoSuchFieldException nfe){
Method cancelMethod = thread.getClass().getDeclaredMethod("cancel");
synchronized(thread) {
cancelMethod.setAccessible(true);
cancelMethod.invoke(thread);
}
}
log.error(sm.getString("webappClassLoader.warnTimerThread",
getContextName(), thread.getName()));
} catch (Exception e) {
// So many things to go wrong above...
Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString(
"webappClassLoader.stopTimerThreadFail",
thread.getName(), getContextName()), t);
}
}
private void checkThreadLocalsForLeaks() {
Thread[] threads = getThreads();
try {
// Make the fields in the Thread class that store ThreadLocals
// accessible
Field threadLocalsField =
Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Field inheritableThreadLocalsField =
Thread.class.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocalsField.setAccessible(true);
// Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
// accessible
Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = tlmClass.getDeclaredField("table");
tableField.setAccessible(true);
Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries");
expungeStaleEntriesMethod.setAccessible(true);
for (int i = 0; i < threads.length; i++) {
Object threadLocalMap;
if (threads[i] != null) {
// Clear the first map
threadLocalMap = threadLocalsField.get(threads[i]);
if (null != threadLocalMap){
expungeStaleEntriesMethod.invoke(threadLocalMap);
checkThreadLocalMapForLeaks(threadLocalMap, tableField);
}
// Clear the second map
threadLocalMap =inheritableThreadLocalsField.get(threads[i]);
if (null != threadLocalMap){
expungeStaleEntriesMethod.invoke(threadLocalMap);
checkThreadLocalMapForLeaks(threadLocalMap, tableField);
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaksFail",
getContextName()), t);
}
}
/**
* Analyzes the given thread local map object. Also pass in the field that
* points to the internal table to save re-calculating it on every
* call to this method.
*/
private void checkThreadLocalMapForLeaks(Object map,
Field internalTableField) throws IllegalAccessException,
NoSuchFieldException {
if (map != null) {
Object[] table = (Object[]) internalTableField.get(map);
if (table != null) {
for (int j =0; j < table.length; j++) {
Object obj = table[j];
if (obj != null) {
boolean potentialLeak = false;
// Check the key
Object key = ((Reference<?>) obj).get();
if (this.equals(key) || loadedByThisOrChild(key)) {
potentialLeak = true;
}
// Check the value
Field valueField =
obj.getClass().getDeclaredField("value");
valueField.setAccessible(true);
Object value = valueField.get(obj);
if (this.equals(value) || loadedByThisOrChild(value)) {
potentialLeak = true;
}
if (potentialLeak) {
Object[] args = new Object[5];
args[0] = getContextName();
if (key != null) {
args[1] = getPrettyClassName(key.getClass());
try {
args[2] = key.toString();
} catch (Exception e) {
log.error(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.badKey",
args[1]), e);
args[2] = sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.unknown");
}
}
if (value != null) {
args[3] = getPrettyClassName(value.getClass());
try {
args[4] = value.toString();
} catch (Exception e) {
log.error(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.badValue",
args[3]), e);
args[4] = sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.unknown");
}
}
if (value == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaksDebug",
args));
}
} else {
log.error(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks",
args));
}
}
}
}
}
}
}
private String getPrettyClassName(Class<?> clazz) {
String name = clazz.getCanonicalName();
if (name==null){
name = clazz.getName();
}
return name;
}
/**
* @param o object to test, may be null
* @return <code>true</code> if o has been loaded by the current classloader
* or one of its descendants.
*/
private boolean loadedByThisOrChild(Object o) {
if (o == null) {
return false;
}
Class<?> clazz;
if (o instanceof Class) {
clazz = (Class<?>) o;
} else {
clazz = o.getClass();
}
ClassLoader cl = clazz.getClassLoader();
while (cl != null) {
if (cl == this) {
return true;
}
cl = cl.getParent();
}
if (o instanceof Collection<?>) {
Iterator<?> iter = ((Collection<?>) o).iterator();
try {
while (iter.hasNext()) {
Object entry = iter.next();
if (loadedByThisOrChild(entry)) {
return true;
}
}
} catch (ConcurrentModificationException e) {
log.warn(sm.getString(
"webappClassLoader", clazz.getName(), getContextName()),
e);
}
}
return false;
}
/*
* Get the set of current threads as an array.
*/
private Thread[] getThreads() {
// Get the current thread group
ThreadGroup tg = Thread.currentThread( ).getThreadGroup( );
// Find the root thread group
while (tg.getParent() != null) {
tg = tg.getParent();
}
int threadCountGuess = tg.activeCount() + 50;
Thread[] threads = new Thread[threadCountGuess];
int threadCountActual = tg.enumerate(threads);
// Make sure we don't miss any threads
while (threadCountActual == threadCountGuess) {
threadCountGuess *=2;
threads = new Thread[threadCountGuess];
// Note tg.enumerate(Thread[]) silently ignores any threads that
// can't fit into the array
threadCountActual = tg.enumerate(threads);
}
return threads;
}
/**
* This depends on the internals of the Sun JVM so it does everything by
* reflection.
*/
private void clearReferencesRmiTargets() {
try {
// Need access to the ccl field of sun.rmi.transport.Target
Class<?> objectTargetClass =
Class.forName("sun.rmi.transport.Target");
Field cclField = objectTargetClass.getDeclaredField("ccl");
cclField.setAccessible(true);
// Clear the objTable map
Class<?> objectTableClass =
Class.forName("sun.rmi.transport.ObjectTable");
Field objTableField = objectTableClass.getDeclaredField("objTable");
objTableField.setAccessible(true);
Object objTable = objTableField.get(null);
if (objTable == null) {
return;
}
// Iterate over the values in the table
if (objTable instanceof Map<?,?>) {
Iterator<?> iter = ((Map<?,?>) objTable).values().iterator();
while (iter.hasNext()) {
Object obj = iter.next();
Object cclObject = cclField.get(obj);
if (this == cclObject) {
iter.remove();
}
}
}
// Clear the implTable map
Field implTableField = objectTableClass.getDeclaredField("implTable");
implTableField.setAccessible(true);
Object implTable = implTableField.get(null);
if (implTable == null) {
return;
}
// Iterate over the values in the table
if (implTable instanceof Map<?,?>) {
Iterator<?> iter = ((Map<?,?>) implTable).values().iterator();
while (iter.hasNext()) {
Object obj = iter.next();
Object cclObject = cclField.get(obj);
if (this == cclObject) {
iter.remove();
}
}
}
} catch (ClassNotFoundException e) {
log.info(sm.getString("webappClassLoader.clearRmiInfo",
getContextName()), e);
} catch (SecurityException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
} catch (NoSuchFieldException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
} catch (IllegalArgumentException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
} catch (IllegalAccessException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
}
}
/**
* Clear the {@link ResourceBundle} cache of any bundles loaded by this
* class loader or any class loader where this loader is a parent class
* loader. Whilst {@link ResourceBundle#clearCache()} could be used there
* are complications around the
* {@link org.apache.jasper.servlet.JasperLoader} that mean a reflection
* based approach is more likely to be complete.
*
* The ResourceBundle is using WeakReferences so it shouldn't be pinning the
* class loader in memory. However, it is. Therefore clear ou the
* references.
*/
private void clearReferencesResourceBundles() {
// Get a reference to the cache
try {
Field cacheListField =
ResourceBundle.class.getDeclaredField("cacheList");
cacheListField.setAccessible(true);
// Java 6 uses ConcurrentMap
// Java 5 uses SoftCache extends Abstract Map
// So use Map and it *should* work with both
Map<?,?> cacheList = (Map<?,?>) cacheListField.get(null);
// Get the keys (loader references are in the key)
Set<?> keys = cacheList.keySet();
Field loaderRefField = null;
// Iterate over the keys looking at the loader instances
Iterator<?> keysIter = keys.iterator();
int countRemoved = 0;
while (keysIter.hasNext()) {
Object key = keysIter.next();
if (loaderRefField == null) {
loaderRefField =
key.getClass().getDeclaredField("loaderRef");
loaderRefField.setAccessible(true);
}
WeakReference<?> loaderRef =
(WeakReference<?>) loaderRefField.get(key);
ClassLoader loader = (ClassLoader) loaderRef.get();
while (loader != null && loader != this) {
loader = loader.getParent();
}
if (loader != null) {
keysIter.remove();
countRemoved++;
}
}
if (countRemoved > 0 && log.isDebugEnabled()) {
log.debug(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesCount",
Integer.valueOf(countRemoved), getContextName()));
}
} catch (SecurityException e) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
} catch (NoSuchFieldException e) {
if (System.getProperty("java.vendor").startsWith("Sun")) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
} else {
log.debug(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
}
} catch (IllegalArgumentException e) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
} catch (IllegalAccessException e) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
}
}
/**
* Used to periodically signal to the classloader to release JAR resources.
*/
protected boolean openJARs() {
if (started && (jarFiles.length > 0)) {
lastJarAccessed = System.currentTimeMillis();
if (jarFiles[0] == null) {
for (int i = 0; i < jarFiles.length; i++) {
try {
jarFiles[i] = new JarFile(jarRealFiles[i]);
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("Failed to open JAR", e);
}
return false;
}
}
}
}
return true;
}
/**
* Find specified class in local repositories.
*
* @return the loaded class, or null if the class isn't found
*/
protected Class<?> findClassInternal(String name)
throws ClassNotFoundException {
if (!validate(name))
throw new ClassNotFoundException(name);
String tempPath = name.replace('.', '/');
String classPath = tempPath + ".class";
ResourceEntry entry = null;
if (securityManager != null) {
PrivilegedAction<ResourceEntry> dp =
new PrivilegedFindResourceByName(name, classPath);
entry = AccessController.doPrivileged(dp);
} else {
entry = findResourceInternal(name, classPath);
}
if (entry == null)
throw new ClassNotFoundException(name);
Class<?> clazz = entry.loadedClass;
if (clazz != null)
return clazz;
synchronized (this) {
clazz = entry.loadedClass;
if (clazz != null)
return clazz;
if (entry.binaryContent == null)
throw new ClassNotFoundException(name);
// Looking up the package
String packageName = null;
int pos = name.lastIndexOf('.');
if (pos != -1)
packageName = name.substring(0, pos);
Package pkg = null;
if (packageName != null) {
pkg = getPackage(packageName);
// Define the package (if null)
if (pkg == null) {
try {
if (entry.manifest == null) {
definePackage(packageName, null, null, null, null,
null, null, null);
} else {
definePackage(packageName, entry.manifest,
entry.codeBase);
}
} catch (IllegalArgumentException e) {
// Ignore: normal error due to dual definition of package
}
pkg = getPackage(packageName);
}
}
if (securityManager != null) {
// Checking sealing
if (pkg != null) {
boolean sealCheck = true;
if (pkg.isSealed()) {
sealCheck = pkg.isSealed(entry.codeBase);
} else {
sealCheck = (entry.manifest == null)
|| !isPackageSealed(packageName, entry.manifest);
}
if (!sealCheck)
throw new SecurityException
("Sealing violation loading " + name + " : Package "
+ packageName + " is sealed.");
}
}
try {
clazz = defineClass(name, entry.binaryContent, 0,
entry.binaryContent.length,
new CodeSource(entry.codeBase, entry.certificates));
} catch (UnsupportedClassVersionError ucve) {
throw new UnsupportedClassVersionError(
ucve.getLocalizedMessage() + " " +
sm.getString("webappClassLoader.wrongVersion",
name));
}
entry.loadedClass = clazz;
entry.binaryContent = null;
entry.source = null;
entry.codeBase = null;
entry.manifest = null;
entry.certificates = null;
}
return clazz;
}
/**
* Find specified resource in local repositories.
*
* @return the loaded resource, or null if the resource isn't found
*/
protected ResourceEntry findResourceInternal(String name, String path) {
if (!started) {
log.info(sm.getString("webappClassLoader.stopped", name));
return null;
}
if ((name == null) || (path == null))
return null;
ResourceEntry entry = resourceEntries.get(name);
if (entry != null)
return entry;
int contentLength = -1;
InputStream binaryStream = null;
boolean isClassResource = path.endsWith(".class");
int jarFilesLength = jarFiles.length;
WebResource resource = null;
boolean fileNeedConvert = false;
if (repositoryPath != null) {
String fullPath = repositoryPath + path;
resource = resources.getResource(fullPath);
if (resource.exists()) {
contentLength = (int) resource.getContentLength();
entry = new ResourceEntry();
entry.source = resource.getURL();
entry.codeBase = entry.source;
entry.lastModified = resource.getLastModified();
binaryStream = resource.getInputStream();
if (needConvert) {
if (path.endsWith(".properties")) {
fileNeedConvert = true;
}
}
// Register the full path for modification checking
// Note: Only syncing on a 'constant' object is needed
synchronized (allPermission) {
int j;
long[] result2 =
new long[lastModifiedDates.length + 1];
for (j = 0; j < lastModifiedDates.length; j++) {
result2[j] = lastModifiedDates[j];
}
result2[lastModifiedDates.length] = entry.lastModified;
lastModifiedDates = result2;
String[] result = new String[paths.length + 1];
for (j = 0; j < paths.length; j++) {
result[j] = paths[j];
}
result[paths.length] = fullPath;
paths = result;
}
}
}
if ((entry == null) && (notFoundResources.containsKey(name)))
return null;
JarEntry jarEntry = null;
synchronized (jarFiles) {
try {
if (!openJARs()) {
return null;
}
for (int i = 0; (entry == null) && (i < jarFilesLength); i++) {
jarEntry = jarFiles[i].getJarEntry(path);
if (jarEntry != null) {
entry = new ResourceEntry();
try {
entry.codeBase = getURI(jarRealFiles[i]);
String jarFakeUrl = entry.codeBase.toString();
jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path;
entry.source = new URL(jarFakeUrl);
entry.lastModified = jarRealFiles[i].lastModified();
} catch (MalformedURLException e) {
return null;
}
contentLength = (int) jarEntry.getSize();
try {
entry.manifest = jarFiles[i].getManifest();
binaryStream = jarFiles[i].getInputStream(jarEntry);
} catch (IOException e) {
return null;
}
// Extract resources contained in JAR to the workdir
if (antiJARLocking && !(path.endsWith(".class"))) {
byte[] buf = new byte[1024];
File resourceFile = new File
(loaderDir, jarEntry.getName());
if (!resourceFile.exists()) {
Enumeration<JarEntry> entries =
jarFiles[i].entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry2 = entries.nextElement();
if (!(jarEntry2.isDirectory())
&& (!jarEntry2.getName().endsWith
(".class"))) {
resourceFile = new File
(loaderDir, jarEntry2.getName());
try {
if (!resourceFile.getCanonicalPath().startsWith(
canonicalLoaderDir)) {
throw new IllegalArgumentException(
sm.getString("webappClassLoader.illegalJarPath",
jarEntry2.getName()));
}
} catch (IOException ioe) {
throw new IllegalArgumentException(
sm.getString("webappClassLoader.validationErrorJarPath",
jarEntry2.getName()), ioe);
}
File parentFile = resourceFile.getParentFile();
if (!parentFile.mkdirs() && !parentFile.exists()) {
// Ignore the error (like the IOExceptions below)
}
FileOutputStream os = null;
InputStream is = null;
try {
is = jarFiles[i].getInputStream
(jarEntry2);
os = new FileOutputStream
(resourceFile);
while (true) {
int n = is.read(buf);
if (n <= 0) {
break;
}
os.write(buf, 0, n);
}
resourceFile.setLastModified(
jarEntry2.getTime());
} catch (IOException e) {
// Ignore
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
// Ignore
}
}
}
}
}
}
}
}
if (entry == null) {
synchronized (notFoundResources) {
notFoundResources.put(name, name);
}
return null;
}
/* Only cache the binary content if there is some content
* available and either:
* a) It is a class file since the binary content is only cached
* until the class has been loaded
* or
* b) The file needs conversion to address encoding issues (see
* below)
*
* In all other cases do not cache the content to prevent
* excessive memory usage if large resources are present (see
* https://issues.apache.org/bugzilla/show_bug.cgi?id=53081).
*/
if (binaryStream != null &&
(isClassResource || fileNeedConvert)) {
byte[] binaryContent = new byte[contentLength];
int pos = 0;
try {
while (true) {
int n = binaryStream.read(binaryContent, pos,
binaryContent.length - pos);
if (n <= 0)
break;
pos += n;
}
} catch (IOException e) {
log.error(sm.getString("webappClassLoader.readError", name), e);
return null;
}
if (fileNeedConvert) {
// Workaround for certain files on platforms that use
// EBCDIC encoding, when they are read through FileInputStream.
// See commit message of rev.303915 for details
// http://svn.apache.org/viewvc?view=revision&revision=303915
String str = new String(binaryContent,0,pos);
try {
binaryContent = str.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
return null;
}
}
entry.binaryContent = binaryContent;
// The certificates are only available after the JarEntry
// associated input stream has been fully read
if (jarEntry != null) {
entry.certificates = jarEntry.getCertificates();
}
}
} finally {
if (binaryStream != null) {
try {
binaryStream.close();
} catch (IOException e) { /* Ignore */}
}
}
}
// Add the entry in the local resource repository
synchronized (resourceEntries) {
// Ensures that all the threads which may be in a race to load
// a particular class all end up with the same ResourceEntry
// instance
ResourceEntry entry2 = resourceEntries.get(name);
if (entry2 == null) {
resourceEntries.put(name, entry);
} else {
entry = entry2;
}
}
return entry;
}
/**
* Returns true if the specified package name is sealed according to the
* given manifest.
*/
protected boolean isPackageSealed(String name, Manifest man) {
String path = name.replace('.', '/') + '/';
Attributes attr = man.getAttributes(path);
String sealed = null;
if (attr != null) {
sealed = attr.getValue(Name.SEALED);
}
if (sealed == null) {
if ((attr = man.getMainAttributes()) != null) {
sealed = attr.getValue(Name.SEALED);
}
}
return "true".equalsIgnoreCase(sealed);
}
/**
* Finds the resource with the given name if it has previously been
* loaded and cached by this class loader, and return an input stream
* to the resource data. If this resource has not been cached, return
* <code>null</code>.
*
* @param name Name of the resource to return
*/
protected InputStream findLoadedResource(String name) {
ResourceEntry entry = resourceEntries.get(name);
if (entry != null) {
if (entry.binaryContent != null)
return new ByteArrayInputStream(entry.binaryContent);
else {
try {
return entry.source.openStream();
} catch (IOException ioe) {
// Ignore
}
}
}
return null;
}
/**
* Finds the class with the given name if it has previously been
* loaded and cached by this class loader, and return the Class object.
* If this class has not been cached, return <code>null</code>.
*
* @param name Name of the resource to return
*/
protected Class<?> findLoadedClass0(String name) {
ResourceEntry entry = resourceEntries.get(name);
if (entry != null) {
return entry.loadedClass;
}
return (null); // FIXME - findLoadedResource()
}
/**
* Refresh the system policy file, to pick up eventual changes.
*/
protected void refreshPolicy() {
try {
// The policy file may have been modified to adjust
// permissions, so we're reloading it when loading or
// reloading a Context
Policy policy = Policy.getPolicy();
policy.refresh();
} catch (AccessControlException e) {
// Some policy files may restrict this, even for the core,
// so this exception is ignored
}
}
/**
* Filter classes.
*
* @param name class name
* @return true if the class should be filtered
*/
protected boolean filter(String name) {
if (name == null)
return false;
// Looking up the package
String packageName = null;
int pos = name.lastIndexOf('.');
if (pos != -1)
packageName = name.substring(0, pos);
else
return false;
for (int i = 0; i < packageTriggers.length; i++) {
if (packageName.startsWith(packageTriggers[i]))
return true;
}
return false;
}
/**
* Validate a classname. As per SRV.9.7.2, we must restrict loading of
* classes from J2SE (java.*) and most classes of the servlet API
* (javax.servlet.*). That should enhance robustness and prevent a number
* of user error (where an older version of servlet.jar would be present
* in /WEB-INF/lib).
*
* @param name class name
* @return true if the name is valid
*/
protected boolean validate(String name) {
// Need to be careful with order here
if (name == null) {
// Can't load a class without a name
return false;
}
if (name.startsWith("java.")) {
// Must never load java.* classes
return false;
}
if (name.startsWith("javax.servlet.jsp.jstl")) {
// OK for web apps to package JSTL
return true;
}
if (name.startsWith("javax.servlet.")) {
// Web apps should never package any other Servlet or JSP classes
return false;
}
if (name.startsWith("javax.el")) {
// Must never load javax.el.* classes
return false;
}
// Assume everything else is OK
return true;
}
/**
* Check the specified JAR file, and return <code>true</code> if it does
* not contain any of the trigger classes.
*
* @param file The JAR file to be checked
*
* @exception IOException if an input/output error occurs
*/
protected boolean validateJarFile(File file)
throws IOException {
if (triggers == null)
return (true);
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
for (int i = 0; i < triggers.length; i++) {
Class<?> clazz = null;
try {
if (parent != null) {
clazz = parent.loadClass(triggers[i]);
} else {
clazz = Class.forName(triggers[i]);
}
} catch (Exception e) {
clazz = null;
}
if (clazz == null)
continue;
String name = triggers[i].replace('.', '/') + ".class";
if (log.isDebugEnabled())
log.debug(" Checking for " + name);
JarEntry jarEntry = jarFile.getJarEntry(name);
if (jarEntry != null) {
log.info("validateJarFile(" + file +
") - jar not loaded. See Servlet Spec 2.3, "
+ "section 9.7.2. Offending class: " + name);
return false;
}
}
return true;
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
/**
* Get the URI for the given file.
*/
protected URL getURI(File file)
throws MalformedURLException {
File realFile = file;
try {
realFile = realFile.getCanonicalFile();
} catch (IOException e) {
// Ignore
}
return realFile.toURI().toURL();
}
/**
* Delete the specified directory, including all of its contents and
* subdirectories recursively.
*
* @param dir File object representing the directory to be deleted
*/
protected static void deleteDir(File dir) {
String files[] = dir.list();
if (files == null) {
files = new String[0];
}
for (int i = 0; i < files.length; i++) {
File file = new File(dir, files[i]);
if (file.isDirectory()) {
deleteDir(file);
} else {
file.delete();
}
}
dir.delete();
}
}
|
55,317
|
Bug 55317 Facilitate weaving by allowing ClassFileTransformer to be added to WebppClassLoader
| null |
resolved fixed
|
dd0cba7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-26T22:55:22Z
| 2013-07-28T11:13:20Z
|
java/org/apache/tomcat/InstrumentableClassLoader.java
| |
55,317
|
Bug 55317 Facilitate weaving by allowing ClassFileTransformer to be added to WebppClassLoader
| null |
resolved fixed
|
dd0cba7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-26T22:55:22Z
| 2013-07-28T11:13:20Z
|
test/org/apache/catalina/loader/TestWebappClassLoaderWeaving.java
| |
55,317
|
Bug 55317 Facilitate weaving by allowing ClassFileTransformer to be added to WebppClassLoader
| null |
resolved fixed
|
dd0cba7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-26T22:55:22Z
| 2013-07-28T11:13:20Z
|
test/org/apache/catalina/loader/TesterNeverWeavedClass.java
| |
55,317
|
Bug 55317 Facilitate weaving by allowing ClassFileTransformer to be added to WebppClassLoader
| null |
resolved fixed
|
dd0cba7
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-09-26T22:55:22Z
| 2013-07-28T11:13:20Z
|
test/org/apache/catalina/loader/TesterUnweavedClass.java
| |
55,629
|
Bug 55629 StatusManagerServlet does not remove JMX notification listener
|
StatusManagerServlet.destroy should call mBeanServer.removeNotificationListener because init method call mBeanServer.addNotificationListener.
|
resolved fixed
|
95faaec
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-07T08:36:23Z
| 2013-10-05T21:53:20Z
|
java/org/apache/catalina/manager/StatusManagerServlet.java
|
/*
* 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.manager;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import javax.management.MBeanServer;
import javax.management.MBeanServerNotification;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.util.ServerInfo;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.res.StringManager;
/**
* This servlet will display a complete status of the HTTP/1.1 connector.
*
* @author Remy Maucherat
* @version $Id$
*/
public class StatusManagerServlet
extends HttpServlet implements NotificationListener {
private static final long serialVersionUID = 1L;
// ----------------------------------------------------- Instance Variables
/**
* MBean server.
*/
protected MBeanServer mBeanServer = null;
/**
* Vector of protocol handlers object names.
*/
protected final Vector<ObjectName> protocolHandlers = new Vector<>();
/**
* Vector of thread pools object names.
*/
protected final Vector<ObjectName> threadPools = new Vector<>();
/**
* Vector of request processors object names.
*/
protected final Vector<ObjectName> requestProcessors = new Vector<>();
/**
* Vector of global request processors object names.
*/
protected final Vector<ObjectName> globalRequestProcessors = new Vector<>();
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
// --------------------------------------------------------- Public Methods
/**
* Initialize this servlet.
*/
@Override
public void init() throws ServletException {
// Retrieve the MBean server
mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
try {
// Query protocol handlers
String onStr = "*:type=ProtocolHandler,*";
ObjectName objectName = new ObjectName(onStr);
Set<ObjectInstance> set = mBeanServer.queryMBeans(objectName, null);
Iterator<ObjectInstance> iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
protocolHandlers.addElement(oi.getObjectName());
}
// Query Thread Pools
onStr = "*:type=ThreadPool,*";
objectName = new ObjectName(onStr);
set = mBeanServer.queryMBeans(objectName, null);
iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
threadPools.addElement(oi.getObjectName());
}
// Query Global Request Processors
onStr = "*:type=GlobalRequestProcessor,*";
objectName = new ObjectName(onStr);
set = mBeanServer.queryMBeans(objectName, null);
iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
globalRequestProcessors.addElement(oi.getObjectName());
}
// Query Request Processors
onStr = "*:type=RequestProcessor,*";
objectName = new ObjectName(onStr);
set = mBeanServer.queryMBeans(objectName, null);
iterator = set.iterator();
while (iterator.hasNext()) {
ObjectInstance oi = iterator.next();
requestProcessors.addElement(oi.getObjectName());
}
// Register with MBean server
onStr = "JMImplementation:type=MBeanServerDelegate";
objectName = new ObjectName(onStr);
mBeanServer.addNotificationListener(objectName, this, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Finalize this servlet.
*/
@Override
public void destroy() {
// No actions necessary
}
/**
* Process a GET request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// mode is flag for HTML or XML output
int mode = 0;
// if ?XML=true, set the mode to XML
if (request.getParameter("XML") != null
&& request.getParameter("XML").equals("true")) {
mode = 1;
}
StatusTransformer.setContentType(response, mode);
PrintWriter writer = response.getWriter();
boolean completeStatus = false;
if ((request.getPathInfo() != null)
&& (request.getPathInfo().equals("/all"))) {
completeStatus = true;
}
// use StatusTransformer to output status
Object[] args = new Object[1];
args[0] = request.getContextPath();
StatusTransformer.writeHeader(writer,args,mode);
// Body Header Section
args = new Object[2];
args[0] = request.getContextPath();
if (completeStatus) {
args[1] = sm.getString("statusServlet.complete");
} else {
args[1] = sm.getString("statusServlet.title");
}
// use StatusTransformer to output status
StatusTransformer.writeBody(writer,args,mode);
// Manager Section
args = new Object[9];
args[0] = sm.getString("htmlManagerServlet.manager");
args[1] = response.encodeURL(request.getContextPath() + "/html/list");
args[2] = sm.getString("htmlManagerServlet.list");
args[3] = response.encodeURL
(request.getContextPath() + "/" +
sm.getString("htmlManagerServlet.helpHtmlManagerFile"));
args[4] = sm.getString("htmlManagerServlet.helpHtmlManager");
args[5] = response.encodeURL
(request.getContextPath() + "/" +
sm.getString("htmlManagerServlet.helpManagerFile"));
args[6] = sm.getString("htmlManagerServlet.helpManager");
if (completeStatus) {
args[7] = response.encodeURL
(request.getContextPath() + "/status");
args[8] = sm.getString("statusServlet.title");
} else {
args[7] = response.encodeURL
(request.getContextPath() + "/status/all");
args[8] = sm.getString("statusServlet.complete");
}
// use StatusTransformer to output status
StatusTransformer.writeManager(writer,args,mode);
// Server Header Section
args = new Object[9];
args[0] = sm.getString("htmlManagerServlet.serverTitle");
args[1] = sm.getString("htmlManagerServlet.serverVersion");
args[2] = sm.getString("htmlManagerServlet.serverJVMVersion");
args[3] = sm.getString("htmlManagerServlet.serverJVMVendor");
args[4] = sm.getString("htmlManagerServlet.serverOSName");
args[5] = sm.getString("htmlManagerServlet.serverOSVersion");
args[6] = sm.getString("htmlManagerServlet.serverOSArch");
args[7] = sm.getString("htmlManagerServlet.serverHostname");
args[8] = sm.getString("htmlManagerServlet.serverIPAddress");
// use StatusTransformer to output status
StatusTransformer.writePageHeading(writer,args,mode);
// Server Row Section
args = new Object[8];
args[0] = ServerInfo.getServerInfo();
args[1] = System.getProperty("java.runtime.version");
args[2] = System.getProperty("java.vm.vendor");
args[3] = System.getProperty("os.name");
args[4] = System.getProperty("os.version");
args[5] = System.getProperty("os.arch");
try {
InetAddress address = InetAddress.getLocalHost();
args[6] = address.getHostName();
args[7] = address.getHostAddress();
} catch (UnknownHostException e) {
args[6] = "-";
args[7] = "-";
}
// use StatusTransformer to output status
StatusTransformer.writeServerInfo(writer, args, mode);
try {
// Display operating system statistics using APR if available
StatusTransformer.writeOSState(writer,mode);
// Display virtual machine statistics
StatusTransformer.writeVMState(writer,mode);
Enumeration<ObjectName> enumeration = threadPools.elements();
while (enumeration.hasMoreElements()) {
ObjectName objectName = enumeration.nextElement();
String name = objectName.getKeyProperty("name");
// use StatusTransformer to output status
StatusTransformer.writeConnectorState
(writer, objectName,
name, mBeanServer, globalRequestProcessors,
requestProcessors, mode);
}
if ((request.getPathInfo() != null)
&& (request.getPathInfo().equals("/all"))) {
// Note: Retrieving the full status is much slower
// use StatusTransformer to output status
StatusTransformer.writeDetailedState
(writer, mBeanServer, mode);
}
} catch (Exception e) {
throw new ServletException(e);
}
// use StatusTransformer to output status
StatusTransformer.writeFooter(writer, mode);
}
// ------------------------------------------- NotificationListener Methods
@Override
public void handleNotification(Notification notification,
java.lang.Object handback) {
if (notification instanceof MBeanServerNotification) {
ObjectName objectName =
((MBeanServerNotification) notification).getMBeanName();
if (notification.getType().equals
(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
String type = objectName.getKeyProperty("type");
if (type != null) {
if (type.equals("ProtocolHandler")) {
protocolHandlers.addElement(objectName);
} else if (type.equals("ThreadPool")) {
threadPools.addElement(objectName);
} else if (type.equals("GlobalRequestProcessor")) {
globalRequestProcessors.addElement(objectName);
} else if (type.equals("RequestProcessor")) {
requestProcessors.addElement(objectName);
}
}
} else if (notification.getType().equals
(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
String type = objectName.getKeyProperty("type");
if (type != null) {
if (type.equals("ProtocolHandler")) {
protocolHandlers.removeElement(objectName);
} else if (type.equals("ThreadPool")) {
threadPools.removeElement(objectName);
} else if (type.equals("GlobalRequestProcessor")) {
globalRequestProcessors.removeElement(objectName);
} else if (type.equals("RequestProcessor")) {
requestProcessors.removeElement(objectName);
}
}
String j2eeType = objectName.getKeyProperty("j2eeType");
if (j2eeType != null) {
}
}
}
}
}
|
55,630
|
Bug 55630 clean way to avoid setURLStreamHandlerFactory call
|
A current method is to set WebappLoader.first via reflection (because private). I think the setURLStreamHandlerFactory should be move to Catalina.start ('first' static field can be move in Catalina). So we could have a static method in Catalina to prevent setURLStreamHandlerFactory call while first starting.
|
resolved fixed
|
bd56eea
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-07T18:49:56Z
| 2013-10-05T21:53:20Z
|
java/org/apache/catalina/webresources/TomcatURLStreamHandlerFactory.java
|
/*
* 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.webresources;
import java.net.URL;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
// TODO Add hook to enable user registered factories to be unloaded on web
// application stop.
public class TomcatURLStreamHandlerFactory implements URLStreamHandlerFactory{
private static final String WAR_PROTOCOL = "war";
// Singleton instance
private static TomcatURLStreamHandlerFactory instance =
new TomcatURLStreamHandlerFactory();
/**
* Obtain a reference to the singleton instance,
*/
public static TomcatURLStreamHandlerFactory getInstance() {
return instance;
}
// List of factories for application defined stream handler factories.
private List<URLStreamHandlerFactory> userFactories =
new CopyOnWriteArrayList<>();
/**
* Register this factory with the JVM. May be called more than once. The
* implementation ensures that registration only occurs once.
*/
public static void register() {
// Calling this method loads this class which in turn triggers all the
// necessary registration.
}
/**
* Since the JVM only allows a single call to
* {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)} and
* Tomcat needs to register a handler, provide a mechanism to allow
* applications to register their own handlers.
*/
public static void addUserFactory(URLStreamHandlerFactory factory) {
instance.userFactories.add(factory);
}
/**
* Release references to any user provided factories that have been loaded
* using the provided class loader. Called during web application stop to
* prevent memory leaks.
*/
public static void release(ClassLoader classLoader) {
Iterator<URLStreamHandlerFactory> iter = instance.userFactories.iterator();
while (iter.hasNext()) {
ClassLoader factoryLoader = iter.next().getClass().getClassLoader();
while (factoryLoader != null) {
if (classLoader.equals(factoryLoader)) {
iter.remove();
break;
}
factoryLoader = factoryLoader.getParent();
}
}
}
private TomcatURLStreamHandlerFactory() {
// Hide default constructor
// Singleton pattern to ensure there is only one instance of this
// factory
URL.setURLStreamHandlerFactory(this);
}
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
// Tomcat's handler always takes priority so applications can't override
// it.
if (WAR_PROTOCOL.equals(protocol)) {
return new WarURLStreamHandler();
}
// Application handlers
for (URLStreamHandlerFactory factory : userFactories) {
URLStreamHandler handler =
factory.createURLStreamHandler(protocol);
if (handler != null) {
return handler;
}
}
// Unknown protocol
return null;
}
}
|
55,642
|
Bug 55642 TagPluginManager isConstantAttribute broken
|
Function isConstantAttribute in TagPluginManager seems to be be broken. For value "order.status" it returns false. And for value "${order.state.name}" it returns true. According to javadoc it should be exact opposite. Problem seems to be in Node.isLiteral function. "el!= null" should probably be "el== null" But this function is being used elsewhere. /** * @return true if the attribute is specified and its value is a * translation-time constant. */ public boolean TagPluginManager.isConstantAttribute(String attribute){ Node.JspAttribute attr = getNodeAttribute(attribute); if (attr == null) return false; return attr.isLiteral(); } /** * @return true if the value is a string literal known at translation * time. */ public boolean isLiteral() { return !expression && (el != null) && !namedAttribute; }
|
resolved fixed
|
af49b44
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-09T14:33:39Z
| 2013-10-09T17:33:20Z
|
java/org/apache/jasper/compiler/Node.java
|
/*
* 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.jasper.compiler;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.el.ELContext;
import javax.el.ELException;
import javax.el.ExpressionFactory;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.JspIdConsumer;
import javax.servlet.jsp.tagext.SimpleTag;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagFileInfo;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagVariableInfo;
import javax.servlet.jsp.tagext.TryCatchFinally;
import javax.servlet.jsp.tagext.VariableInfo;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.apache.jasper.compiler.tagplugin.TagPluginContext;
import org.xml.sax.Attributes;
/**
* An internal data representation of a JSP page or a JSP document (XML). Also
* included here is a visitor class for traversing nodes.
*
* @author Kin-man Chung
* @author Jan Luehe
* @author Shawn Bayern
* @author Mark Roth
*/
abstract class Node implements TagConstants {
private static final VariableInfo[] ZERO_VARIABLE_INFO = {};
protected Attributes attrs;
// xmlns attributes that represent tag libraries (only in XML syntax)
protected Attributes taglibAttrs;
/*
* xmlns attributes that do not represent tag libraries (only in XML syntax)
*/
protected Attributes nonTaglibXmlnsAttrs;
protected Nodes body;
protected String text;
protected Mark startMark;
protected int beginJavaLine;
protected int endJavaLine;
protected Node parent;
protected Nodes namedAttributeNodes; // cached for performance
protected String qName;
protected String localName;
/*
* The name of the inner class to which the codes for this node and its body
* are generated. For instance, for <jsp:body> in foo.jsp, this is
* "foo_jspHelper". This is primarily used for communicating such info from
* Generator to Smap generator.
*/
protected String innerClassName;
/**
* Zero-arg Constructor.
*/
public Node() {
}
/**
* Constructor.
*
* @param start
* The location of the jsp page
* @param parent
* The enclosing node
*/
public Node(Mark start, Node parent) {
this.startMark = start;
addToParent(parent);
}
/**
* Constructor for Nodes parsed from standard syntax.
*
* @param qName
* The action's qualified name
* @param localName
* The action's local name
* @param attrs
* The attributes for this node
* @param start
* The location of the jsp page
* @param parent
* The enclosing node
*/
public Node(String qName, String localName, Attributes attrs, Mark start,
Node parent) {
this.qName = qName;
this.localName = localName;
this.attrs = attrs;
this.startMark = start;
addToParent(parent);
}
/**
* Constructor for Nodes parsed from XML syntax.
*
* @param qName
* The action's qualified name
* @param localName
* The action's local name
* @param attrs
* The action's attributes whose name does not start with xmlns
* @param nonTaglibXmlnsAttrs
* The action's xmlns attributes that do not represent tag
* libraries
* @param taglibAttrs
* The action's xmlns attributes that represent tag libraries
* @param start
* The location of the jsp page
* @param parent
* The enclosing node
*/
public Node(String qName, String localName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start,
Node parent) {
this.qName = qName;
this.localName = localName;
this.attrs = attrs;
this.nonTaglibXmlnsAttrs = nonTaglibXmlnsAttrs;
this.taglibAttrs = taglibAttrs;
this.startMark = start;
addToParent(parent);
}
/*
* Constructor.
*
* @param qName The action's qualified name @param localName The action's
* local name @param text The text associated with this node @param start
* The location of the jsp page @param parent The enclosing node
*/
public Node(String qName, String localName, String text, Mark start,
Node parent) {
this.qName = qName;
this.localName = localName;
this.text = text;
this.startMark = start;
addToParent(parent);
}
public String getQName() {
return this.qName;
}
public String getLocalName() {
return this.localName;
}
/*
* Gets this Node's attributes.
*
* In the case of a Node parsed from standard syntax, this method returns
* all the Node's attributes.
*
* In the case of a Node parsed from XML syntax, this method returns only
* those attributes whose name does not start with xmlns.
*/
public Attributes getAttributes() {
return this.attrs;
}
/*
* Gets this Node's xmlns attributes that represent tag libraries (only
* meaningful for Nodes parsed from XML syntax)
*/
public Attributes getTaglibAttributes() {
return this.taglibAttrs;
}
/*
* Gets this Node's xmlns attributes that do not represent tag libraries
* (only meaningful for Nodes parsed from XML syntax)
*/
public Attributes getNonTaglibXmlnsAttributes() {
return this.nonTaglibXmlnsAttrs;
}
public void setAttributes(Attributes attrs) {
this.attrs = attrs;
}
public String getAttributeValue(String name) {
return (attrs == null) ? null : attrs.getValue(name);
}
/**
* Get the attribute that is non request time expression, either from the
* attribute of the node, or from a jsp:attrbute
*/
public String getTextAttribute(String name) {
String attr = getAttributeValue(name);
if (attr != null) {
return attr;
}
NamedAttribute namedAttribute = getNamedAttributeNode(name);
if (namedAttribute == null) {
return null;
}
return namedAttribute.getText();
}
/**
* Searches all subnodes of this node for jsp:attribute standard actions
* with the given name, and returns the NamedAttribute node of the matching
* named attribute, nor null if no such node is found.
* <p>
* This should always be called and only be called for nodes that accept
* dynamic runtime attribute expressions.
*/
public NamedAttribute getNamedAttributeNode(String name) {
NamedAttribute result = null;
// Look for the attribute in NamedAttribute children
Nodes nodes = getNamedAttributeNodes();
int numChildNodes = nodes.size();
for (int i = 0; i < numChildNodes; i++) {
NamedAttribute na = (NamedAttribute) nodes.getNode(i);
boolean found = false;
int index = name.indexOf(':');
if (index != -1) {
// qualified name
found = na.getName().equals(name);
} else {
found = na.getLocalName().equals(name);
}
if (found) {
result = na;
break;
}
}
return result;
}
/**
* Searches all subnodes of this node for jsp:attribute standard actions,
* and returns that set of nodes as a Node.Nodes object.
*
* @return Possibly empty Node.Nodes object containing any jsp:attribute
* subnodes of this Node
*/
public Node.Nodes getNamedAttributeNodes() {
if (namedAttributeNodes != null) {
return namedAttributeNodes;
}
Node.Nodes result = new Node.Nodes();
// Look for the attribute in NamedAttribute children
Nodes nodes = getBody();
if (nodes != null) {
int numChildNodes = nodes.size();
for (int i = 0; i < numChildNodes; i++) {
Node n = nodes.getNode(i);
if (n instanceof NamedAttribute) {
result.add(n);
} else if (!(n instanceof Comment)) {
// Nothing can come before jsp:attribute, and only
// jsp:body can come after it.
break;
}
}
}
namedAttributeNodes = result;
return result;
}
public Nodes getBody() {
return body;
}
public void setBody(Nodes body) {
this.body = body;
}
public String getText() {
return text;
}
public Mark getStart() {
return startMark;
}
public Node getParent() {
return parent;
}
public int getBeginJavaLine() {
return beginJavaLine;
}
public void setBeginJavaLine(int begin) {
beginJavaLine = begin;
}
public int getEndJavaLine() {
return endJavaLine;
}
public void setEndJavaLine(int end) {
endJavaLine = end;
}
public Node.Root getRoot() {
Node n = this;
while (!(n instanceof Node.Root)) {
n = n.getParent();
}
return (Node.Root) n;
}
public String getInnerClassName() {
return innerClassName;
}
public void setInnerClassName(String icn) {
innerClassName = icn;
}
/**
* Selects and invokes a method in the visitor class based on the node type.
* This is abstract and should be overrode by the extending classes.
*
* @param v
* The visitor class
*/
abstract void accept(Visitor v) throws JasperException;
// *********************************************************************
// Private utility methods
/*
* Adds this Node to the body of the given parent.
*/
private void addToParent(Node parent) {
if (parent != null) {
this.parent = parent;
Nodes parentBody = parent.getBody();
if (parentBody == null) {
parentBody = new Nodes();
parent.setBody(parentBody);
}
parentBody.add(this);
}
}
/***************************************************************************
* Child classes
*/
/**
* Represents the root of a Jsp page or Jsp document
*/
public static class Root extends Node {
private final Root parentRoot;
private final boolean isXmlSyntax;
// Source encoding of the page containing this Root
private String pageEnc;
// Page encoding specified in JSP config element
private String jspConfigPageEnc;
/*
* Flag indicating if the default page encoding is being used (only
* applicable with standard syntax).
*
* True if the page does not provide a page directive with a
* 'contentType' attribute (or the 'contentType' attribute doesn't have
* a CHARSET value), the page does not provide a page directive with a
* 'pageEncoding' attribute, and there is no JSP configuration element
* page-encoding whose URL pattern matches the page.
*/
private boolean isDefaultPageEncoding;
/*
* Indicates whether an encoding has been explicitly specified in the
* page's XML prolog (only used for pages in XML syntax). This
* information is used to decide whether a translation error must be
* reported for encoding conflicts.
*/
private boolean isEncodingSpecifiedInProlog;
/*
* Indicates whether an encoding has been explicitly specified in the
* page's dom.
*/
private boolean isBomPresent;
/*
* Sequence number for temporary variables.
*/
private int tempSequenceNumber = 0;
/*
* Constructor.
*/
Root(Mark start, Node parent, boolean isXmlSyntax) {
super(start, parent);
this.isXmlSyntax = isXmlSyntax;
this.qName = JSP_ROOT_ACTION;
this.localName = ROOT_ACTION;
// Figure out and set the parent root
Node r = parent;
while ((r != null) && !(r instanceof Node.Root))
r = r.getParent();
parentRoot = (Node.Root) r;
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public boolean isXmlSyntax() {
return isXmlSyntax;
}
/*
* Sets the encoding specified in the JSP config element whose URL
* pattern matches the page containing this Root.
*/
public void setJspConfigPageEncoding(String enc) {
jspConfigPageEnc = enc;
}
/*
* Gets the encoding specified in the JSP config element whose URL
* pattern matches the page containing this Root.
*/
public String getJspConfigPageEncoding() {
return jspConfigPageEnc;
}
public void setPageEncoding(String enc) {
pageEnc = enc;
}
public String getPageEncoding() {
return pageEnc;
}
public void setIsDefaultPageEncoding(boolean isDefault) {
isDefaultPageEncoding = isDefault;
}
public boolean isDefaultPageEncoding() {
return isDefaultPageEncoding;
}
public void setIsEncodingSpecifiedInProlog(boolean isSpecified) {
isEncodingSpecifiedInProlog = isSpecified;
}
public boolean isEncodingSpecifiedInProlog() {
return isEncodingSpecifiedInProlog;
}
public void setIsBomPresent(boolean isBom) {
isBomPresent = isBom;
}
public boolean isBomPresent() {
return isBomPresent;
}
/**
* Generates a new temporary variable name.
*/
public String nextTemporaryVariableName() {
if (parentRoot == null) {
return Constants.TEMP_VARIABLE_NAME_PREFIX + (tempSequenceNumber++);
} else {
return parentRoot.nextTemporaryVariableName();
}
}
}
/**
* Represents the root of a Jsp document (XML syntax)
*/
public static class JspRoot extends Node {
public JspRoot(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, ROOT_ACTION, attrs, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a page directive
*/
public static class PageDirective extends Node {
private final Vector<String> imports;
public PageDirective(Attributes attrs, Mark start, Node parent) {
this(JSP_PAGE_DIRECTIVE_ACTION, attrs, null, null, start, parent);
}
public PageDirective(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, PAGE_DIRECTIVE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
imports = new Vector<>();
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
/**
* Parses the comma-separated list of class or package names in the
* given attribute value and adds each component to this PageDirective's
* vector of imported classes and packages.
*
* @param value
* A comma-separated string of imports.
*/
public void addImport(String value) {
int start = 0;
int index;
while ((index = value.indexOf(',', start)) != -1) {
imports.add(value.substring(start, index).trim());
start = index + 1;
}
if (start == 0) {
// No comma found
imports.add(value.trim());
} else {
imports.add(value.substring(start).trim());
}
}
public List<String> getImports() {
return imports;
}
}
/**
* Represents an include directive
*/
public static class IncludeDirective extends Node {
public IncludeDirective(Attributes attrs, Mark start, Node parent) {
this(JSP_INCLUDE_DIRECTIVE_ACTION, attrs, null, null, start, parent);
}
public IncludeDirective(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, INCLUDE_DIRECTIVE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a custom taglib directive
*/
public static class TaglibDirective extends Node {
public TaglibDirective(Attributes attrs, Mark start, Node parent) {
super(JSP_TAGLIB_DIRECTIVE_ACTION, TAGLIB_DIRECTIVE_ACTION, attrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a tag directive
*/
public static class TagDirective extends Node {
private final Vector<String> imports;
public TagDirective(Attributes attrs, Mark start, Node parent) {
this(JSP_TAG_DIRECTIVE_ACTION, attrs, null, null, start, parent);
}
public TagDirective(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, TAG_DIRECTIVE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
imports = new Vector<>();
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
/**
* Parses the comma-separated list of class or package names in the
* given attribute value and adds each component to this PageDirective's
* vector of imported classes and packages.
*
* @param value
* A comma-separated string of imports.
*/
public void addImport(String value) {
int start = 0;
int index;
while ((index = value.indexOf(',', start)) != -1) {
imports.add(value.substring(start, index).trim());
start = index + 1;
}
if (start == 0) {
// No comma found
imports.add(value.trim());
} else {
imports.add(value.substring(start).trim());
}
}
public List<String> getImports() {
return imports;
}
}
/**
* Represents an attribute directive
*/
public static class AttributeDirective extends Node {
public AttributeDirective(Attributes attrs, Mark start, Node parent) {
this(JSP_ATTRIBUTE_DIRECTIVE_ACTION, attrs, null, null, start,
parent);
}
public AttributeDirective(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, ATTRIBUTE_DIRECTIVE_ACTION, attrs,
nonTaglibXmlnsAttrs, taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a variable directive
*/
public static class VariableDirective extends Node {
public VariableDirective(Attributes attrs, Mark start, Node parent) {
this(JSP_VARIABLE_DIRECTIVE_ACTION, attrs, null, null, start,
parent);
}
public VariableDirective(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, VARIABLE_DIRECTIVE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a <jsp:invoke> tag file action
*/
public static class InvokeAction extends Node {
public InvokeAction(Attributes attrs, Mark start, Node parent) {
this(JSP_INVOKE_ACTION, attrs, null, null, start, parent);
}
public InvokeAction(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, INVOKE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a <jsp:doBody> tag file action
*/
public static class DoBodyAction extends Node {
public DoBodyAction(Attributes attrs, Mark start, Node parent) {
this(JSP_DOBODY_ACTION, attrs, null, null, start, parent);
}
public DoBodyAction(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, DOBODY_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a Jsp comment Comments are kept for completeness.
*/
public static class Comment extends Node {
public Comment(String text, Mark start, Node parent) {
super(null, null, text, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents an expression, declaration, or scriptlet
*/
public abstract static class ScriptingElement extends Node {
public ScriptingElement(String qName, String localName, String text,
Mark start, Node parent) {
super(qName, localName, text, start, parent);
}
public ScriptingElement(String qName, String localName,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, localName, null, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
/**
* When this node was created from a JSP page in JSP syntax, its text
* was stored as a String in the "text" field, whereas when this node
* was created from a JSP document, its text was stored as one or more
* TemplateText nodes in its body. This method handles either case.
*
* @return The text string
*/
@Override
public String getText() {
String ret = text;
if (ret == null) {
if (body != null) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < body.size(); i++) {
buf.append(body.getNode(i).getText());
}
ret = buf.toString();
} else {
// Nulls cause NPEs further down the line
ret = "";
}
}
return ret;
}
/**
* For the same reason as above, the source line information in the
* contained TemplateText node should be used.
*/
@Override
public Mark getStart() {
if (text == null && body != null && body.size() > 0) {
return body.getNode(0).getStart();
} else {
return super.getStart();
}
}
}
/**
* Represents a declaration
*/
public static class Declaration extends ScriptingElement {
public Declaration(String text, Mark start, Node parent) {
super(JSP_DECLARATION_ACTION, DECLARATION_ACTION, text, start,
parent);
}
public Declaration(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, DECLARATION_ACTION, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents an expression. Expressions in attributes are embedded in the
* attribute string and not here.
*/
public static class Expression extends ScriptingElement {
public Expression(String text, Mark start, Node parent) {
super(JSP_EXPRESSION_ACTION, EXPRESSION_ACTION, text, start, parent);
}
public Expression(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, EXPRESSION_ACTION, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a scriptlet
*/
public static class Scriptlet extends ScriptingElement {
public Scriptlet(String text, Mark start, Node parent) {
super(JSP_SCRIPTLET_ACTION, SCRIPTLET_ACTION, text, start, parent);
}
public Scriptlet(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, SCRIPTLET_ACTION, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents an EL expression. Expressions in attributes are embedded in
* the attribute string and not here.
*/
public static class ELExpression extends Node {
private ELNode.Nodes el;
private final char type;
public ELExpression(char type, String text, Mark start, Node parent) {
super(null, null, text, start, parent);
this.type = type;
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setEL(ELNode.Nodes el) {
this.el = el;
}
public ELNode.Nodes getEL() {
return el;
}
public char getType() {
return this.type;
}
}
/**
* Represents a param action
*/
public static class ParamAction extends Node {
private JspAttribute value;
public ParamAction(Attributes attrs, Mark start, Node parent) {
this(JSP_PARAM_ACTION, attrs, null, null, start, parent);
}
public ParamAction(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, PARAM_ACTION, attrs, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setValue(JspAttribute value) {
this.value = value;
}
public JspAttribute getValue() {
return value;
}
}
/**
* Represents a params action
*/
public static class ParamsAction extends Node {
public ParamsAction(Mark start, Node parent) {
this(JSP_PARAMS_ACTION, null, null, start, parent);
}
public ParamsAction(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, PARAMS_ACTION, null, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a fallback action
*/
public static class FallBackAction extends Node {
public FallBackAction(Mark start, Node parent) {
this(JSP_FALLBACK_ACTION, null, null, start, parent);
}
public FallBackAction(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, FALLBACK_ACTION, null, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents an include action
*/
public static class IncludeAction extends Node {
private JspAttribute page;
public IncludeAction(Attributes attrs, Mark start, Node parent) {
this(JSP_INCLUDE_ACTION, attrs, null, null, start, parent);
}
public IncludeAction(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, INCLUDE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setPage(JspAttribute page) {
this.page = page;
}
public JspAttribute getPage() {
return page;
}
}
/**
* Represents a forward action
*/
public static class ForwardAction extends Node {
private JspAttribute page;
public ForwardAction(Attributes attrs, Mark start, Node parent) {
this(JSP_FORWARD_ACTION, attrs, null, null, start, parent);
}
public ForwardAction(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, FORWARD_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setPage(JspAttribute page) {
this.page = page;
}
public JspAttribute getPage() {
return page;
}
}
/**
* Represents a getProperty action
*/
public static class GetProperty extends Node {
public GetProperty(Attributes attrs, Mark start, Node parent) {
this(JSP_GET_PROPERTY_ACTION, attrs, null, null, start, parent);
}
public GetProperty(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, GET_PROPERTY_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a setProperty action
*/
public static class SetProperty extends Node {
private JspAttribute value;
public SetProperty(Attributes attrs, Mark start, Node parent) {
this(JSP_SET_PROPERTY_ACTION, attrs, null, null, start, parent);
}
public SetProperty(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, SET_PROPERTY_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setValue(JspAttribute value) {
this.value = value;
}
public JspAttribute getValue() {
return value;
}
}
/**
* Represents a useBean action
*/
public static class UseBean extends Node {
private JspAttribute beanName;
public UseBean(Attributes attrs, Mark start, Node parent) {
this(JSP_USE_BEAN_ACTION, attrs, null, null, start, parent);
}
public UseBean(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, USE_BEAN_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setBeanName(JspAttribute beanName) {
this.beanName = beanName;
}
public JspAttribute getBeanName() {
return beanName;
}
}
/**
* Represents a plugin action
*/
public static class PlugIn extends Node {
private JspAttribute width;
private JspAttribute height;
public PlugIn(Attributes attrs, Mark start, Node parent) {
this(JSP_PLUGIN_ACTION, attrs, null, null, start, parent);
}
public PlugIn(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, PLUGIN_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setHeight(JspAttribute height) {
this.height = height;
}
public void setWidth(JspAttribute width) {
this.width = width;
}
public JspAttribute getHeight() {
return height;
}
public JspAttribute getWidth() {
return width;
}
}
/**
* Represents an uninterpreted tag, from a Jsp document
*/
public static class UninterpretedTag extends Node {
private JspAttribute[] jspAttrs;
public UninterpretedTag(String qName, String localName,
Attributes attrs, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, localName, attrs, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setJspAttributes(JspAttribute[] jspAttrs) {
this.jspAttrs = jspAttrs;
}
public JspAttribute[] getJspAttributes() {
return jspAttrs;
}
}
/**
* Represents a <jsp:element>.
*/
public static class JspElement extends Node {
private JspAttribute[] jspAttrs;
private JspAttribute nameAttr;
public JspElement(Attributes attrs, Mark start, Node parent) {
this(JSP_ELEMENT_ACTION, attrs, null, null, start, parent);
}
public JspElement(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, ELEMENT_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public void setJspAttributes(JspAttribute[] jspAttrs) {
this.jspAttrs = jspAttrs;
}
public JspAttribute[] getJspAttributes() {
return jspAttrs;
}
/*
* Sets the XML-style 'name' attribute
*/
public void setNameAttribute(JspAttribute nameAttr) {
this.nameAttr = nameAttr;
}
/*
* Gets the XML-style 'name' attribute
*/
public JspAttribute getNameAttribute() {
return this.nameAttr;
}
}
/**
* Represents a <jsp:output>.
*/
public static class JspOutput extends Node {
public JspOutput(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, OUTPUT_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Collected information about child elements. Used by nodes like CustomTag,
* JspBody, and NamedAttribute. The information is set in the Collector.
*/
public static class ChildInfo {
private boolean scriptless; // true if the tag and its body
// contain no scripting elements.
private boolean hasUseBean;
private boolean hasIncludeAction;
private boolean hasParamAction;
private boolean hasSetProperty;
private boolean hasScriptingVars;
public void setScriptless(boolean s) {
scriptless = s;
}
public boolean isScriptless() {
return scriptless;
}
public void setHasUseBean(boolean u) {
hasUseBean = u;
}
public boolean hasUseBean() {
return hasUseBean;
}
public void setHasIncludeAction(boolean i) {
hasIncludeAction = i;
}
public boolean hasIncludeAction() {
return hasIncludeAction;
}
public void setHasParamAction(boolean i) {
hasParamAction = i;
}
public boolean hasParamAction() {
return hasParamAction;
}
public void setHasSetProperty(boolean s) {
hasSetProperty = s;
}
public boolean hasSetProperty() {
return hasSetProperty;
}
public void setHasScriptingVars(boolean s) {
hasScriptingVars = s;
}
public boolean hasScriptingVars() {
return hasScriptingVars;
}
}
/**
* Represents a custom tag
*/
public static class CustomTag extends Node {
private final String uri;
private final String prefix;
private JspAttribute[] jspAttrs;
private TagData tagData;
private String tagHandlerPoolName;
private final TagInfo tagInfo;
private final TagFileInfo tagFileInfo;
private Class<?> tagHandlerClass;
private VariableInfo[] varInfos;
private final int customNestingLevel;
private final ChildInfo childInfo;
private final boolean implementsIterationTag;
private final boolean implementsBodyTag;
private final boolean implementsTryCatchFinally;
private final boolean implementsJspIdConsumer;
private final boolean implementsSimpleTag;
private final boolean implementsDynamicAttributes;
private List<Object> atBeginScriptingVars;
private List<Object> atEndScriptingVars;
private List<Object> nestedScriptingVars;
private Node.CustomTag customTagParent;
private Integer numCount;
private boolean useTagPlugin;
private TagPluginContext tagPluginContext;
/**
* The following two fields are used for holding the Java scriptlets
* that the tag plugins may generate. Meaningful only if useTagPlugin is
* true; Could move them into TagPluginContextImpl, but we'll need to
* cast tagPluginContext to TagPluginContextImpl all the time...
*/
private Nodes atSTag;
private Nodes atETag;
/*
* Constructor for custom action implemented by tag handler.
*/
public CustomTag(String qName, String prefix, String localName,
String uri, Attributes attrs, Mark start, Node parent,
TagInfo tagInfo, Class<?> tagHandlerClass) {
this(qName, prefix, localName, uri, attrs, null, null, start,
parent, tagInfo, tagHandlerClass);
}
/*
* Constructor for custom action implemented by tag handler.
*/
public CustomTag(String qName, String prefix, String localName,
String uri, Attributes attrs, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent,
TagInfo tagInfo, Class<?> tagHandlerClass) {
super(qName, localName, attrs, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
this.uri = uri;
this.prefix = prefix;
this.tagInfo = tagInfo;
this.tagFileInfo = null;
this.tagHandlerClass = tagHandlerClass;
this.customNestingLevel = makeCustomNestingLevel();
this.childInfo = new ChildInfo();
this.implementsIterationTag = IterationTag.class
.isAssignableFrom(tagHandlerClass);
this.implementsBodyTag = BodyTag.class
.isAssignableFrom(tagHandlerClass);
this.implementsTryCatchFinally = TryCatchFinally.class
.isAssignableFrom(tagHandlerClass);
this.implementsSimpleTag = SimpleTag.class
.isAssignableFrom(tagHandlerClass);
this.implementsDynamicAttributes = DynamicAttributes.class
.isAssignableFrom(tagHandlerClass);
this.implementsJspIdConsumer = JspIdConsumer.class
.isAssignableFrom(tagHandlerClass);
}
/*
* Constructor for custom action implemented by tag file.
*/
public CustomTag(String qName, String prefix, String localName,
String uri, Attributes attrs, Mark start, Node parent,
TagFileInfo tagFileInfo) {
this(qName, prefix, localName, uri, attrs, null, null, start,
parent, tagFileInfo);
}
/*
* Constructor for custom action implemented by tag file.
*/
public CustomTag(String qName, String prefix, String localName,
String uri, Attributes attrs, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent,
TagFileInfo tagFileInfo) {
super(qName, localName, attrs, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
this.uri = uri;
this.prefix = prefix;
this.tagFileInfo = tagFileInfo;
this.tagInfo = tagFileInfo.getTagInfo();
this.customNestingLevel = makeCustomNestingLevel();
this.childInfo = new ChildInfo();
this.implementsIterationTag = false;
this.implementsBodyTag = false;
this.implementsTryCatchFinally = false;
this.implementsSimpleTag = true;
this.implementsJspIdConsumer = false;
this.implementsDynamicAttributes = tagInfo.hasDynamicAttributes();
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
/**
* @return The URI namespace that this custom action belongs to
*/
public String getURI() {
return this.uri;
}
/**
* @return The tag prefix
*/
public String getPrefix() {
return prefix;
}
public void setJspAttributes(JspAttribute[] jspAttrs) {
this.jspAttrs = jspAttrs;
}
public JspAttribute[] getJspAttributes() {
return jspAttrs;
}
public ChildInfo getChildInfo() {
return childInfo;
}
public void setTagData(TagData tagData) {
this.tagData = tagData;
this.varInfos = tagInfo.getVariableInfo(tagData);
if (this.varInfos == null) {
this.varInfos = ZERO_VARIABLE_INFO;
}
}
public TagData getTagData() {
return tagData;
}
public void setTagHandlerPoolName(String s) {
tagHandlerPoolName = s;
}
public String getTagHandlerPoolName() {
return tagHandlerPoolName;
}
public TagInfo getTagInfo() {
return tagInfo;
}
public TagFileInfo getTagFileInfo() {
return tagFileInfo;
}
/*
* @return true if this custom action is supported by a tag file, false
* otherwise
*/
public boolean isTagFile() {
return tagFileInfo != null;
}
public Class<?> getTagHandlerClass() {
return tagHandlerClass;
}
public void setTagHandlerClass(Class<?> hc) {
tagHandlerClass = hc;
}
public boolean implementsIterationTag() {
return implementsIterationTag;
}
public boolean implementsBodyTag() {
return implementsBodyTag;
}
public boolean implementsTryCatchFinally() {
return implementsTryCatchFinally;
}
public boolean implementsJspIdConsumer() {
return implementsJspIdConsumer;
}
public boolean implementsSimpleTag() {
return implementsSimpleTag;
}
public boolean implementsDynamicAttributes() {
return implementsDynamicAttributes;
}
public TagVariableInfo[] getTagVariableInfos() {
return tagInfo.getTagVariableInfos();
}
public VariableInfo[] getVariableInfos() {
return varInfos;
}
public void setCustomTagParent(Node.CustomTag n) {
this.customTagParent = n;
}
public Node.CustomTag getCustomTagParent() {
return this.customTagParent;
}
public void setNumCount(Integer count) {
this.numCount = count;
}
public Integer getNumCount() {
return this.numCount;
}
public void setScriptingVars(List<Object> vec, int scope) {
switch (scope) {
case VariableInfo.AT_BEGIN:
this.atBeginScriptingVars = vec;
break;
case VariableInfo.AT_END:
this.atEndScriptingVars = vec;
break;
case VariableInfo.NESTED:
this.nestedScriptingVars = vec;
break;
}
}
/*
* Gets the scripting variables for the given scope that need to be
* declared.
*/
public List<Object> getScriptingVars(int scope) {
List<Object> vec = null;
switch (scope) {
case VariableInfo.AT_BEGIN:
vec = this.atBeginScriptingVars;
break;
case VariableInfo.AT_END:
vec = this.atEndScriptingVars;
break;
case VariableInfo.NESTED:
vec = this.nestedScriptingVars;
break;
}
return vec;
}
/*
* Gets this custom tag's custom nesting level, which is given as the
* number of times this custom tag is nested inside itself.
*/
public int getCustomNestingLevel() {
return customNestingLevel;
}
/**
* Checks to see if the attribute of the given name is of type
* JspFragment.
*/
public boolean checkIfAttributeIsJspFragment(String name) {
boolean result = false;
TagAttributeInfo[] attributes = tagInfo.getAttributes();
for (int i = 0; i < attributes.length; i++) {
if (attributes[i].getName().equals(name)
&& attributes[i].isFragment()) {
result = true;
break;
}
}
return result;
}
public void setUseTagPlugin(boolean use) {
useTagPlugin = use;
}
public boolean useTagPlugin() {
return useTagPlugin;
}
public void setTagPluginContext(TagPluginContext tagPluginContext) {
this.tagPluginContext = tagPluginContext;
}
public TagPluginContext getTagPluginContext() {
return tagPluginContext;
}
public void setAtSTag(Nodes sTag) {
atSTag = sTag;
}
public Nodes getAtSTag() {
return atSTag;
}
public void setAtETag(Nodes eTag) {
atETag = eTag;
}
public Nodes getAtETag() {
return atETag;
}
/*
* Computes this custom tag's custom nesting level, which corresponds to
* the number of times this custom tag is nested inside itself.
*
* Example:
*
* <g:h> <a:b> -- nesting level 0 <c:d> <e:f> <a:b> -- nesting level 1
* <a:b> -- nesting level 2 </a:b> </a:b> <a:b> -- nesting level 1
* </a:b> </e:f> </c:d> </a:b> </g:h>
*
* @return Custom tag's nesting level
*/
private int makeCustomNestingLevel() {
int n = 0;
Node p = parent;
while (p != null) {
if ((p instanceof Node.CustomTag)
&& qName.equals(((Node.CustomTag) p).qName)) {
n++;
}
p = p.parent;
}
return n;
}
/**
* Returns true if this custom action has an empty body, and false
* otherwise.
*
* A custom action is considered to have an empty body if the following
* holds true: - getBody() returns null, or - all immediate children are
* jsp:attribute actions, or - the action's jsp:body is empty.
*/
public boolean hasEmptyBody() {
boolean hasEmptyBody = true;
Nodes nodes = getBody();
if (nodes != null) {
int numChildNodes = nodes.size();
for (int i = 0; i < numChildNodes; i++) {
Node n = nodes.getNode(i);
if (!(n instanceof NamedAttribute)) {
if (n instanceof JspBody) {
hasEmptyBody = (n.getBody() == null);
} else {
hasEmptyBody = false;
}
break;
}
}
}
return hasEmptyBody;
}
}
/**
* Used as a placeholder for the evaluation code of a custom action
* attribute (used by the tag plugin machinery only).
*/
public static class AttributeGenerator extends Node {
private String name; // name of the attribute
private CustomTag tag; // The tag this attribute belongs to
public AttributeGenerator(Mark start, String name, CustomTag tag) {
super(start, null);
this.name = name;
this.tag = tag;
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public String getName() {
return name;
}
public CustomTag getTag() {
return tag;
}
}
/**
* Represents the body of a <jsp:text> element
*/
public static class JspText extends Node {
public JspText(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, TEXT_ACTION, null, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
}
/**
* Represents a Named Attribute (<jsp:attribute>)
*/
public static class NamedAttribute extends Node {
// A unique temporary variable name suitable for code generation
private String temporaryVariableName;
// True if this node is to be trimmed, or false otherwise
private boolean trim = true;
// True if this attribute should be omitted from the output if
// used with a <jsp:element>, otherwise false
private JspAttribute omit;
private final ChildInfo childInfo;
private final String name;
private String localName;
private String prefix;
public NamedAttribute(Attributes attrs, Mark start, Node parent) {
this(JSP_ATTRIBUTE_ACTION, attrs, null, null, start, parent);
}
public NamedAttribute(String qName, Attributes attrs,
Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs,
Mark start, Node parent) {
super(qName, ATTRIBUTE_ACTION, attrs, nonTaglibXmlnsAttrs,
taglibAttrs, start, parent);
if ("false".equals(this.getAttributeValue("trim"))) {
// (if null or true, leave default of true)
trim = false;
}
childInfo = new ChildInfo();
name = this.getAttributeValue("name");
if (name != null) {
// Mandatory attribute "name" will be checked in Validator
localName = name;
int index = name.indexOf(':');
if (index != -1) {
prefix = name.substring(0, index);
localName = name.substring(index + 1);
}
}
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public String getName() {
return this.name;
}
@Override
public String getLocalName() {
return this.localName;
}
public String getPrefix() {
return this.prefix;
}
public ChildInfo getChildInfo() {
return this.childInfo;
}
public boolean isTrim() {
return trim;
}
public void setOmit(JspAttribute omit) {
this.omit = omit;
}
public JspAttribute getOmit() {
return omit;
}
/**
* @return A unique temporary variable name to store the result in.
* (this probably could go elsewhere, but it's convenient here)
*/
public String getTemporaryVariableName() {
if (temporaryVariableName == null) {
temporaryVariableName = getRoot().nextTemporaryVariableName();
}
return temporaryVariableName;
}
/*
* Get the attribute value from this named attribute (<jsp:attribute>).
* Since this method is only for attributes that are not rtexpr, we can
* assume the body of the jsp:attribute is a template text.
*/
@Override
public String getText() {
class AttributeVisitor extends Visitor {
private String attrValue = null;
@Override
public void visit(TemplateText txt) {
attrValue = txt.getText();
}
public String getAttrValue() {
return attrValue;
}
}
// According to JSP 2.0, if the body of the <jsp:attribute>
// action is empty, it is equivalent of specifying "" as the value
// of the attribute.
String text = "";
if (getBody() != null) {
AttributeVisitor attributeVisitor = new AttributeVisitor();
try {
getBody().visit(attributeVisitor);
} catch (JasperException e) {
}
text = attributeVisitor.getAttrValue();
}
return text;
}
}
/**
* Represents a JspBody node (<jsp:body>)
*/
public static class JspBody extends Node {
private final ChildInfo childInfo;
public JspBody(Mark start, Node parent) {
this(JSP_BODY_ACTION, null, null, start, parent);
}
public JspBody(String qName, Attributes nonTaglibXmlnsAttrs,
Attributes taglibAttrs, Mark start, Node parent) {
super(qName, BODY_ACTION, null, nonTaglibXmlnsAttrs, taglibAttrs,
start, parent);
this.childInfo = new ChildInfo();
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
public ChildInfo getChildInfo() {
return childInfo;
}
}
/**
* Represents a template text string
*/
public static class TemplateText extends Node {
private ArrayList<Integer> extraSmap = null;
public TemplateText(String text, Mark start, Node parent) {
super(null, null, text, start, parent);
}
@Override
public void accept(Visitor v) throws JasperException {
v.visit(this);
}
/**
* Trim all whitespace from the left of the template text
*/
public void ltrim() {
int index = 0;
while ((index < text.length()) && (text.charAt(index) <= ' ')) {
index++;
}
text = text.substring(index);
}
public void setText(String text) {
this.text = text;
}
/**
* Trim all whitespace from the right of the template text
*/
public void rtrim() {
int index = text.length();
while ((index > 0) && (text.charAt(index - 1) <= ' ')) {
index--;
}
text = text.substring(0, index);
}
/**
* Returns true if this template text contains whitespace only.
*/
public boolean isAllSpace() {
boolean isAllSpace = true;
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
isAllSpace = false;
break;
}
}
return isAllSpace;
}
/**
* Add a source to Java line mapping
*
* @param srcLine
* The position of the source line, relative to the line at
* the start of this node. The corresponding java line is
* assumed to be consecutive, i.e. one more than the last.
*/
public void addSmap(int srcLine) {
if (extraSmap == null) {
extraSmap = new ArrayList<>();
}
extraSmap.add(new Integer(srcLine));
}
public ArrayList<Integer> getExtraSmap() {
return extraSmap;
}
}
/***************************************************************************
* Auxiliary classes used in Node
*/
/**
* Represents attributes that can be request time expressions.
*
* Can either be a plain attribute, an attribute that represents a request
* time expression value, or a named attribute (specified using the
* jsp:attribute standard action).
*/
public static class JspAttribute {
private final String qName;
private final String uri;
private final String localName;
private final String value;
private final boolean expression;
private final boolean dynamic;
private final ELNode.Nodes el;
private final TagAttributeInfo tai;
// If true, this JspAttribute represents a <jsp:attribute>
private final boolean namedAttribute;
// The node in the parse tree for the NamedAttribute
private final NamedAttribute namedAttributeNode;
JspAttribute(TagAttributeInfo tai, String qName, String uri,
String localName, String value, boolean expr, ELNode.Nodes el,
boolean dyn) {
this.qName = qName;
this.uri = uri;
this.localName = localName;
this.value = value;
this.namedAttributeNode = null;
this.expression = expr;
this.el = el;
this.dynamic = dyn;
this.namedAttribute = false;
this.tai = tai;
}
/**
* Allow node to validate itself
*
* @param ef
* @param ctx
* @throws ELException
*/
public void validateEL(ExpressionFactory ef, ELContext ctx)
throws ELException {
if (this.el != null) {
// determine exact type
ef.createValueExpression(ctx, this.value, String.class);
}
}
/**
* Use this constructor if the JspAttribute represents a named
* attribute. In this case, we have to store the nodes of the body of
* the attribute.
*/
JspAttribute(NamedAttribute na, TagAttributeInfo tai, boolean dyn) {
this.qName = na.getName();
this.localName = na.getLocalName();
this.value = null;
this.namedAttributeNode = na;
this.expression = false;
this.el = null;
this.dynamic = dyn;
this.namedAttribute = true;
this.tai = tai;
this.uri = null;
}
/**
* @return The name of the attribute
*/
public String getName() {
return qName;
}
/**
* @return The local name of the attribute
*/
public String getLocalName() {
return localName;
}
/**
* @return The namespace of the attribute, or null if in the default
* namespace
*/
public String getURI() {
return uri;
}
public TagAttributeInfo getTagAttributeInfo() {
return this.tai;
}
/**
*
* @return return true if there's TagAttributeInfo meaning we need to
* assign a ValueExpression
*/
public boolean isDeferredInput() {
return (this.tai != null) ? this.tai.isDeferredValue() : false;
}
/**
*
* @return return true if there's TagAttributeInfo meaning we need to
* assign a MethodExpression
*/
public boolean isDeferredMethodInput() {
return (this.tai != null) ? this.tai.isDeferredMethod() : false;
}
public String getExpectedTypeName() {
if (this.tai != null) {
if (this.isDeferredInput()) {
return this.tai.getExpectedTypeName();
} else if (this.isDeferredMethodInput()) {
String m = this.tai.getMethodSignature();
if (m != null) {
int rti = m.trim().indexOf(' ');
if (rti > 0) {
return m.substring(0, rti).trim();
}
}
}
}
return "java.lang.Object";
}
public String[] getParameterTypeNames() {
if (this.tai != null) {
if (this.isDeferredMethodInput()) {
String m = this.tai.getMethodSignature();
if (m != null) {
m = m.trim();
m = m.substring(m.indexOf('(') + 1);
m = m.substring(0, m.length() - 1);
if (m.trim().length() > 0) {
String[] p = m.split(",");
for (int i = 0; i < p.length; i++) {
p[i] = p[i].trim();
}
return p;
}
}
}
}
return new String[0];
}
/**
* Only makes sense if namedAttribute is false.
*
* @return the value for the attribute, or the expression string
* (stripped of "<%=", "%>", "%=", or "%" but containing "${"
* and "}" for EL expressions)
*/
public String getValue() {
return value;
}
/**
* Only makes sense if namedAttribute is true.
*
* @return the nodes that evaluate to the body of this attribute.
*/
public NamedAttribute getNamedAttributeNode() {
return namedAttributeNode;
}
/**
* @return true if the value represents a traditional rtexprvalue
*/
public boolean isExpression() {
return expression;
}
/**
* @return true if the value represents a NamedAttribute value.
*/
public boolean isNamedAttribute() {
return namedAttribute;
}
/**
* @return true if the value represents an expression that should be fed
* to the expression interpreter
* false for string literals or rtexprvalues that should not be
* interpreted or reevaluated
*/
public boolean isELInterpreterInput() {
return el != null || this.isDeferredInput()
|| this.isDeferredMethodInput();
}
/**
* @return true if the value is a string literal known at translation
* time.
*/
public boolean isLiteral() {
return !expression && (el != null) && !namedAttribute;
}
/**
* XXX
*/
public boolean isDynamic() {
return dynamic;
}
public ELNode.Nodes getEL() {
return el;
}
}
/**
* An ordered list of Node, used to represent the body of an element, or a
* jsp page of jsp document.
*/
public static class Nodes {
private final List<Node> list;
private Node.Root root; // null if this is not a page
private boolean generatedInBuffer;
public Nodes() {
list = new Vector<>();
}
public Nodes(Node.Root root) {
this.root = root;
list = new Vector<>();
list.add(root);
}
/**
* Appends a node to the list
*
* @param n
* The node to add
*/
public void add(Node n) {
list.add(n);
root = null;
}
/**
* Removes the given node from the list.
*
* @param n
* The node to be removed
*/
public void remove(Node n) {
list.remove(n);
}
/**
* Visit the nodes in the list with the supplied visitor
*
* @param v
* The visitor used
*/
public void visit(Visitor v) throws JasperException {
Iterator<Node> iter = list.iterator();
while (iter.hasNext()) {
Node n = iter.next();
n.accept(v);
}
}
public int size() {
return list.size();
}
public Node getNode(int index) {
Node n = null;
try {
n = list.get(index);
} catch (ArrayIndexOutOfBoundsException e) {
}
return n;
}
public Node.Root getRoot() {
return root;
}
public boolean isGeneratedInBuffer() {
return generatedInBuffer;
}
public void setGeneratedInBuffer(boolean g) {
generatedInBuffer = g;
}
}
/**
* A visitor class for visiting the node. This class also provides the
* default action (i.e. nop) for each of the child class of the Node. An
* actual visitor should extend this class and supply the visit method for
* the nodes that it cares.
*/
public static class Visitor {
/**
* This method provides a place to put actions that are common to all
* nodes. Override this in the child visitor class if need to.
*/
@SuppressWarnings("unused")
protected void doVisit(Node n) throws JasperException {
// NOOP by default
}
/**
* Visit the body of a node, using the current visitor
*/
protected void visitBody(Node n) throws JasperException {
if (n.getBody() != null) {
n.getBody().visit(this);
}
}
public void visit(Root n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(JspRoot n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(PageDirective n) throws JasperException {
doVisit(n);
}
public void visit(TagDirective n) throws JasperException {
doVisit(n);
}
public void visit(IncludeDirective n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(TaglibDirective n) throws JasperException {
doVisit(n);
}
public void visit(AttributeDirective n) throws JasperException {
doVisit(n);
}
public void visit(VariableDirective n) throws JasperException {
doVisit(n);
}
public void visit(Comment n) throws JasperException {
doVisit(n);
}
public void visit(Declaration n) throws JasperException {
doVisit(n);
}
public void visit(Expression n) throws JasperException {
doVisit(n);
}
public void visit(Scriptlet n) throws JasperException {
doVisit(n);
}
public void visit(ELExpression n) throws JasperException {
doVisit(n);
}
public void visit(IncludeAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(ForwardAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(GetProperty n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(SetProperty n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(ParamAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(ParamsAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(FallBackAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(UseBean n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(PlugIn n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(CustomTag n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(UninterpretedTag n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(JspElement n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(JspText n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(NamedAttribute n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(JspBody n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(InvokeAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(DoBodyAction n) throws JasperException {
doVisit(n);
visitBody(n);
}
public void visit(TemplateText n) throws JasperException {
doVisit(n);
}
public void visit(JspOutput n) throws JasperException {
doVisit(n);
}
public void visit(AttributeGenerator n) throws JasperException {
doVisit(n);
}
}
}
|
55,642
|
Bug 55642 TagPluginManager isConstantAttribute broken
|
Function isConstantAttribute in TagPluginManager seems to be be broken. For value "order.status" it returns false. And for value "${order.state.name}" it returns true. According to javadoc it should be exact opposite. Problem seems to be in Node.isLiteral function. "el!= null" should probably be "el== null" But this function is being used elsewhere. /** * @return true if the attribute is specified and its value is a * translation-time constant. */ public boolean TagPluginManager.isConstantAttribute(String attribute){ Node.JspAttribute attr = getNodeAttribute(attribute); if (attr == null) return false; return attr.isLiteral(); } /** * @return true if the value is a string literal known at translation * time. */ public boolean isLiteral() { return !expression && (el != null) && !namedAttribute; }
|
resolved fixed
|
af49b44
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-09T14:33:39Z
| 2013-10-09T17:33:20Z
|
test/org/apache/jasper/compiler/TestNode.java
| |
55,251
|
Bug 55251 JspC fails silently if directory for generated web.xml does not exist
|
If the file specified for webXml (via call to setWebXml) cannot be created (for example if the directory does not exist), then JspC fails silently.
|
resolved fixed
|
06d8338
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-10T13:38:20Z
| 2013-07-12T09:06:40Z
|
java/org/apache/jasper/JspC.java
|
/*
* 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.jasper;
import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.Compiler;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.JspRuntimeContext;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldLocationsCache;
import org.apache.jasper.servlet.JspCServletContext;
import org.apache.jasper.servlet.TldScanner;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.util.FileUtils;
import org.xml.sax.SAXException;
/**
* Shell for the jspc compiler. Handles all options associated with the
* command line and creates compilation contexts which it then compiles
* according to the specified options.
*
* This version can process files from a _single_ webapp at once, i.e.
* a single docbase can be specified.
*
* It can be used as an Ant task using:
* <pre>
* <taskdef classname="org.apache.jasper.JspC" name="jasper" >
* <classpath>
* <pathelement location="${java.home}/../lib/tools.jar"/>
* <fileset dir="${ENV.CATALINA_HOME}/lib">
* <include name="*.jar"/>
* </fileset>
* <path refid="myjars"/>
* </classpath>
* </taskdef>
*
* <jasper verbose="0"
* package="my.package"
* uriroot="${webapps.dir}/${webapp.name}"
* webXmlFragment="${build.dir}/generated_web.xml"
* outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />
* </pre>
*
* @author Danno Ferrin
* @author Pierre Delisle
* @author Costin Manolache
* @author Yoav Shapira
*/
public class JspC extends Task implements Options {
public static final String DEFAULT_IE_CLASS_ID =
"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
// Logger
private static final Log log = LogFactory.getLog(JspC.class);
protected static final String SWITCH_VERBOSE = "-v";
protected static final String SWITCH_HELP = "-help";
protected static final String SWITCH_OUTPUT_DIR = "-d";
protected static final String SWITCH_PACKAGE_NAME = "-p";
protected static final String SWITCH_CACHE = "-cache";
protected static final String SWITCH_CLASS_NAME = "-c";
protected static final String SWITCH_FULL_STOP = "--";
protected static final String SWITCH_COMPILE = "-compile";
protected static final String SWITCH_SOURCE = "-source";
protected static final String SWITCH_TARGET = "-target";
protected static final String SWITCH_URI_BASE = "-uribase";
protected static final String SWITCH_URI_ROOT = "-uriroot";
protected static final String SWITCH_FILE_WEBAPP = "-webapp";
protected static final String SWITCH_WEBAPP_INC = "-webinc";
protected static final String SWITCH_WEBAPP_XML = "-webxml";
protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding";
protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings";
protected static final String SWITCH_MAPPED = "-mapped";
protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy";
protected static final String SWITCH_TRIM_SPACES = "-trimSpaces";
protected static final String SWITCH_CLASSPATH = "-classpath";
protected static final String SWITCH_DIE = "-die";
protected static final String SWITCH_POOLING = "-poolingEnabled";
protected static final String SWITCH_ENCODING = "-javaEncoding";
protected static final String SWITCH_SMAP = "-smap";
protected static final String SWITCH_DUMP_SMAP = "-dumpsmap";
protected static final String SHOW_SUCCESS ="-s";
protected static final String LIST_ERRORS = "-l";
protected static final int INC_WEBXML = 10;
protected static final int ALL_WEBXML = 20;
protected static final int DEFAULT_DIE_LEVEL = 1;
protected static final int NO_DIE_LEVEL = 0;
protected static final Set<String> insertBefore = new HashSet<>();
static {
insertBefore.add("</web-app>");
insertBefore.add("<servlet-mapping>");
insertBefore.add("<session-config>");
insertBefore.add("<mime-mapping>");
insertBefore.add("<welcome-file-list>");
insertBefore.add("<error-page>");
insertBefore.add("<taglib>");
insertBefore.add("<resource-env-ref>");
insertBefore.add("<resource-ref>");
insertBefore.add("<security-constraint>");
insertBefore.add("<login-config>");
insertBefore.add("<security-role>");
insertBefore.add("<env-entry>");
insertBefore.add("<ejb-ref>");
insertBefore.add("<ejb-local-ref>");
}
protected String classPath = null;
protected ClassLoader loader = null;
protected boolean trimSpaces = false;
protected boolean genStringAsCharArray = false;
protected boolean validateXml;
protected boolean xpoweredBy;
protected boolean mappedFile = false;
protected boolean poolingEnabled = true;
protected File scratchDir;
protected String ieClassId = DEFAULT_IE_CLASS_ID;
protected String targetPackage;
protected String targetClassName;
protected String uriBase;
protected String uriRoot;
protected int dieLevel;
protected boolean helpNeeded = false;
protected boolean compile = false;
protected boolean smapSuppressed = true;
protected boolean smapDumped = false;
protected boolean caching = true;
protected final Map<String, TagLibraryInfo> cache = new HashMap<>();
protected String compiler = null;
protected String compilerTargetVM = "1.6";
protected String compilerSourceVM = "1.6";
protected boolean classDebugInfo = true;
/**
* Throw an exception if there's a compilation error, or swallow it.
* Default is true to preserve old behavior.
*/
protected boolean failOnError = true;
/**
* The file extensions to be handled as JSP files.
* Default list is .jsp and .jspx.
*/
protected List<String> extensions;
/**
* The pages.
*/
protected final List<String> pages = new Vector<>();
/**
* Needs better documentation, this data member does.
* True by default.
*/
protected boolean errorOnUseBeanInvalidClassAttribute = true;
/**
* The java file encoding. Default
* is UTF-8. Added per bugzilla 19622.
*/
protected String javaEncoding = "UTF-8";
// Generation of web.xml fragments
protected String webxmlFile;
protected int webxmlLevel;
protected String webxmlEncoding;
protected boolean addWebXmlMappings = false;
protected Writer mapout;
protected CharArrayWriter servletout;
protected CharArrayWriter mappingout;
/**
* The servlet context.
*/
protected JspCServletContext context;
/**
* The runtime context.
* Maintain a dummy JspRuntimeContext for compiling tag files.
*/
protected JspRuntimeContext rctxt;
/**
* Cache for the TLD locations
*/
protected TldLocationsCache tldLocationsCache = null;
protected JspConfig jspConfig = null;
protected TagPluginManager tagPluginManager = null;
protected boolean verbose = false;
protected boolean listErrors = false;
protected boolean showSuccess = false;
protected int argPos;
protected boolean fullstop = false;
protected String args[];
public static void main(String arg[]) {
if (arg.length == 0) {
System.out.println(Localizer.getMessage("jspc.usage"));
} else {
JspC jspc = new JspC();
try {
jspc.setArgs(arg);
if (jspc.helpNeeded) {
System.out.println(Localizer.getMessage("jspc.usage"));
} else {
jspc.execute();
}
} catch (JasperException je) {
System.err.println(je);
if (jspc.dieLevel != NO_DIE_LEVEL) {
System.exit(jspc.dieLevel);
}
} catch (BuildException je) {
System.err.println(je);
if (jspc.dieLevel != NO_DIE_LEVEL) {
System.exit(jspc.dieLevel);
}
}
}
}
/**
* Apply command-line arguments.
*
* @param arg
* The arguments
*/
public void setArgs(String[] arg) throws JasperException {
args = arg;
String tok;
dieLevel = NO_DIE_LEVEL;
while ((tok = nextArg()) != null) {
if (tok.equals(SWITCH_VERBOSE)) {
verbose = true;
showSuccess = true;
listErrors = true;
} else if (tok.equals(SWITCH_OUTPUT_DIR)) {
tok = nextArg();
setOutputDir( tok );
} else if (tok.equals(SWITCH_PACKAGE_NAME)) {
targetPackage = nextArg();
} else if (tok.equals(SWITCH_COMPILE)) {
compile=true;
} else if (tok.equals(SWITCH_CLASS_NAME)) {
targetClassName = nextArg();
} else if (tok.equals(SWITCH_URI_BASE)) {
uriBase=nextArg();
} else if (tok.equals(SWITCH_URI_ROOT)) {
setUriroot( nextArg());
} else if (tok.equals(SWITCH_FILE_WEBAPP)) {
setUriroot( nextArg());
} else if ( tok.equals( SHOW_SUCCESS ) ) {
showSuccess = true;
} else if ( tok.equals( LIST_ERRORS ) ) {
listErrors = true;
} else if (tok.equals(SWITCH_WEBAPP_INC)) {
webxmlFile = nextArg();
if (webxmlFile != null) {
webxmlLevel = INC_WEBXML;
}
} else if (tok.equals(SWITCH_WEBAPP_XML)) {
webxmlFile = nextArg();
if (webxmlFile != null) {
webxmlLevel = ALL_WEBXML;
}
} else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) {
setWebXmlEncoding(nextArg());
} else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) {
setAddWebXmlMappings(true);
} else if (tok.equals(SWITCH_MAPPED)) {
mappedFile = true;
} else if (tok.equals(SWITCH_XPOWERED_BY)) {
xpoweredBy = true;
} else if (tok.equals(SWITCH_TRIM_SPACES)) {
setTrimSpaces(true);
} else if (tok.equals(SWITCH_CACHE)) {
tok = nextArg();
if ("false".equals(tok)) {
caching = false;
} else {
caching = true;
}
} else if (tok.equals(SWITCH_CLASSPATH)) {
setClassPath(nextArg());
} else if (tok.startsWith(SWITCH_DIE)) {
try {
dieLevel = Integer.parseInt(
tok.substring(SWITCH_DIE.length()));
} catch (NumberFormatException nfe) {
dieLevel = DEFAULT_DIE_LEVEL;
}
} else if (tok.equals(SWITCH_HELP)) {
helpNeeded = true;
} else if (tok.equals(SWITCH_POOLING)) {
tok = nextArg();
if ("false".equals(tok)) {
poolingEnabled = false;
} else {
poolingEnabled = true;
}
} else if (tok.equals(SWITCH_ENCODING)) {
setJavaEncoding(nextArg());
} else if (tok.equals(SWITCH_SOURCE)) {
setCompilerSourceVM(nextArg());
} else if (tok.equals(SWITCH_TARGET)) {
setCompilerTargetVM(nextArg());
} else if (tok.equals(SWITCH_SMAP)) {
smapSuppressed = false;
} else if (tok.equals(SWITCH_DUMP_SMAP)) {
smapDumped = true;
} else {
if (tok.startsWith("-")) {
throw new JasperException("Unrecognized option: " + tok +
". Use -help for help.");
}
if (!fullstop) {
argPos--;
}
// Start treating the rest as JSP Pages
break;
}
}
// Add all extra arguments to the list of files
while( true ) {
String file = nextFile();
if( file==null ) {
break;
}
pages.add( file );
}
}
/**
* In JspC this always returns <code>true</code>.
* {@inheritDoc}
*/
@Override
public boolean getKeepGenerated() {
// isn't this why we are running jspc?
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getTrimSpaces() {
return trimSpaces;
}
/**
* Sets the option to trim white spaces between directives or actions.
*/
public void setTrimSpaces(boolean ts) {
this.trimSpaces = ts;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPoolingEnabled() {
return poolingEnabled;
}
/**
* Sets the option to enable the tag handler pooling.
*/
public void setPoolingEnabled(boolean poolingEnabled) {
this.poolingEnabled = poolingEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isXpoweredBy() {
return xpoweredBy;
}
/**
* Sets the option to enable generation of X-Powered-By response header.
*/
public void setXpoweredBy(boolean xpoweredBy) {
this.xpoweredBy = xpoweredBy;
}
/**
* In JspC this always returns <code>true</code>.
* {@inheritDoc}
*/
@Override
public boolean getDisplaySourceFragment() {
return true;
}
@Override
public int getMaxLoadedJsps() {
return -1;
}
@Override
public int getJspIdleTimeout() {
return -1;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getErrorOnUseBeanInvalidClassAttribute() {
return errorOnUseBeanInvalidClassAttribute;
}
/**
* Sets the option to issue a compilation error if the class attribute
* specified in useBean action is invalid.
*/
public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
errorOnUseBeanInvalidClassAttribute = b;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getMappedFile() {
return mappedFile;
}
/**
* Sets the option to include debug information in compiled class.
*/
public void setClassDebugInfo( boolean b ) {
classDebugInfo=b;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getClassDebugInfo() {
// compile with debug info
return classDebugInfo;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCaching() {
return caching;
}
/**
* Sets the option to enable caching.
*
* @see Options#isCaching()
*/
public void setCaching(boolean caching) {
this.caching = caching;
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, TagLibraryInfo> getCache() {
return cache;
}
/**
* In JspC this always returns <code>0</code>.
* {@inheritDoc}
*/
@Override
public int getCheckInterval() {
return 0;
}
/**
* In JspC this always returns <code>0</code>.
* {@inheritDoc}
*/
@Override
public int getModificationTestInterval() {
return 0;
}
/**
* In JspC this always returns <code>false</code>.
* {@inheritDoc}
*/
@Override
public boolean getRecompileOnFail() {
return false;
}
/**
* In JspC this always returns <code>false</code>.
* {@inheritDoc}
*/
@Override
public boolean getDevelopment() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSmapSuppressed() {
return smapSuppressed;
}
/**
* Sets smapSuppressed flag.
*/
public void setSmapSuppressed(boolean smapSuppressed) {
this.smapSuppressed = smapSuppressed;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSmapDumped() {
return smapDumped;
}
/**
* Sets smapDumped flag.
*
* @see Options#isSmapDumped()
*/
public void setSmapDumped(boolean smapDumped) {
this.smapDumped = smapDumped;
}
/**
* Determines whether text strings are to be generated as char arrays,
* which improves performance in some cases.
*
* @param genStringAsCharArray true if text strings are to be generated as
* char arrays, false otherwise
*/
public void setGenStringAsCharArray(boolean genStringAsCharArray) {
this.genStringAsCharArray = genStringAsCharArray;
}
/**
* {@inheritDoc}
*/
@Override
public boolean genStringAsCharArray() {
return genStringAsCharArray;
}
/**
* Sets the class-id value to be sent to Internet Explorer when using
* <jsp:plugin> tags.
*
* @param ieClassId
* Class-id value
*/
public void setIeClassId(String ieClassId) {
this.ieClassId = ieClassId;
}
/**
* {@inheritDoc}
*/
@Override
public String getIeClassId() {
return ieClassId;
}
/**
* {@inheritDoc}
*/
@Override
public File getScratchDir() {
return scratchDir;
}
/**
* {@inheritDoc}
*/
@Override
public String getCompiler() {
return compiler;
}
/**
* Sets the option to determine what compiler to use.
*
* @see Options#getCompiler()
*/
public void setCompiler(String c) {
compiler=c;
}
/**
* {@inheritDoc}
*/
@Override
public String getCompilerClassName() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String getCompilerTargetVM() {
return compilerTargetVM;
}
/**
* Sets the compiler target VM.
*
* @see Options#getCompilerTargetVM()
*/
public void setCompilerTargetVM(String vm) {
compilerTargetVM = vm;
}
/**
* {@inheritDoc}
*/
@Override
public String getCompilerSourceVM() {
return compilerSourceVM;
}
/**
* Sets the compiler source VM.
*
* @see Options#getCompilerSourceVM()
*/
public void setCompilerSourceVM(String vm) {
compilerSourceVM = vm;
}
/**
* {@inheritDoc}
*/
@Override
public TldLocationsCache getTldLocationsCache() {
return tldLocationsCache;
}
/**
* Returns the encoding to use for
* java files. The default is UTF-8.
*
* @return String The encoding
*/
@Override
public String getJavaEncoding() {
return javaEncoding;
}
/**
* Sets the encoding to use for
* java files.
*
* @param encodingName The name, e.g. "UTF-8"
*/
public void setJavaEncoding(String encodingName) {
javaEncoding = encodingName;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getFork() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String getClassPath() {
if( classPath != null )
return classPath;
return System.getProperty("java.class.path");
}
/**
* Sets the classpath used while compiling the servlets generated from JSP
* files
*/
public void setClassPath(String s) {
classPath=s;
}
/**
* Returns the list of file extensions
* that are treated as JSP files.
*
* @return The list of extensions
*/
public List<String> getExtensions() {
return extensions;
}
/**
* Adds the given file extension to the
* list of extensions handled as JSP files.
*
* @param extension The extension to add, e.g. "myjsp"
*/
protected void addExtension(final String extension) {
if(extension != null) {
if(extensions == null) {
extensions = new Vector<>();
}
extensions.add(extension);
}
}
/**
* Base dir for the webapp. Used to generate class names and resolve
* includes.
*/
public void setUriroot( String s ) {
if (s == null) {
uriRoot = null;
return;
}
try {
uriRoot = resolveFile(s).getCanonicalPath();
} catch( Exception ex ) {
uriRoot = s;
}
}
/**
* Parses comma-separated list of JSP files to be processed. If the argument
* is null, nothing is done.
*
* <p>Each file is interpreted relative to uriroot, unless it is absolute,
* in which case it must start with uriroot.</p>
*
* @param jspFiles Comma-separated list of JSP files to be processed
*/
public void setJspFiles(final String jspFiles) {
if(jspFiles == null) {
return;
}
StringTokenizer tok = new StringTokenizer(jspFiles, ",");
while (tok.hasMoreTokens()) {
pages.add(tok.nextToken());
}
}
/**
* Sets the compile flag.
*
* @param b Flag value
*/
public void setCompile( final boolean b ) {
compile = b;
}
/**
* Sets the verbosity level. The actual number doesn't
* matter: if it's greater than zero, the verbose flag will
* be true.
*
* @param level Positive means verbose
*/
public void setVerbose( final int level ) {
if (level > 0) {
verbose = true;
showSuccess = true;
listErrors = true;
}
}
public void setValidateXml( boolean b ) {
this.validateXml = b;
org.apache.jasper.xmlparser.ParserUtils.validating=b;
}
public void setListErrors( boolean b ) {
listErrors = b;
}
public void setOutputDir( String s ) {
if( s!= null ) {
scratchDir = resolveFile(s).getAbsoluteFile();
} else {
scratchDir=null;
}
}
/**
* Sets the package name to be used for the generated servlet classes.
*/
public void setPackage( String p ) {
targetPackage=p;
}
/**
* Class name of the generated file ( without package ).
* Can only be used if a single file is converted.
* XXX Do we need this feature ?
*/
public void setClassName( String p ) {
targetClassName=p;
}
/**
* File where we generate a web.xml fragment with the class definitions.
*/
public void setWebXmlFragment( String s ) {
webxmlFile=resolveFile(s).getAbsolutePath();
webxmlLevel=INC_WEBXML;
}
/**
* File where we generate a complete web.xml with the class definitions.
*/
public void setWebXml( String s ) {
webxmlFile=resolveFile(s).getAbsolutePath();
webxmlLevel=ALL_WEBXML;
}
/**
* Sets the encoding to be used to read and write web.xml files.
*
* <p>
* If not specified, defaults to the platform default encoding.
* </p>
*
* @param encoding
* Encoding, e.g. "UTF-8".
*/
public void setWebXmlEncoding(String encoding) {
webxmlEncoding = encoding;
}
/**
* Sets the option to merge generated web.xml fragment into the
* WEB-INF/web.xml file of the web application that we were processing.
*
* @param b
* <code>true</code> to merge the fragment into the existing
* web.xml file of the processed web application
* ({uriroot}/WEB-INF/web.xml), <code>false</code> to keep the
* generated web.xml fragment
*/
public void setAddWebXmlMappings(boolean b) {
addWebXmlMappings = b;
}
/**
* Sets the option that throws an exception in case of a compilation error.
*/
public void setFailOnError(final boolean b) {
failOnError = b;
}
/**
* Returns true if an exception will be thrown in case of a compilation
* error.
*/
public boolean getFailOnError() {
return failOnError;
}
/**
* {@inheritDoc}
*/
@Override
public JspConfig getJspConfig() {
return jspConfig;
}
/**
* {@inheritDoc}
*/
@Override
public TagPluginManager getTagPluginManager() {
return tagPluginManager;
}
/**
* Adds servlet declaration and mapping for the JSP page servlet to the
* generated web.xml fragment.
*
* @param file
* Context-relative path to the JSP file, e.g.
* <code>/index.jsp</code>
* @param clctxt
* Compilation context of the servlet
*/
public void generateWebMapping( String file, JspCompilationContext clctxt )
throws IOException
{
if (log.isDebugEnabled()) {
log.debug("Generating web mapping for file " + file
+ " using compilation context " + clctxt);
}
String className = clctxt.getServletClassName();
String packageName = clctxt.getServletPackageName();
String thisServletName;
if ("".equals(packageName)) {
thisServletName = className;
} else {
thisServletName = packageName + '.' + className;
}
if (servletout != null) {
servletout.write("\n <servlet>\n <servlet-name>");
servletout.write(thisServletName);
servletout.write("</servlet-name>\n <servlet-class>");
servletout.write(thisServletName);
servletout.write("</servlet-class>\n </servlet>\n");
}
if (mappingout != null) {
mappingout.write("\n <servlet-mapping>\n <servlet-name>");
mappingout.write(thisServletName);
mappingout.write("</servlet-name>\n <url-pattern>");
mappingout.write(file.replace('\\', '/'));
mappingout.write("</url-pattern>\n </servlet-mapping>\n");
}
}
/**
* Include the generated web.xml inside the webapp's web.xml.
*/
protected void mergeIntoWebXml() throws IOException {
File webappBase = new File(uriRoot);
File webXml = new File(webappBase, "WEB-INF/web.xml");
File webXml2 = new File(webappBase, "WEB-INF/web2.xml");
String insertStartMarker =
Localizer.getMessage("jspc.webinc.insertStart");
String insertEndMarker =
Localizer.getMessage("jspc.webinc.insertEnd");
BufferedReader reader = new BufferedReader(openWebxmlReader(webXml));
BufferedReader fragmentReader = new BufferedReader(
openWebxmlReader(new File(webxmlFile)));
PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2));
// Insert the <servlet> and <servlet-mapping> declarations
boolean inserted = false;
int current = reader.read();
while (current > -1) {
if (current == '<') {
String element = getElement(reader);
if (!inserted && insertBefore.contains(element)) {
// Insert generated content here
writer.println(insertStartMarker);
while (true) {
String line = fragmentReader.readLine();
if (line == null) {
writer.println();
break;
}
writer.println(line);
}
writer.println(insertEndMarker);
writer.println();
writer.write(element);
inserted = true;
} else if (element.equals(insertStartMarker)) {
// Skip the previous auto-generated content
while (true) {
current = reader.read();
if (current < 0) {
throw new EOFException();
}
if (current == '<') {
element = getElement(reader);
if (element.equals(insertEndMarker)) {
break;
}
}
}
current = reader.read();
while (current == '\n' || current == '\r') {
current = reader.read();
}
continue;
} else {
writer.write(element);
}
} else {
writer.write(current);
}
current = reader.read();
}
writer.close();
reader.close();
fragmentReader.close();
FileInputStream fis = new FileInputStream(webXml2);
FileOutputStream fos = new FileOutputStream(webXml);
byte buf[] = new byte[512];
while (true) {
int n = fis.read(buf);
if (n < 0) {
break;
}
fos.write(buf, 0, n);
}
fis.close();
fos.close();
if(!webXml2.delete() && log.isDebugEnabled())
log.debug(Localizer.getMessage("jspc.delete.fail",
webXml2.toString()));
if (!(new File(webxmlFile)).delete() && log.isDebugEnabled())
log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile));
}
/*
* Assumes valid xml
*/
private String getElement(Reader reader) throws IOException {
StringBuilder result = new StringBuilder();
result.append('<');
boolean done = false;
while (!done) {
int current = reader.read();
while (current != '>') {
if (current < 0) {
throw new EOFException();
}
result.append((char) current);
current = reader.read();
}
result.append((char) current);
int len = result.length();
if (len > 4 && result.substring(0, 4).equals("<!--")) {
// This is a comment - make sure we are at the end
if (len >= 7 && result.substring(len - 3, len).equals("-->")) {
done = true;
}
} else {
done = true;
}
}
return result.toString();
}
protected void processFile(String file)
throws JasperException
{
if (log.isDebugEnabled()) {
log.debug("Processing file: " + file);
}
ClassLoader originalClassLoader = null;
try {
// set up a scratch/output dir if none is provided
if (scratchDir == null) {
String temp = System.getProperty("java.io.tmpdir");
if (temp == null) {
temp = "";
}
scratchDir = new File(new File(temp).getAbsolutePath());
}
String jspUri=file.replace('\\','/');
JspCompilationContext clctxt = new JspCompilationContext
( jspUri, this, context, null, rctxt );
/* Override the defaults */
if ((targetClassName != null) && (targetClassName.length() > 0)) {
clctxt.setServletClassName(targetClassName);
targetClassName = null;
}
if (targetPackage != null) {
clctxt.setServletPackageName(targetPackage);
}
originalClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(loader);
clctxt.setClassLoader(loader);
clctxt.setClassPath(classPath);
Compiler clc = clctxt.createCompiler();
// If compile is set, generate both .java and .class, if
// .jsp file is newer than .class file;
// Otherwise only generate .java, if .jsp file is newer than
// the .java file
if( clc.isOutDated(compile) ) {
if (log.isDebugEnabled()) {
log.debug(jspUri + " is out dated, compiling...");
}
clc.compile(compile, true);
}
// Generate mapping
generateWebMapping( file, clctxt );
if ( showSuccess ) {
log.info( "Built File: " + file );
}
} catch (JasperException je) {
Throwable rootCause = je;
while (rootCause instanceof JasperException
&& ((JasperException) rootCause).getRootCause() != null) {
rootCause = ((JasperException) rootCause).getRootCause();
}
if (rootCause != je) {
log.error(Localizer.getMessage("jspc.error.generalException",
file),
rootCause);
}
// Bugzilla 35114.
if(getFailOnError()) {
throw je;
} else {
log.error(je.getMessage());
}
} catch (Exception e) {
if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist",
e.getMessage()));
}
throw new JasperException(e);
} finally {
if(originalClassLoader != null) {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
}
/**
* Locate all jsp files in the webapp. Used if no explicit
* jsps are specified.
*/
public void scanFiles( File base ) {
Stack<String> dirs = new Stack<>();
dirs.push(base.toString());
// Make sure default extensions are always included
if ((getExtensions() == null) || (getExtensions().size() < 2)) {
addExtension("jsp");
addExtension("jspx");
}
while (!dirs.isEmpty()) {
String s = dirs.pop();
File f = new File(s);
if (f.exists() && f.isDirectory()) {
String[] files = f.list();
String ext;
for (int i = 0; (files != null) && i < files.length; i++) {
File f2 = new File(s, files[i]);
if (f2.isDirectory()) {
dirs.push(f2.getPath());
} else {
String path = f2.getPath();
String uri = path.substring(uriRoot.length());
ext = files[i].substring(files[i].lastIndexOf('.') +1);
if (getExtensions().contains(ext) ||
jspConfig.isJspPage(uri)) {
pages.add(path);
}
}
}
}
}
}
/**
* Executes the compilation.
*/
@Override
public void execute() {
if(log.isDebugEnabled()) {
log.debug("execute() starting for " + pages.size() + " pages.");
}
try {
if (uriRoot == null) {
if( pages.size() == 0 ) {
throw new JasperException(
Localizer.getMessage("jsp.error.jspc.missingTarget"));
}
String firstJsp = pages.get( 0 );
File firstJspF = new File( firstJsp );
if (!firstJspF.exists()) {
throw new JasperException(
Localizer.getMessage("jspc.error.fileDoesNotExist",
firstJsp));
}
locateUriRoot( firstJspF );
}
if (uriRoot == null) {
throw new JasperException(
Localizer.getMessage("jsp.error.jspc.no_uriroot"));
}
File uriRootF = new File(uriRoot);
if (!uriRootF.isDirectory()) {
throw new JasperException(
Localizer.getMessage("jsp.error.jspc.uriroot_not_dir"));
}
if (loader == null) {
loader = initClassLoader();
}
if (context == null) {
initServletContext(loader);
}
// No explicit pages, we'll process all .jsp in the webapp
if (pages.size() == 0) {
scanFiles(uriRootF);
}
initWebXml();
Iterator<String> iter = pages.iterator();
while (iter.hasNext()) {
String nextjsp = iter.next().toString();
File fjsp = new File(nextjsp);
if (!fjsp.isAbsolute()) {
fjsp = new File(uriRootF, nextjsp);
}
if (!fjsp.exists()) {
if (log.isWarnEnabled()) {
log.warn
(Localizer.getMessage
("jspc.error.fileDoesNotExist", fjsp.toString()));
}
continue;
}
String s = fjsp.getAbsolutePath();
if (s.startsWith(uriRoot)) {
nextjsp = s.substring(uriRoot.length());
}
if (nextjsp.startsWith("." + File.separatorChar)) {
nextjsp = nextjsp.substring(2);
}
processFile(nextjsp);
}
completeWebXml();
if (addWebXmlMappings) {
mergeIntoWebXml();
}
} catch (IOException ioe) {
throw new BuildException(ioe);
} catch (JasperException je) {
Throwable rootCause = je;
while (rootCause instanceof JasperException
&& ((JasperException) rootCause).getRootCause() != null) {
rootCause = ((JasperException) rootCause).getRootCause();
}
if (rootCause != je) {
rootCause.printStackTrace();
}
throw new BuildException(je);
} finally {
if (loader != null) {
LogFactory.release(loader);
}
}
}
// ==================== protected utility methods ====================
protected String nextArg() {
if ((argPos >= args.length)
|| (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
return null;
} else {
return args[argPos++];
}
}
protected String nextFile() {
if (fullstop) argPos++;
if (argPos >= args.length) {
return null;
} else {
return args[argPos++];
}
}
protected void initWebXml() {
try {
if (webxmlLevel >= INC_WEBXML) {
mapout = openWebxmlWriter(new File(webxmlFile));
servletout = new CharArrayWriter();
mappingout = new CharArrayWriter();
} else {
mapout = null;
servletout = null;
mappingout = null;
}
if (webxmlLevel >= ALL_WEBXML) {
mapout.write(Localizer.getMessage("jspc.webxml.header"));
mapout.flush();
} else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
mapout.write(Localizer.getMessage("jspc.webinc.header"));
mapout.flush();
}
} catch (IOException ioe) {
mapout = null;
servletout = null;
mappingout = null;
}
}
protected void completeWebXml() {
if (mapout != null) {
try {
servletout.writeTo(mapout);
mappingout.writeTo(mapout);
if (webxmlLevel >= ALL_WEBXML) {
mapout.write(Localizer.getMessage("jspc.webxml.footer"));
} else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) {
mapout.write(Localizer.getMessage("jspc.webinc.footer"));
}
mapout.close();
} catch (IOException ioe) {
// nothing to do if it fails since we are done with it
}
}
}
protected void initServletContext(ClassLoader classLoader)
throws IOException, JasperException {
// TODO: should we use the Ant Project's log?
PrintWriter log = new PrintWriter(System.out);
URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL();
context = new JspCServletContext(log, resourceBase, classLoader);
TldScanner scanner = new TldScanner(context, true, validateXml);
scanner.setClassLoader(classLoader);
try {
scanner.scan();
} catch (SAXException e) {
throw new JasperException(e);
}
tldLocationsCache = new TldLocationsCache(scanner.getTaglibMap());
context.setAttribute(TldLocationsCache.KEY, tldLocationsCache);
rctxt = new JspRuntimeContext(context, this);
jspConfig = new JspConfig(context);
tagPluginManager = new TagPluginManager(context);
}
/**
* Initializes the classloader as/if needed for the given
* compilation context.
*
* @throws IOException If an error occurs
*/
protected ClassLoader initClassLoader() throws IOException {
classPath = getClassPath();
ClassLoader jspcLoader = getClass().getClassLoader();
if (jspcLoader instanceof AntClassLoader) {
classPath += File.pathSeparator
+ ((AntClassLoader) jspcLoader).getClasspath();
}
// Turn the classPath into URLs
ArrayList<URL> urls = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(classPath,
File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
String path = tokenizer.nextToken();
try {
File libFile = new File(path);
urls.add(libFile.toURI().toURL());
} catch (IOException ioe) {
// Failing a toCanonicalPath on a file that
// exists() should be a JVM regression test,
// therefore we have permission to freak uot
throw new RuntimeException(ioe.toString());
}
}
File webappBase = new File(uriRoot);
if (webappBase.exists()) {
File classes = new File(webappBase, "/WEB-INF/classes");
try {
if (classes.exists()) {
classPath = classPath + File.pathSeparator
+ classes.getCanonicalPath();
urls.add(classes.getCanonicalFile().toURI().toURL());
}
} catch (IOException ioe) {
// failing a toCanonicalPath on a file that
// exists() should be a JVM regression test,
// therefore we have permission to freak out
throw new RuntimeException(ioe.toString());
}
File lib = new File(webappBase, "/WEB-INF/lib");
if (lib.exists() && lib.isDirectory()) {
String[] libs = lib.list();
for (int i = 0; i < libs.length; i++) {
if( libs[i].length() <5 ) continue;
String ext=libs[i].substring( libs[i].length() - 4 );
if (! ".jar".equalsIgnoreCase(ext)) {
if (".tld".equalsIgnoreCase(ext)) {
log.warn("TLD files should not be placed in "
+ "/WEB-INF/lib");
}
continue;
}
try {
File libFile = new File(lib, libs[i]);
classPath = classPath + File.pathSeparator
+ libFile.getAbsolutePath();
urls.add(libFile.getAbsoluteFile().toURI().toURL());
} catch (IOException ioe) {
// failing a toCanonicalPath on a file that
// exists() should be a JVM regression test,
// therefore we have permission to freak out
throw new RuntimeException(ioe.toString());
}
}
}
}
URL urlsA[]=new URL[urls.size()];
urls.toArray(urlsA);
loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
return loader;
}
/**
* Find the WEB-INF dir by looking up in the directory tree.
* This is used if no explicit docbase is set, but only files.
* XXX Maybe we should require the docbase.
*/
protected void locateUriRoot( File f ) {
String tUriBase = uriBase;
if (tUriBase == null) {
tUriBase = "/";
}
try {
if (f.exists()) {
f = new File(f.getAbsolutePath());
while (true) {
File g = new File(f, "WEB-INF");
if (g.exists() && g.isDirectory()) {
uriRoot = f.getCanonicalPath();
uriBase = tUriBase;
if (log.isInfoEnabled()) {
log.info(Localizer.getMessage(
"jspc.implicit.uriRoot",
uriRoot));
}
break;
}
if (f.exists() && f.isDirectory()) {
tUriBase = "/" + f.getName() + "/" + tUriBase;
}
String fParent = f.getParent();
if (fParent == null) {
break;
} else {
f = new File(fParent);
}
// If there is no acceptable candidate, uriRoot will
// remain null to indicate to the CompilerContext to
// use the current working/user dir.
}
if (uriRoot != null) {
File froot = new File(uriRoot);
uriRoot = froot.getCanonicalPath();
}
}
} catch (IOException ioe) {
// since this is an optional default and a null value
// for uriRoot has a non-error meaning, we can just
// pass straight through
}
}
/**
* Resolves the relative or absolute pathname correctly
* in both Ant and command-line situations. If Ant launched
* us, we should use the basedir of the current project
* to resolve relative paths.
*
* See Bugzilla 35571.
*
* @param s The file
* @return The file resolved
*/
protected File resolveFile(final String s) {
if(getProject() == null) {
// Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3
return FileUtils.getFileUtils().resolveFile(null, s);
} else {
return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s);
}
}
private Reader openWebxmlReader(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
try {
return webxmlEncoding != null ? new InputStreamReader(fis,
webxmlEncoding) : new InputStreamReader(fis);
} catch (IOException ex) {
fis.close();
throw ex;
}
}
private Writer openWebxmlWriter(File file) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
try {
return webxmlEncoding != null ? new OutputStreamWriter(fos,
webxmlEncoding) : new OutputStreamWriter(fos);
} catch (IOException ex) {
fos.close();
throw ex;
}
}
}
|
54,095
|
Bug 54095 [patch] support gzipped versions of static resources by DefaultServlet
| null |
resolved fixed
|
f0101d0
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-10T21:24:59Z
| 2012-11-04T00:46:40Z
|
java/org/apache/catalina/servlets/DefaultServlet.java
|
/*
* 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.servlets;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.catalina.Globals;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.connector.RequestFacade;
import org.apache.catalina.connector.ResponseFacade;
import org.apache.catalina.util.RequestUtil;
import org.apache.catalina.util.ServerInfo;
import org.apache.catalina.util.URLEncoder;
import org.apache.tomcat.util.res.StringManager;
/**
* <p>The default resource-serving servlet for most web applications,
* used to serve static resources such as HTML pages and images.
* </p>
* <p>
* This servlet is intended to be mapped to <em>/</em> e.g.:
* </p>
* <pre>
* <servlet-mapping>
* <servlet-name>default</servlet-name>
* <url-pattern>/</url-pattern>
* </servlet-mapping>
* </pre>
* <p>It can be mapped to sub-paths, however in all cases resources are served
* from the web appplication resource root using the full path from the root
* of the web application context.
* <br/>e.g. given a web application structure:
*</p>
* <pre>
* /context
* /images
* tomcat2.jpg
* /static
* /images
* tomcat.jpg
* </pre>
* <p>
* ... and a servlet mapping that maps only <code>/static/*</code> to the default servlet:
* </p>
* <pre>
* <servlet-mapping>
* <servlet-name>default</servlet-name>
* <url-pattern>/static/*</url-pattern>
* </servlet-mapping>
* </pre>
* <p>
* Then a request to <code>/context/static/images/tomcat.jpg</code> will succeed
* while a request to <code>/context/images/tomcat2.jpg</code> will fail.
* </p>
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Id$
*/
public class DefaultServlet
extends HttpServlet {
private static final long serialVersionUID = 1L;
// ----------------------------------------------------- Instance Variables
/**
* The debugging detail level for this servlet.
*/
protected int debug = 0;
/**
* The input buffer size to use when serving resources.
*/
protected int input = 2048;
/**
* Should we generate directory listings?
*/
protected boolean listings = false;
/**
* Read only flag. By default, it's set to true.
*/
protected boolean readOnly = true;
/**
* The output buffer size to use when serving resources.
*/
protected int output = 2048;
/**
* Array containing the safe characters set.
*/
protected static final URLEncoder urlEncoder;
/**
* Allow customized directory listing per directory.
*/
protected String localXsltFile = null;
/**
* Allow customized directory listing per context.
*/
protected String contextXsltFile = null;
/**
* Allow customized directory listing per instance.
*/
protected String globalXsltFile = null;
/**
* Allow a readme file to be included.
*/
protected String readmeFile = null;
/**
* The complete set of web application resources
*/
protected transient WebResourceRoot resources = null;
/**
* File encoding to be used when reading static files. If none is specified
* the platform default is used.
*/
protected String fileEncoding = null;
/**
* Minimum size for sendfile usage in bytes.
*/
protected int sendfileSize = 48 * 1024;
/**
* Should the Accept-Ranges: bytes header be send with static resources?
*/
protected boolean useAcceptRanges = true;
/**
* Full range marker.
*/
protected static final ArrayList<Range> FULL = new ArrayList<>();
// ----------------------------------------------------- Static Initializer
/**
* GMT timezone - all HTTP dates are on GMT
*/
static {
urlEncoder = new URLEncoder();
urlEncoder.addSafeCharacter('-');
urlEncoder.addSafeCharacter('_');
urlEncoder.addSafeCharacter('.');
urlEncoder.addSafeCharacter('*');
urlEncoder.addSafeCharacter('/');
}
/**
* MIME multipart separation string
*/
protected static final String mimeSeparation = "CATALINA_MIME_BOUNDARY";
/**
* JNDI resources name.
*/
protected static final String RESOURCES_JNDI_NAME = "java:/comp/Resources";
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Size of file transfer buffer in bytes.
*/
protected static final int BUFFER_SIZE = 4096;
// --------------------------------------------------------- Public Methods
/**
* Finalize this servlet.
*/
@Override
public void destroy() {
// NOOP
}
/**
* Initialize this servlet.
*/
@Override
public void init() throws ServletException {
if (getServletConfig().getInitParameter("debug") != null)
debug = Integer.parseInt(getServletConfig().getInitParameter("debug"));
if (getServletConfig().getInitParameter("input") != null)
input = Integer.parseInt(getServletConfig().getInitParameter("input"));
if (getServletConfig().getInitParameter("output") != null)
output = Integer.parseInt(getServletConfig().getInitParameter("output"));
listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings"));
if (getServletConfig().getInitParameter("readonly") != null)
readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly"));
if (getServletConfig().getInitParameter("sendfileSize") != null)
sendfileSize =
Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024;
fileEncoding = getServletConfig().getInitParameter("fileEncoding");
globalXsltFile = getServletConfig().getInitParameter("globalXsltFile");
contextXsltFile = getServletConfig().getInitParameter("contextXsltFile");
localXsltFile = getServletConfig().getInitParameter("localXsltFile");
readmeFile = getServletConfig().getInitParameter("readmeFile");
if (getServletConfig().getInitParameter("useAcceptRanges") != null)
useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges"));
// Sanity check on the specified buffer sizes
if (input < 256)
input = 256;
if (output < 256)
output = 256;
if (debug > 0) {
log("DefaultServlet.init: input buffer size=" + input +
", output buffer size=" + output);
}
// Load the web resources
resources = (WebResourceRoot) getServletContext().getAttribute(
Globals.RESOURCES_ATTR);
if (resources == null) {
throw new UnavailableException("No resources");
}
}
// ------------------------------------------------------ Protected Methods
/**
* Return the relative path associated with this servlet.
*
* @param request The servlet request we are processing
*/
protected String getRelativePath(HttpServletRequest request) {
// IMPORTANT: DefaultServlet can be mapped to '/' or '/path/*' but always
// serves resources from the web app root with context rooted paths.
// i.e. it can not be used to mount the web app root under a sub-path
// This method must construct a complete context rooted path, although
// subclasses can change this behaviour.
// Are we being processed by a RequestDispatcher.include()?
if (request.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
String result = (String) request.getAttribute(
RequestDispatcher.INCLUDE_PATH_INFO);
if (result == null) {
result = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
} else {
result = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH) + result;
}
if ((result == null) || (result.equals(""))) {
result = "/";
}
return (result);
}
// No, extract the desired path directly from the request
String result = request.getPathInfo();
if (result == null) {
result = request.getServletPath();
} else {
result = request.getServletPath() + result;
}
if ((result == null) || (result.equals(""))) {
result = "/";
}
return (result);
}
/**
* Determines the appropriate path to prepend resources with
* when generating directory listings. Depending on the behaviour of
* {@link #getRelativePath(HttpServletRequest)} this will change.
* @param request the request to determine the path for
* @return the prefix to apply to all resources in the listing.
*/
protected String getPathPrefix(final HttpServletRequest request) {
return request.getContextPath();
}
/**
* Process a GET request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Serve the requested resource, including the data content
serveResource(request, response, true, fileEncoding);
}
/**
* Process a HEAD request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doHead(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Serve the requested resource, without the data content
serveResource(request, response, false, fileEncoding);
}
/**
* Override default implementation to ensure that TRACE is correctly
* handled.
*
* @param req the {@link HttpServletRequest} object that
* contains the request the client made of
* the servlet
*
* @param resp the {@link HttpServletResponse} object that
* contains the response the servlet returns
* to the client
*
* @exception IOException if an input or output error occurs
* while the servlet is handling the
* OPTIONS request
*
* @exception ServletException if the request for the
* OPTIONS cannot be handled
*/
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
StringBuilder allow = new StringBuilder();
// There is a doGet method
allow.append("GET, HEAD");
// There is a doPost
allow.append(", POST");
// There is a doPut
allow.append(", PUT");
// There is a doDelete
allow.append(", DELETE");
// Trace - assume disabled unless we can prove otherwise
if (req instanceof RequestFacade &&
((RequestFacade) req).getAllowTrace()) {
allow.append(", TRACE");
}
// Always allow options
allow.append(", OPTIONS");
resp.setHeader("Allow", allow.toString());
}
/**
* Process a POST request for the specified resource.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
/**
* Process a PUT request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
WebResource resource = resources.getResource(path);
Range range = parseContentRange(req, resp);
InputStream resourceInputStream = null;
try {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
// Assume just one range is specified for now
if (range != null) {
File contentFile = executePartialPut(req, range, path);
resourceInputStream = new FileInputStream(contentFile);
} else {
resourceInputStream = req.getInputStream();
}
if (resources.write(path, resourceInputStream, true)) {
if (resource.exists()) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
}
} else {
resp.sendError(HttpServletResponse.SC_CONFLICT);
}
} finally {
if (resourceInputStream != null) {
try {
resourceInputStream.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
/**
* Handle a partial PUT. New content specified in request is appended to
* existing content in oldRevisionContent (if present). This code does
* not support simultaneous partial updates to the same resource.
*/
protected File executePartialPut(HttpServletRequest req, Range range,
String path)
throws IOException {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
File tempDir = (File) getServletContext().getAttribute
(ServletContext.TEMPDIR);
// Convert all '/' characters to '.' in resourcePath
String convertedResourcePath = path.replace('/', '.');
File contentFile = new File(tempDir, convertedResourcePath);
if (contentFile.createNewFile()) {
// Clean up contentFile when Tomcat is terminated
contentFile.deleteOnExit();
}
RandomAccessFile randAccessContentFile =
new RandomAccessFile(contentFile, "rw");
WebResource oldResource = resources.getResource(path);
// Copy data in oldRevisionContent to contentFile
if (oldResource.isFile()) {
BufferedInputStream bufOldRevStream =
new BufferedInputStream(oldResource.getInputStream(),
BUFFER_SIZE);
int numBytesRead;
byte[] copyBuffer = new byte[BUFFER_SIZE];
while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) {
randAccessContentFile.write(copyBuffer, 0, numBytesRead);
}
bufOldRevStream.close();
}
randAccessContentFile.setLength(range.length);
// Append data in request input stream to contentFile
randAccessContentFile.seek(range.start);
int numBytesRead;
byte[] transferBuffer = new byte[BUFFER_SIZE];
BufferedInputStream requestBufInStream =
new BufferedInputStream(req.getInputStream(), BUFFER_SIZE);
while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
randAccessContentFile.write(transferBuffer, 0, numBytesRead);
}
randAccessContentFile.close();
requestBufInStream.close();
return contentFile;
}
/**
* Process a DELETE request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
WebResource resource = resources.getResource(path);
if (resource.exists()) {
if (resource.delete()) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
} else {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Check if the conditions specified in the optional If headers are
* satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets all the specified conditions,
* and false if any of the conditions is not satisfied, in which case
* request processing is stopped
*/
protected boolean checkIfHeaders(HttpServletRequest request,
HttpServletResponse response,
WebResource resource)
throws IOException {
return checkIfMatch(request, response, resource)
&& checkIfModifiedSince(request, response, resource)
&& checkIfNoneMatch(request, response, resource)
&& checkIfUnmodifiedSince(request, response, resource);
}
/**
* URL rewriter.
*
* @param path Path which has to be rewritten
*/
protected String rewriteUrl(String path) {
return urlEncoder.encode( path );
}
/**
* Serve the specified resource, optionally including the data content.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param content Should the content be included?
* @param encoding The encoding to use if it is necessary to access the
* source as characters rather than as bytes
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
protected void serveResource(HttpServletRequest request,
HttpServletResponse response,
boolean content,
String encoding)
throws IOException, ServletException {
boolean serveContent = content;
// Identify the requested resource path
String path = getRelativePath(request);
if (debug > 0) {
if (serveContent)
log("DefaultServlet.serveResource: Serving resource '" +
path + "' headers and data");
else
log("DefaultServlet.serveResource: Serving resource '" +
path + "' headers only");
}
WebResource resource = resources.getResource(path);
if (!resource.exists()) {
// Check if we're included so we can return the appropriate
// missing resource name in the error
String requestUri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI);
if (requestUri == null) {
requestUri = request.getRequestURI();
} else {
// We're included
// SRV.9.3 says we must throw a FNFE
throw new FileNotFoundException(
sm.getString("defaultServlet.missingResource",
requestUri));
}
response.sendError(HttpServletResponse.SC_NOT_FOUND,
requestUri);
return;
}
// If the resource is not a collection, and the resource path
// ends with "/" or "\", return NOT FOUND
if (resource.isFile()) {
if (path.endsWith("/") || (path.endsWith("\\"))) {
// Check if we're included so we can return the appropriate
// missing resource name in the error
String requestUri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI);
if (requestUri == null) {
requestUri = request.getRequestURI();
}
response.sendError(HttpServletResponse.SC_NOT_FOUND,
requestUri);
return;
}
}
boolean isError =
response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
// Check if the conditions specified in the optional If headers are
// satisfied.
if (resource.isFile()) {
// Checking If headers
boolean included = (request.getAttribute(
RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
if (!included && !isError &&
!checkIfHeaders(request, response, resource)) {
return;
}
}
// Find content type.
String contentType = resource.getMimeType();
if (contentType == null) {
contentType = getServletContext().getMimeType(resource.getName());
resource.setMimeType(contentType);
}
ArrayList<Range> ranges = null;
long contentLength = -1L;
if (resource.isDirectory()) {
// Skip directory listings if we have been configured to
// suppress them
if (!listings) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
request.getRequestURI());
return;
}
contentType = "text/html;charset=UTF-8";
} else {
if (!isError) {
if (useAcceptRanges) {
// Accept ranges header
response.setHeader("Accept-Ranges", "bytes");
}
// Parse range specifier
ranges = parseRange(request, response, resource);
// ETag header
response.setHeader("ETag", resource.getETag());
// Last-Modified header
response.setHeader("Last-Modified",
resource.getLastModifiedHttp());
}
// Get content length
contentLength = resource.getContentLength();
// Special case for zero length files, which would cause a
// (silent) ISE when setting the output buffer size
if (contentLength == 0L) {
serveContent = false;
}
}
ServletOutputStream ostream = null;
PrintWriter writer = null;
if (serveContent) {
// Trying to retrieve the servlet output stream
try {
ostream = response.getOutputStream();
} catch (IllegalStateException e) {
// If it fails, we try to get a Writer instead if we're
// trying to serve a text file
if ( (contentType == null)
|| (contentType.startsWith("text"))
|| (contentType.endsWith("xml"))
|| (contentType.contains("/javascript")) ) {
writer = response.getWriter();
// Cannot reliably serve partial content with a Writer
ranges = FULL;
} else {
throw e;
}
}
}
// Check to see if a Filter, Valve of wrapper has written some content.
// If it has, disable range requests and setting of a content length
// since neither can be done reliably.
ServletResponse r = response;
long contentWritten = 0;
while (r instanceof ServletResponseWrapper) {
r = ((ServletResponseWrapper) r).getResponse();
}
if (r instanceof ResponseFacade) {
contentWritten = ((ResponseFacade) r).getContentWritten();
}
if (contentWritten > 0) {
ranges = FULL;
}
if (resource.isDirectory() ||
isError ||
( (ranges == null || ranges.isEmpty())
&& request.getHeader("Range") == null ) ||
ranges == FULL ) {
// Set the appropriate output headers
if (contentType != null) {
if (debug > 0)
log("DefaultServlet.serveFile: contentType='" +
contentType + "'");
response.setContentType(contentType);
}
if (resource.isFile() && contentLength >= 0 &&
(!serveContent || ostream != null)) {
if (debug > 0)
log("DefaultServlet.serveFile: contentLength=" +
contentLength);
// Don't set a content length if something else has already
// written to the response.
if (contentWritten == 0) {
response.setContentLengthLong(contentLength);
}
}
InputStream renderResult = null;
if (resource.isDirectory()) {
if (serveContent) {
// Serve the directory browser
renderResult = render(getPathPrefix(request), resource);
}
}
// Copy the input stream to our output stream (if requested)
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
if (!checkSendfile(request, response, resource,
contentLength, null))
copy(resource, renderResult, ostream);
} else {
copy(resource, renderResult, writer, encoding);
}
}
} else {
if ((ranges == null) || (ranges.isEmpty()))
return;
// Partial content response.
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (ranges.size() == 1) {
Range range = ranges.get(0);
response.addHeader("Content-Range", "bytes "
+ range.start
+ "-" + range.end + "/"
+ range.length);
long length = range.end - range.start + 1;
response.setContentLengthLong(length);
if (contentType != null) {
if (debug > 0)
log("DefaultServlet.serveFile: contentType='" +
contentType + "'");
response.setContentType(contentType);
}
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
if (!checkSendfile(request, response, resource,
range.end - range.start + 1, range))
copy(resource, ostream, range);
} else {
// we should not get here
throw new IllegalStateException();
}
}
} else {
response.setContentType("multipart/byteranges; boundary="
+ mimeSeparation);
if (serveContent) {
try {
response.setBufferSize(output);
} catch (IllegalStateException e) {
// Silent catch
}
if (ostream != null) {
copy(resource, ostream, ranges.iterator(),
contentType);
} else {
// we should not get here
throw new IllegalStateException();
}
}
}
}
}
/**
* Parse the content-range header.
*
* @param request The servlet request we a)re processing
* @param response The servlet response we are creating
* @return Range
*/
protected Range parseContentRange(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
// Retrieving the content-range header (if any is specified
String rangeHeader = request.getHeader("Content-Range");
if (rangeHeader == null)
return null;
// bytes is the only range unit supported
if (!rangeHeader.startsWith("bytes")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
rangeHeader = rangeHeader.substring(6).trim();
int dashPos = rangeHeader.indexOf('-');
int slashPos = rangeHeader.indexOf('/');
if (dashPos == -1) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
if (slashPos == -1) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
Range range = new Range();
try {
range.start = Long.parseLong(rangeHeader.substring(0, dashPos));
range.end =
Long.parseLong(rangeHeader.substring(dashPos + 1, slashPos));
range.length = Long.parseLong
(rangeHeader.substring(slashPos + 1, rangeHeader.length()));
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
if (!range.validate()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
return range;
}
/**
* Parse the range header.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return Vector of ranges
*/
protected ArrayList<Range> parseRange(HttpServletRequest request,
HttpServletResponse response,
WebResource resource) throws IOException {
// Checking If-Range
String headerValue = request.getHeader("If-Range");
if (headerValue != null) {
long headerValueTime = (-1L);
try {
headerValueTime = request.getDateHeader("If-Range");
} catch (IllegalArgumentException e) {
// Ignore
}
String eTag = resource.getETag();
long lastModified = resource.getLastModified();
if (headerValueTime == (-1L)) {
// If the ETag the client gave does not match the entity
// etag, then the entire entity is returned.
if (!eTag.equals(headerValue.trim()))
return FULL;
} else {
// If the timestamp of the entity the client got is older than
// the last modification date of the entity, the entire entity
// is returned.
if (lastModified > (headerValueTime + 1000))
return FULL;
}
}
long fileLength = resource.getContentLength();
if (fileLength == 0)
return null;
// Retrieving the range header (if any is specified
String rangeHeader = request.getHeader("Range");
if (rangeHeader == null)
return null;
// bytes is the only range unit supported (and I don't see the point
// of adding new ones).
if (!rangeHeader.startsWith("bytes")) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
rangeHeader = rangeHeader.substring(6);
// Vector which will contain all the ranges which are successfully
// parsed.
ArrayList<Range> result = new ArrayList<>();
StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ",");
// Parsing the range list
while (commaTokenizer.hasMoreTokens()) {
String rangeDefinition = commaTokenizer.nextToken().trim();
Range currentRange = new Range();
currentRange.length = fileLength;
int dashPos = rangeDefinition.indexOf('-');
if (dashPos == -1) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
if (dashPos == 0) {
try {
long offset = Long.parseLong(rangeDefinition);
currentRange.start = fileLength + offset;
currentRange.end = fileLength - 1;
} catch (NumberFormatException e) {
response.addHeader("Content-Range",
"bytes */" + fileLength);
response.sendError
(HttpServletResponse
.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
} else {
try {
currentRange.start = Long.parseLong
(rangeDefinition.substring(0, dashPos));
if (dashPos < rangeDefinition.length() - 1)
currentRange.end = Long.parseLong
(rangeDefinition.substring
(dashPos + 1, rangeDefinition.length()));
else
currentRange.end = fileLength - 1;
} catch (NumberFormatException e) {
response.addHeader("Content-Range",
"bytes */" + fileLength);
response.sendError
(HttpServletResponse
.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
}
if (!currentRange.validate()) {
response.addHeader("Content-Range", "bytes */" + fileLength);
response.sendError
(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
result.add(currentRange);
}
return result;
}
/**
* Decide which way to render. HTML or XML.
*/
protected InputStream render(String contextPath, WebResource resource)
throws IOException, ServletException {
InputStream xsltInputStream =
findXsltInputStream(resource);
if (xsltInputStream==null) {
return renderHtml(contextPath, resource);
}
return renderXml(contextPath, resource, xsltInputStream);
}
/**
* Return an InputStream to an HTML representation of the contents
* of this directory.
*
* @param contextPath Context path to which our internal paths are
* relative
*/
protected InputStream renderXml(String contextPath,
WebResource resource,
InputStream xsltInputStream)
throws IOException, ServletException {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<listing ");
sb.append(" contextPath='");
sb.append(contextPath);
sb.append("'");
sb.append(" directory='");
sb.append(resource.getName());
sb.append("' ");
sb.append(" hasParent='").append(!resource.getName().equals("/"));
sb.append("'>");
sb.append("<entries>");
String[] entries = resources.list(resource.getWebappPath());
// rewriteUrl(contextPath) is expensive. cache result for later reuse
String rewrittenContextPath = rewriteUrl(contextPath);
String directoryWebappPath = resource.getWebappPath();
for (String entry : entries) {
if (entry.equalsIgnoreCase("WEB-INF") ||
entry.equalsIgnoreCase("META-INF") ||
entry.equalsIgnoreCase(localXsltFile))
continue;
if ((directoryWebappPath + entry).equals(contextXsltFile))
continue;
WebResource childResource =
resources.getResource(directoryWebappPath + entry);
if (!childResource.exists()) {
continue;
}
sb.append("<entry");
sb.append(" type='")
.append(childResource.isDirectory()?"dir":"file")
.append("'");
sb.append(" urlPath='")
.append(rewrittenContextPath)
.append(rewriteUrl(directoryWebappPath + entry))
.append(childResource.isDirectory()?"/":"")
.append("'");
if (childResource.isFile()) {
sb.append(" size='")
.append(renderSize(childResource.getContentLength()))
.append("'");
}
sb.append(" date='")
.append(childResource.getLastModifiedHttp())
.append("'");
sb.append(">");
sb.append(RequestUtil.filter(entry));
if (childResource.isDirectory())
sb.append("/");
sb.append("</entry>");
}
sb.append("</entries>");
String readme = getReadme(resource);
if (readme!=null) {
sb.append("<readme><![CDATA[");
sb.append(readme);
sb.append("]]></readme>");
}
sb.append("</listing>");
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xmlSource = new StreamSource(new StringReader(sb.toString()));
Source xslSource = new StreamSource(xsltInputStream);
Transformer transformer = tFactory.newTransformer(xslSource);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
StreamResult out = new StreamResult(osWriter);
transformer.transform(xmlSource, out);
osWriter.flush();
return (new ByteArrayInputStream(stream.toByteArray()));
} catch (TransformerException e) {
throw new ServletException("XSL transformer error", e);
}
}
/**
* Return an InputStream to an HTML representation of the contents
* of this directory.
*
* @param contextPath Context path to which our internal paths are
* relative
*/
protected InputStream renderHtml(String contextPath, WebResource resource)
throws IOException {
String name = resource.getName();
// Prepare a writer to a buffered area
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
PrintWriter writer = new PrintWriter(osWriter);
StringBuilder sb = new StringBuilder();
String[] entries = resources.list(resource.getWebappPath());
// rewriteUrl(contextPath) is expensive. cache result for later reuse
String rewrittenContextPath = rewriteUrl(contextPath);
String directoryWebappPath = resource.getWebappPath();
// Render the page header
sb.append("<html>\r\n");
sb.append("<head>\r\n");
sb.append("<title>");
sb.append(sm.getString("directory.title", name));
sb.append("</title>\r\n");
sb.append("<STYLE><!--");
sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS);
sb.append("--></STYLE> ");
sb.append("</head>\r\n");
sb.append("<body>");
sb.append("<h1>");
sb.append(sm.getString("directory.title", name));
// Render the link to our parent (if required)
String parentDirectory = name;
if (parentDirectory.endsWith("/")) {
parentDirectory =
parentDirectory.substring(0, parentDirectory.length() - 1);
}
int slash = parentDirectory.lastIndexOf('/');
if (slash >= 0) {
String parent = name.substring(0, slash);
sb.append(" - <a href=\"");
sb.append(rewrittenContextPath);
if (parent.equals(""))
parent = "/";
sb.append(rewriteUrl(parent));
if (!parent.endsWith("/"))
sb.append("/");
sb.append("\">");
sb.append("<b>");
sb.append(sm.getString("directory.parent", parent));
sb.append("</b>");
sb.append("</a>");
}
sb.append("</h1>");
sb.append("<HR size=\"1\" noshade=\"noshade\">");
sb.append("<table width=\"100%\" cellspacing=\"0\"" +
" cellpadding=\"5\" align=\"center\">\r\n");
// Render the column headings
sb.append("<tr>\r\n");
sb.append("<td align=\"left\"><font size=\"+1\"><strong>");
sb.append(sm.getString("directory.filename"));
sb.append("</strong></font></td>\r\n");
sb.append("<td align=\"center\"><font size=\"+1\"><strong>");
sb.append(sm.getString("directory.size"));
sb.append("</strong></font></td>\r\n");
sb.append("<td align=\"right\"><font size=\"+1\"><strong>");
sb.append(sm.getString("directory.lastModified"));
sb.append("</strong></font></td>\r\n");
sb.append("</tr>");
boolean shade = false;
for (String entry : entries) {
if (entry.equalsIgnoreCase("WEB-INF") ||
entry.equalsIgnoreCase("META-INF"))
continue;
WebResource childResource =
resources.getResource(directoryWebappPath + entry);
if (!childResource.exists()) {
continue;
}
sb.append("<tr");
if (shade)
sb.append(" bgcolor=\"#eeeeee\"");
sb.append(">\r\n");
shade = !shade;
sb.append("<td align=\"left\"> \r\n");
sb.append("<a href=\"");
sb.append(rewrittenContextPath);
sb.append(rewriteUrl(directoryWebappPath + entry));
if (childResource.isDirectory())
sb.append("/");
sb.append("\"><tt>");
sb.append(RequestUtil.filter(entry));
if (childResource.isDirectory())
sb.append("/");
sb.append("</tt></a></td>\r\n");
sb.append("<td align=\"right\"><tt>");
if (childResource.isDirectory())
sb.append(" ");
else
sb.append(renderSize(childResource.getContentLength()));
sb.append("</tt></td>\r\n");
sb.append("<td align=\"right\"><tt>");
sb.append(childResource.getLastModifiedHttp());
sb.append("</tt></td>\r\n");
sb.append("</tr>\r\n");
}
// Render the page footer
sb.append("</table>\r\n");
sb.append("<HR size=\"1\" noshade=\"noshade\">");
String readme = getReadme(resource);
if (readme!=null) {
sb.append(readme);
sb.append("<HR size=\"1\" noshade=\"noshade\">");
}
sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");
sb.append("</body>\r\n");
sb.append("</html>\r\n");
// Return an input stream to the underlying bytes
writer.write(sb.toString());
writer.flush();
return (new ByteArrayInputStream(stream.toByteArray()));
}
/**
* Render the specified file size (in bytes).
*
* @param size File size (in bytes)
*/
protected String renderSize(long size) {
long leftSide = size / 1024;
long rightSide = (size % 1024) / 103; // Makes 1 digit
if ((leftSide == 0) && (rightSide == 0) && (size > 0))
rightSide = 1;
return ("" + leftSide + "." + rightSide + " kb");
}
/**
* Get the readme file as a string.
*/
protected String getReadme(WebResource directory) {
if (readmeFile != null) {
WebResource resource = resources.getResource(
directory.getWebappPath() + readmeFile);
if (resource.isFile()) {
StringWriter buffer = new StringWriter();
InputStream is = resource.getInputStream();
copyRange(new InputStreamReader(is),
new PrintWriter(buffer));
return buffer.toString();
} else {
if (debug > 10)
log("readme '" + readmeFile + "' not found");
return null;
}
}
return null;
}
/**
* Return the xsl template inputstream (if possible)
*/
protected InputStream findXsltInputStream(WebResource directory)
throws IOException {
if (localXsltFile != null) {
WebResource resource = resources.getResource(
directory.getWebappPath() + localXsltFile);
if (resource.isFile()) {
InputStream is = resource.getInputStream();
if (is != null) {
return is;
}
}
if (debug > 10) {
log("localXsltFile '" + localXsltFile + "' not found");
}
}
if (contextXsltFile != null) {
InputStream is =
getServletContext().getResourceAsStream(contextXsltFile);
if (is != null)
return is;
if (debug > 10)
log("contextXsltFile '" + contextXsltFile + "' not found");
}
/* Open and read in file in one fell swoop to reduce chance
* chance of leaving handle open.
*/
if (globalXsltFile!=null) {
FileInputStream fis = null;
try {
File f = new File(globalXsltFile);
if (f.exists()){
fis =new FileInputStream(f);
byte b[] = new byte[(int)f.length()]; /* danger! */
fis.read(b);
return new ByteArrayInputStream(b);
}
} finally {
if (fis!=null)
fis.close();
}
}
return null;
}
// -------------------------------------------------------- protected Methods
/**
* Check if sendfile can be used.
*/
protected boolean checkSendfile(HttpServletRequest request,
HttpServletResponse response,
WebResource resource,
long length, Range range) {
if (sendfileSize > 0
&& resource.isFile()
&& length > sendfileSize
&& (resource.getCanonicalPath() != null)
&& (Boolean.TRUE == request.getAttribute(Globals.SENDFILE_SUPPORTED_ATTR))
&& (request.getClass().getName().equals("org.apache.catalina.connector.RequestFacade"))
&& (response.getClass().getName().equals("org.apache.catalina.connector.ResponseFacade"))) {
request.setAttribute(Globals.SENDFILE_FILENAME_ATTR, resource.getCanonicalPath());
if (range == null) {
request.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(0L));
request.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(length));
} else {
request.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(range.start));
request.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(range.end + 1));
}
return true;
}
return false;
}
/**
* Check if the if-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfMatch(HttpServletRequest request,
HttpServletResponse response, WebResource resource)
throws IOException {
String eTag = resource.getETag();
String headerValue = request.getHeader("If-Match");
if (headerValue != null) {
if (headerValue.indexOf('*') == -1) {
StringTokenizer commaTokenizer = new StringTokenizer
(headerValue, ",");
boolean conditionSatisfied = false;
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
// If none of the given ETags match, 412 Precodition failed is
// sent back
if (!conditionSatisfied) {
response.sendError
(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
}
return true;
}
/**
* Check if the if-modified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfModifiedSince(HttpServletRequest request,
HttpServletResponse response, WebResource resource) {
try {
long headerValue = request.getDateHeader("If-Modified-Since");
long lastModified = resource.getLastModified();
if (headerValue != -1) {
// If an If-None-Match header has been specified, if modified since
// is ignored.
if ((request.getHeader("If-None-Match") == null)
&& (lastModified < headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", resource.getETag());
return false;
}
}
} catch (IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Check if the if-none-match condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfNoneMatch(HttpServletRequest request,
HttpServletResponse response, WebResource resource)
throws IOException {
String eTag = resource.getETag();
String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!headerValue.equals("*")) {
StringTokenizer commaTokenizer =
new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(eTag))
conditionSatisfied = true;
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
// For GET and HEAD, we should respond with
// 304 Not Modified.
// For every other method, 412 Precondition Failed is sent
// back.
if ( ("GET".equals(request.getMethod()))
|| ("HEAD".equals(request.getMethod())) ) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", eTag);
return false;
}
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
return true;
}
/**
* Check if the if-unmodified-since condition is satisfied.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param resource The resource
* @return boolean true if the resource meets the specified condition,
* and false if the condition is not satisfied, in which case request
* processing is stopped
*/
protected boolean checkIfUnmodifiedSince(HttpServletRequest request,
HttpServletResponse response, WebResource resource)
throws IOException {
try {
long lastModified = resource.getLastModified();
long headerValue = request.getDateHeader("If-Unmodified-Since");
if (headerValue != -1) {
if ( lastModified >= (headerValue + 1000)) {
// The entity has not been modified since the date
// specified by the client. This is not an error case.
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
} catch(IllegalArgumentException illegalArgument) {
return true;
}
return true;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param is The input stream to read the source resource from
* @param ostream The output stream to write to
*
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, InputStream is,
ServletOutputStream ostream)
throws IOException {
IOException exception = null;
InputStream resourceInputStream = null;
// Optimization: If the binary content has already been loaded, send
// it directly
if (resource.isFile()) {
byte buffer[] = resource.getContent();
if (buffer != null) {
ostream.write(buffer, 0, buffer.length);
return;
}
resourceInputStream = resource.getInputStream();
} else {
resourceInputStream = is;
}
InputStream istream = new BufferedInputStream
(resourceInputStream, input);
// Copy the input stream to the output stream
exception = copyRange(istream, ostream);
// Clean up the input stream
istream.close();
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param is The input stream to read the source resource from
* @param writer The writer to write to
* @param encoding The encoding to use when reading the source input stream
*
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, InputStream is, PrintWriter writer,
String encoding) throws IOException {
IOException exception = null;
InputStream resourceInputStream = null;
if (resource.isFile()) {
resourceInputStream = resource.getInputStream();
} else {
resourceInputStream = is;
}
Reader reader;
if (encoding == null) {
reader = new InputStreamReader(resourceInputStream);
} else {
reader = new InputStreamReader(resourceInputStream, encoding);
}
// Copy the input stream to the output stream
exception = copyRange(reader, writer);
// Clean up the reader
reader.close();
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param ostream The output stream to write to
* @param range Range the client wanted to retrieve
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, ServletOutputStream ostream,
Range range)
throws IOException {
IOException exception = null;
InputStream resourceInputStream = resource.getInputStream();
InputStream istream =
new BufferedInputStream(resourceInputStream, input);
exception = copyRange(istream, ostream, range.start, range.end);
// Clean up the input stream
istream.close();
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param resource The source resource
* @param ostream The output stream to write to
* @param ranges Enumeration of the ranges the client wanted to
* retrieve
* @param contentType Content type of the resource
* @exception IOException if an input/output error occurs
*/
protected void copy(WebResource resource, ServletOutputStream ostream,
Iterator<Range> ranges, String contentType)
throws IOException {
IOException exception = null;
while ( (exception == null) && (ranges.hasNext()) ) {
InputStream resourceInputStream = resource.getInputStream();
InputStream istream =
new BufferedInputStream(resourceInputStream, input);
Range currentRange = ranges.next();
// Writing MIME header.
ostream.println();
ostream.println("--" + mimeSeparation);
if (contentType != null)
ostream.println("Content-Type: " + contentType);
ostream.println("Content-Range: bytes " + currentRange.start
+ "-" + currentRange.end + "/"
+ currentRange.length);
ostream.println();
// Printing content
exception = copyRange(istream, ostream, currentRange.start,
currentRange.end);
istream.close();
}
ostream.println();
ostream.print("--" + mimeSeparation + "--");
// Rethrow any exception that has occurred
if (exception != null)
throw exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param istream The input stream to read from
* @param ostream The output stream to write to
* @return Exception which occurred during processing
*/
protected IOException copyRange(InputStream istream,
ServletOutputStream ostream) {
// Copy the input stream to the output stream
IOException exception = null;
byte buffer[] = new byte[input];
int len = buffer.length;
while (true) {
try {
len = istream.read(buffer);
if (len == -1)
break;
ostream.write(buffer, 0, len);
} catch (IOException e) {
exception = e;
len = -1;
break;
}
}
return exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param reader The reader to read from
* @param writer The writer to write to
* @return Exception which occurred during processing
*/
protected IOException copyRange(Reader reader, PrintWriter writer) {
// Copy the input stream to the output stream
IOException exception = null;
char buffer[] = new char[input];
int len = buffer.length;
while (true) {
try {
len = reader.read(buffer);
if (len == -1)
break;
writer.write(buffer, 0, len);
} catch (IOException e) {
exception = e;
len = -1;
break;
}
}
return exception;
}
/**
* Copy the contents of the specified input stream to the specified
* output stream, and ensure that both streams are closed before returning
* (even in the face of an exception).
*
* @param istream The input stream to read from
* @param ostream The output stream to write to
* @param start Start of the range which will be copied
* @param end End of the range which will be copied
* @return Exception which occurred during processing
*/
protected IOException copyRange(InputStream istream,
ServletOutputStream ostream,
long start, long end) {
if (debug > 10)
log("Serving bytes:" + start + "-" + end);
long skipped = 0;
try {
skipped = istream.skip(start);
} catch (IOException e) {
return e;
}
if (skipped < start) {
return new IOException(sm.getString("defaultservlet.skipfail",
Long.valueOf(skipped), Long.valueOf(start)));
}
IOException exception = null;
long bytesToRead = end - start + 1;
byte buffer[] = new byte[input];
int len = buffer.length;
while ( (bytesToRead > 0) && (len >= buffer.length)) {
try {
len = istream.read(buffer);
if (bytesToRead >= len) {
ostream.write(buffer, 0, len);
bytesToRead -= len;
} else {
ostream.write(buffer, 0, (int) bytesToRead);
bytesToRead = 0;
}
} catch (IOException e) {
exception = e;
len = -1;
}
if (len < buffer.length)
break;
}
return exception;
}
// ------------------------------------------------------ Range Inner Class
protected static class Range {
public long start;
public long end;
public long length;
/**
* Validate range.
*/
public boolean validate() {
if (end >= length)
end = length - 1;
return (start >= 0) && (end >= 0) && (start <= end) && (length > 0);
}
}
}
|
54,095
|
Bug 54095 [patch] support gzipped versions of static resources by DefaultServlet
| null |
resolved fixed
|
f0101d0
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-10T21:24:59Z
| 2012-11-04T00:46:40Z
|
test/org/apache/catalina/servlets/TestDefaultServlet.java
|
/*
* 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.servlets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import static org.apache.catalina.startup.SimpleHttpClient.CRLF;
import org.apache.catalina.startup.SimpleHttpClient;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.descriptor.web.ApplicationListener;
import org.apache.tomcat.websocket.server.WsContextListener;
public class TestDefaultServlet extends TomcatBaseTest {
/**
* Test attempting to access special paths (WEB-INF/META-INF) using
* DefaultServlet.
*/
@Test
public void testGetSpecials() throws Exception {
Tomcat tomcat = getTomcatInstance();
String contextPath = "/examples";
File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
// app dir is relative to server home
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
tomcat.start();
final ByteChunk res = new ByteChunk();
int rc =getUrl("http://localhost:" + getPort() + contextPath +
"/WEB-INF/web.xml", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/WEB-INF/doesntexistanywhere", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/WEB-INF/", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/META-INF/MANIFEST.MF", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/META-INF/doesntexistanywhere", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
}
/**
* Test https://issues.apache.org/bugzilla/show_bug.cgi?id=50026
* Verify serving of resources from context root with subpath mapping.
*/
@Test
public void testGetWithSubpathmount() throws Exception {
Tomcat tomcat = getTomcatInstance();
String contextPath = "/examples";
File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
// app dir is relative to server home
org.apache.catalina.Context ctx =
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
ctx.addApplicationListener(new ApplicationListener(
WsContextListener.class.getName(), false));
// Override the default servlet with our own mappings
Tomcat.addServlet(ctx, "default2", new DefaultServlet());
ctx.addServletMapping("/", "default2");
ctx.addServletMapping("/servlets/*", "default2");
ctx.addServletMapping("/static/*", "default2");
tomcat.start();
final ByteChunk res = new ByteChunk();
// Make sure DefaultServlet isn't exposing special directories
// by remounting the webapp under a sub-path
int rc =getUrl("http://localhost:" + getPort() + contextPath +
"/static/WEB-INF/web.xml", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/static/WEB-INF/doesntexistanywhere", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/static/WEB-INF/", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/static/META-INF/MANIFEST.MF", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/static/META-INF/doesntexistanywhere", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
// Make sure DefaultServlet is serving resources relative to the
// context root regardless of where the it is mapped
final ByteChunk rootResource = new ByteChunk();
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/index.html", rootResource, null);
assertEquals(HttpServletResponse.SC_OK, rc);
final ByteChunk subpathResource = new ByteChunk();
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/servlets/index.html", subpathResource, null);
assertEquals(HttpServletResponse.SC_OK, rc);
assertFalse(rootResource.toString().equals(subpathResource.toString()));
rc =getUrl("http://localhost:" + getPort() + contextPath +
"/static/index.html", res, null);
assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
}
/**
* Test https://issues.apache.org/bugzilla/show_bug.cgi?id=50413 Serving a
* custom error page
*/
@Test
public void testCustomErrorPage() throws Exception {
File appDir = new File(getTemporaryDirectory(), "MyApp");
File webInf = new File(appDir, "WEB-INF");
addDeleteOnTearDown(appDir);
if (!webInf.mkdirs() && !webInf.isDirectory()) {
fail("Unable to create directory [" + webInf + "]");
}
Writer w = new OutputStreamWriter(new FileOutputStream(new File(appDir,
"WEB-INF/web.xml")), "UTF-8");
try {
w.write("<?xml version='1.0' encoding='UTF-8'?>\n"
+ "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' "
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
+ " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee "
+ " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'"
+ " version='2.4'>\n"
+ "<error-page>\n<error-code>404</error-code>\n"
+ "<location>/404.html</location>\n</error-page>\n"
+ "</web-app>\n");
w.flush();
} finally {
w.close();
}
w = new OutputStreamWriter(new FileOutputStream(new File(appDir,
"404.html")), "ISO-8859-1");
try {
w.write("It is 404.html");
w.flush();
} finally {
w.close();
}
Tomcat tomcat = getTomcatInstance();
String contextPath = "/MyApp";
tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath());
tomcat.start();
TestCustomErrorClient client =
new TestCustomErrorClient(tomcat.getConnector().getLocalPort());
client.reset();
client.setRequest(new String[] {
"GET /MyApp/missing HTTP/1.0" +CRLF + CRLF });
client.connect();
client.processRequest();
assertTrue(client.isResponse404());
assertEquals("It is 404.html", client.getResponseBody());
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String tomorrow = format.format(new Date(System.currentTimeMillis()
+ 24 * 60 * 60 * 1000));
// https://issues.apache.org/bugzilla/show_bug.cgi?id=50413
//
client.reset();
client.setRequest(new String[] {
"GET /MyApp/missing HTTP/1.1" + CRLF +
"Host: localhost" + CRLF +
"Connection: close" + CRLF +
"If-Modified-Since: " + tomorrow + CRLF + CRLF });
client.connect();
client.processRequest();
assertTrue(client.isResponse404());
assertEquals("It is 404.html", client.getResponseBody());
// https://issues.apache.org/bugzilla/show_bug.cgi?id=50413#c6
//
client.reset();
client.setRequest(new String[] {
"GET /MyApp/missing HTTP/1.1" + CRLF +
"Host: localhost" + CRLF +
"Connection: close" + CRLF +
"Range: bytes=0-100" + CRLF + CRLF });
client.connect();
client.processRequest();
assertTrue(client.isResponse404());
assertEquals("It is 404.html", client.getResponseBody());
}
/**
* Test what happens if a custom 404 page is configured,
* but its file is actually missing.
*/
@Test
public void testCustomErrorPageMissing() throws Exception {
File appDir = new File(getTemporaryDirectory(), "MyApp");
File webInf = new File(appDir, "WEB-INF");
addDeleteOnTearDown(appDir);
if (!webInf.mkdirs() && !webInf.isDirectory()) {
fail("Unable to create directory [" + webInf + "]");
}
Writer w = new OutputStreamWriter(new FileOutputStream(new File(appDir,
"WEB-INF/web.xml")), "UTF-8");
try {
w.write("<?xml version='1.0' encoding='UTF-8'?>\n"
+ "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' "
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
+ " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee "
+ " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'"
+ " version='2.4'>\n"
+ "<error-page>\n<error-code>404</error-code>\n"
+ "<location>/404-absent.html</location>\n</error-page>\n"
+ "</web-app>\n");
w.flush();
} finally {
w.close();
}
Tomcat tomcat = getTomcatInstance();
String contextPath = "/MyApp";
tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath());
tomcat.start();
TestCustomErrorClient client =
new TestCustomErrorClient(tomcat.getConnector().getLocalPort());
client.reset();
client.setRequest(new String[] {
"GET /MyApp/missing HTTP/1.0" + CRLF + CRLF });
client.connect();
client.processRequest();
assertTrue(client.isResponse404());
}
public static int getUrl(String path, ByteChunk out,
Map<String, List<String>> resHead) throws IOException {
out.recycle();
return TomcatBaseTest.getUrl(path, out, resHead);
}
private static class TestCustomErrorClient extends SimpleHttpClient {
public TestCustomErrorClient(int port) {
setPort(port);
}
@Override
public boolean isResponseBodyOK() {
return true;
}
}
}
|
55,656
|
Bug 55656 Server ClassLoader not used for Server creation
| null |
resolved fixed
|
86ec1f4
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-17T15:26:13Z
| 2013-10-16T13:26:40Z
|
java/org/apache/catalina/startup/Catalina.java
|
/*
* 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.startup;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.ConnectException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.LogManager;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Server;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.security.SecurityConfig;
import org.apache.juli.ClassLoaderLogManager;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.digester.Digester;
import org.apache.tomcat.util.digester.Rule;
import org.apache.tomcat.util.digester.RuleSet;
import org.apache.tomcat.util.log.SystemLogHandler;
import org.apache.tomcat.util.res.StringManager;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
/**
* Startup/Shutdown shell program for Catalina. The following command line
* options are recognized:
* <ul>
* <li><b>-config {pathname}</b> - Set the pathname of the configuration file
* to be processed. If a relative path is specified, it will be
* interpreted as relative to the directory pathname specified by the
* "catalina.base" system property. [conf/server.xml]
* <li><b>-help</b> - Display usage information.
* <li><b>-nonaming</b> - Disable naming support.
* <li><b>configtest</b> - Try to test the config
* <li><b>start</b> - Start an instance of Catalina.
* <li><b>stop</b> - Stop the currently running instance of Catalina.
* </u>
*
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Id$
*/
public class Catalina {
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
// ----------------------------------------------------- Instance Variables
/**
* Use await.
*/
protected boolean await = false;
/**
* Pathname to the server configuration file.
*/
protected String configFile = "conf/server.xml";
// XXX Should be moved to embedded
/**
* The shared extensions class loader for this server.
*/
protected ClassLoader parentClassLoader =
Catalina.class.getClassLoader();
/**
* The server component we are starting or stopping.
*/
protected Server server = null;
/**
* Use shutdown hook flag.
*/
protected boolean useShutdownHook = true;
/**
* Shutdown hook.
*/
protected Thread shutdownHook = null;
/**
* Is naming enabled ?
*/
protected boolean useNaming = true;
// ----------------------------------------------------------- Constructors
public Catalina() {
setSecurityProtection();
}
// ------------------------------------------------------------- Properties
public void setConfigFile(String file) {
configFile = file;
}
public String getConfigFile() {
return configFile;
}
public void setUseShutdownHook(boolean useShutdownHook) {
this.useShutdownHook = useShutdownHook;
}
public boolean getUseShutdownHook() {
return useShutdownHook;
}
/**
* Set the shared extensions class loader.
*
* @param parentClassLoader The shared extensions class loader.
*/
public void setParentClassLoader(ClassLoader parentClassLoader) {
this.parentClassLoader = parentClassLoader;
}
public ClassLoader getParentClassLoader() {
if (parentClassLoader != null) {
return (parentClassLoader);
}
return ClassLoader.getSystemClassLoader();
}
public void setServer(Server server) {
this.server = server;
}
public Server getServer() {
return server;
}
/**
* Return true if naming is enabled.
*/
public boolean isUseNaming() {
return (this.useNaming);
}
/**
* Enables or disables naming support.
*
* @param useNaming The new use naming value
*/
public void setUseNaming(boolean useNaming) {
this.useNaming = useNaming;
}
public void setAwait(boolean b) {
await = b;
}
public boolean isAwait() {
return await;
}
// ------------------------------------------------------ Protected Methods
/**
* Process the specified command line arguments, and return
* <code>true</code> if we should continue processing; otherwise
* return <code>false</code>.
*
* @param args Command line arguments to process
*/
protected boolean arguments(String args[]) {
boolean isConfig = false;
if (args.length < 1) {
usage();
return false;
}
for (int i = 0; i < args.length; i++) {
if (isConfig) {
configFile = args[i];
isConfig = false;
} else if (args[i].equals("-config")) {
isConfig = true;
} else if (args[i].equals("-nonaming")) {
setUseNaming(false);
} else if (args[i].equals("-help")) {
usage();
return false;
} else if (args[i].equals("start")) {
// NOOP
} else if (args[i].equals("configtest")) {
// NOOP
} else if (args[i].equals("stop")) {
// NOOP
} else {
usage();
return false;
}
}
return true;
}
/**
* Return a File object representing our configuration file.
*/
protected File configFile() {
File file = new File(configFile);
if (!file.isAbsolute()) {
file = new File(Bootstrap.getCatalinaBase(), configFile);
}
return (file);
}
/**
* Create and configure the Digester we will be using for startup.
*/
protected Digester createStartDigester() {
long t1=System.currentTimeMillis();
// Initialize the digester
Digester digester = new Digester();
digester.setValidating(false);
digester.setRulesValidation(true);
HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>();
ArrayList<String> attrs = new ArrayList<>();
attrs.add("className");
fakeAttributes.put(Object.class, attrs);
digester.setFakeAttributes(fakeAttributes);
digester.setClassLoader(StandardServer.class.getClassLoader());
// Configure the actions we will be using
digester.addObjectCreate("Server",
"org.apache.catalina.core.StandardServer",
"className");
digester.addSetProperties("Server");
digester.addSetNext("Server",
"setServer",
"org.apache.catalina.Server");
digester.addObjectCreate("Server/GlobalNamingResources",
"org.apache.catalina.deploy.NamingResourcesImpl");
digester.addSetProperties("Server/GlobalNamingResources");
digester.addSetNext("Server/GlobalNamingResources",
"setGlobalNamingResources",
"org.apache.catalina.deploy.NamingResourcesImpl");
digester.addObjectCreate("Server/Listener",
null, // MUST be specified in the element
"className");
digester.addSetProperties("Server/Listener");
digester.addSetNext("Server/Listener",
"addLifecycleListener",
"org.apache.catalina.LifecycleListener");
digester.addObjectCreate("Server/Service",
"org.apache.catalina.core.StandardService",
"className");
digester.addSetProperties("Server/Service");
digester.addSetNext("Server/Service",
"addService",
"org.apache.catalina.Service");
digester.addObjectCreate("Server/Service/Listener",
null, // MUST be specified in the element
"className");
digester.addSetProperties("Server/Service/Listener");
digester.addSetNext("Server/Service/Listener",
"addLifecycleListener",
"org.apache.catalina.LifecycleListener");
//Executor
digester.addObjectCreate("Server/Service/Executor",
"org.apache.catalina.core.StandardThreadExecutor",
"className");
digester.addSetProperties("Server/Service/Executor");
digester.addSetNext("Server/Service/Executor",
"addExecutor",
"org.apache.catalina.Executor");
digester.addRule("Server/Service/Connector",
new ConnectorCreateRule());
digester.addRule("Server/Service/Connector",
new SetAllPropertiesRule(new String[]{"executor"}));
digester.addSetNext("Server/Service/Connector",
"addConnector",
"org.apache.catalina.connector.Connector");
digester.addObjectCreate("Server/Service/Connector/Listener",
null, // MUST be specified in the element
"className");
digester.addSetProperties("Server/Service/Connector/Listener");
digester.addSetNext("Server/Service/Connector/Listener",
"addLifecycleListener",
"org.apache.catalina.LifecycleListener");
// Add RuleSets for nested elements
digester.addRuleSet(new NamingRuleSet("Server/GlobalNamingResources/"));
digester.addRuleSet(new EngineRuleSet("Server/Service/"));
digester.addRuleSet(new HostRuleSet("Server/Service/Engine/"));
digester.addRuleSet(new ContextRuleSet("Server/Service/Engine/Host/"));
addClusterRuleSet(digester, "Server/Service/Engine/Host/Cluster/");
digester.addRuleSet(new NamingRuleSet("Server/Service/Engine/Host/Context/"));
// When the 'engine' is found, set the parentClassLoader.
digester.addRule("Server/Service/Engine",
new SetParentClassLoaderRule(parentClassLoader));
addClusterRuleSet(digester, "Server/Service/Engine/Cluster/");
long t2=System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Digester for server.xml created " + ( t2-t1 ));
}
return (digester);
}
/**
* Cluster support is optional. The JARs may have been removed.
*/
private void addClusterRuleSet(Digester digester, String prefix) {
Class<?> clazz = null;
Constructor<?> constructor = null;
try {
clazz = Class.forName("org.apache.catalina.ha.ClusterRuleSet");
constructor = clazz.getConstructor(String.class);
RuleSet ruleSet = (RuleSet) constructor.newInstance(prefix);
digester.addRuleSet(ruleSet);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.noCluster",
e.getClass().getName() + ": " + e.getMessage()), e);
} else if (log.isInfoEnabled()) {
log.info(sm.getString("catalina.noCluster",
e.getClass().getName() + ": " + e.getMessage()));
}
}
}
/**
* Create and configure the Digester we will be using for shutdown.
*/
protected Digester createStopDigester() {
// Initialize the digester
Digester digester = new Digester();
// Configure the rules we need for shutting down
digester.addObjectCreate("Server",
"org.apache.catalina.core.StandardServer",
"className");
digester.addSetProperties("Server");
digester.addSetNext("Server",
"setServer",
"org.apache.catalina.Server");
return (digester);
}
public void stopServer() {
stopServer(null);
}
public void stopServer(String[] arguments) {
if (arguments != null) {
arguments(arguments);
}
Server s = getServer();
if( s == null ) {
// Create and execute our Digester
Digester digester = createStopDigester();
digester.setClassLoader(Thread.currentThread().getContextClassLoader());
File file = configFile();
FileInputStream fis = null;
try {
InputSource is =
new InputSource(file.toURI().toURL().toString());
fis = new FileInputStream(file);
is.setByteStream(fis);
digester.push(this);
digester.parse(is);
} catch (Exception e) {
log.error("Catalina.stop: ", e);
System.exit(1);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore
}
}
}
} else {
// Server object already present. Must be running as a service
try {
s.stop();
} catch (LifecycleException e) {
log.error("Catalina.stop: ", e);
}
return;
}
// Stop the existing server
s = getServer();
if (s.getPort()>0) {
Socket socket = null;
OutputStream stream = null;
try {
socket = new Socket(s.getAddress(), s.getPort());
stream = socket.getOutputStream();
String shutdown = s.getShutdown();
for (int i = 0; i < shutdown.length(); i++) {
stream.write(shutdown.charAt(i));
}
stream.flush();
} catch (ConnectException ce) {
log.error(sm.getString("catalina.stopServer.connectException",
s.getAddress(),
String.valueOf(s.getPort())));
log.error("Catalina.stop: ", ce);
System.exit(1);
} catch (IOException e) {
log.error("Catalina.stop: ", e);
System.exit(1);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
}
} else {
log.error(sm.getString("catalina.stopServer"));
System.exit(1);
}
}
/**
* Start a new server instance.
*/
public void load() {
long t1 = System.nanoTime();
initDirs();
// Before digester - it may be needed
initNaming();
// Create and execute our Digester
Digester digester = createStartDigester();
InputSource inputSource = null;
InputStream inputStream = null;
File file = null;
try {
file = configFile();
inputStream = new FileInputStream(file);
inputSource = new InputSource(file.toURI().toURL().toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail", file), e);
}
}
if (inputStream == null) {
try {
inputStream = getClass().getClassLoader()
.getResourceAsStream(getConfigFile());
inputSource = new InputSource
(getClass().getClassLoader()
.getResource(getConfigFile()).toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail",
getConfigFile()), e);
}
}
}
// This should be included in catalina.jar
// Alternative: don't bother with xml, just create it manually.
if( inputStream==null ) {
try {
inputStream = getClass().getClassLoader()
.getResourceAsStream("server-embed.xml");
inputSource = new InputSource
(getClass().getClassLoader()
.getResource("server-embed.xml").toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail",
"server-embed.xml"), e);
}
}
}
if (inputStream == null || inputSource == null) {
if (file == null) {
log.warn(sm.getString("catalina.configFail",
getConfigFile() + "] or [server-embed.xml]"));
} else {
log.warn(sm.getString("catalina.configFail",
file.getAbsolutePath()));
if (file.exists() && !file.canRead()) {
log.warn("Permissions incorrect, read permission is not allowed on the file.");
}
}
return;
}
try {
inputSource.setByteStream(inputStream);
digester.push(this);
digester.parse(inputSource);
} catch (SAXParseException spe) {
log.warn("Catalina.start using " + getConfigFile() + ": " +
spe.getMessage());
return;
} catch (Exception e) {
log.warn("Catalina.start using " + getConfigFile() + ": " , e);
return;
} finally {
try {
inputStream.close();
} catch (IOException e) {
// Ignore
}
}
getServer().setCatalina(this);
getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile());
getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile());
// Stream redirection
initStreams();
// Start the new server
try {
getServer().init();
} catch (LifecycleException e) {
if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) {
throw new java.lang.Error(e);
} else {
log.error("Catalina.start", e);
}
}
long t2 = System.nanoTime();
if(log.isInfoEnabled()) {
log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms");
}
}
/*
* Load using arguments
*/
public void load(String args[]) {
try {
if (arguments(args)) {
load();
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
/**
* Start a new server instance.
*/
public void start() {
if (getServer() == null) {
load();
}
if (getServer() == null) {
log.fatal("Cannot start server. Server instance is not configured.");
return;
}
long t1 = System.nanoTime();
// Start the new server
try {
getServer().start();
} catch (LifecycleException e) {
log.fatal(sm.getString("catalina.serverStartFail"), e);
try {
getServer().destroy();
} catch (LifecycleException e1) {
log.debug("destroy() failed for failed Server ", e1);
}
return;
}
long t2 = System.nanoTime();
if(log.isInfoEnabled()) {
log.info("Server startup in " + ((t2 - t1) / 1000000) + " ms");
}
// Register shutdown hook
if (useShutdownHook) {
if (shutdownHook == null) {
shutdownHook = new CatalinaShutdownHook();
}
Runtime.getRuntime().addShutdownHook(shutdownHook);
// If JULI is being used, disable JULI's shutdown hook since
// shutdown hooks run in parallel and log messages may be lost
// if JULI's hook completes before the CatalinaShutdownHook()
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).setUseShutdownHook(
false);
}
}
if (await) {
await();
stop();
}
}
/**
* Stop an existing server instance.
*/
public void stop() {
try {
// Remove the ShutdownHook first so that server.stop()
// doesn't get invoked twice
if (useShutdownHook) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
// If JULI is being used, re-enable JULI's shutdown to ensure
// log messages are not lost
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).setUseShutdownHook(
true);
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This will fail on JDK 1.2. Ignoring, as Tomcat can run
// fine without the shutdown hook.
}
// Shut down the server
try {
Server s = getServer();
LifecycleState state = s.getState();
if (LifecycleState.STOPPING_PREP.compareTo(state) <= 0
&& LifecycleState.DESTROYED.compareTo(state) >= 0) {
// Nothing to do. stop() was already called
} else {
s.stop();
s.destroy();
}
} catch (LifecycleException e) {
log.error("Catalina.stop", e);
}
}
/**
* Await and shutdown.
*/
public void await() {
getServer().await();
}
/**
* Print usage information for this application.
*/
protected void usage() {
System.out.println
("usage: java org.apache.catalina.startup.Catalina"
+ " [ -config {pathname} ]"
+ " [ -nonaming ] "
+ " { -help | start | stop }");
}
protected void initDirs() {
String temp = System.getProperty("java.io.tmpdir");
if (temp == null || (!(new File(temp)).exists())
|| (!(new File(temp)).isDirectory())) {
log.error(sm.getString("embedded.notmp", temp));
}
}
protected void initStreams() {
// Replace System.out and System.err with a custom PrintStream
System.setOut(new SystemLogHandler(System.out));
System.setErr(new SystemLogHandler(System.err));
}
protected void initNaming() {
// Setting additional variables
if (!useNaming) {
log.info( "Catalina naming disabled");
System.setProperty("catalina.useNaming", "false");
} else {
System.setProperty("catalina.useNaming", "true");
String value = "org.apache.naming";
String oldValue =
System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
if (oldValue != null) {
value = value + ":" + oldValue;
}
System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
if( log.isDebugEnabled() ) {
log.debug("Setting naming prefix=" + value);
}
value = System.getProperty
(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
if (value == null) {
System.setProperty
(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
} else {
log.debug( "INITIAL_CONTEXT_FACTORY alread set " + value );
}
}
}
/**
* Set the security package access/protection.
*/
protected void setSecurityProtection(){
SecurityConfig securityConfig = SecurityConfig.newInstance();
securityConfig.setPackageDefinition();
securityConfig.setPackageAccess();
}
// --------------------------------------- CatalinaShutdownHook Inner Class
// XXX Should be moved to embedded !
/**
* Shutdown hook which will perform a clean shutdown of Catalina if needed.
*/
protected class CatalinaShutdownHook extends Thread {
@Override
public void run() {
try {
if (getServer() != null) {
Catalina.this.stop();
}
} catch (Throwable ex) {
ExceptionUtils.handleThrowable(ex);
log.error(sm.getString("catalina.shutdownHookFail"), ex);
} finally {
// If JULI is used, shut JULI down *after* the server shuts down
// so log messages aren't lost
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).shutdown();
}
}
}
}
private static final org.apache.juli.logging.Log log=
org.apache.juli.logging.LogFactory.getLog( 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;
@Override
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);
}
}
|
55,664
|
Bug 55664 [websocket] NPE in Util$DecoderMatch during application start
| null |
resolved fixed
|
4e4a24a
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-18T07:40:00Z
| 2013-10-17T22:46:40Z
|
java/org/apache/tomcat/websocket/Util.java
|
/*
* 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.websocket;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.websocket.CloseReason.CloseCode;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.Decoder;
import javax.websocket.Decoder.Binary;
import javax.websocket.Decoder.BinaryStream;
import javax.websocket.Decoder.Text;
import javax.websocket.Decoder.TextStream;
import javax.websocket.DeploymentException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.PongMessage;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBinary;
import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeText;
/**
* Utility class for internal use only within the
* {@link org.apache.tomcat.websocket} package.
*/
public class Util {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static final Queue<SecureRandom> randoms =
new ConcurrentLinkedQueue<>();
private Util() {
// Hide default constructor
}
static boolean isControl(byte opCode) {
return (opCode & 0x08) > 0;
}
static boolean isText(byte opCode) {
return opCode == Constants.OPCODE_TEXT;
}
static CloseCode getCloseCode(int code) {
if (code > 2999 && code < 5000) {
return CloseCodes.NORMAL_CLOSURE;
}
switch (code) {
case 1000:
return CloseCodes.NORMAL_CLOSURE;
case 1001:
return CloseCodes.GOING_AWAY;
case 1002:
return CloseCodes.PROTOCOL_ERROR;
case 1003:
return CloseCodes.CANNOT_ACCEPT;
case 1004:
// Should not be used in a close frame
// return CloseCodes.RESERVED;
return CloseCodes.PROTOCOL_ERROR;
case 1005:
// Should not be used in a close frame
// return CloseCodes.NO_STATUS_CODE;
return CloseCodes.PROTOCOL_ERROR;
case 1006:
// Should not be used in a close frame
// return CloseCodes.CLOSED_ABNORMALLY;
return CloseCodes.PROTOCOL_ERROR;
case 1007:
return CloseCodes.NOT_CONSISTENT;
case 1008:
return CloseCodes.VIOLATED_POLICY;
case 1009:
return CloseCodes.TOO_BIG;
case 1010:
return CloseCodes.NO_EXTENSION;
case 1011:
return CloseCodes.UNEXPECTED_CONDITION;
case 1012:
// Not in RFC6455
// return CloseCodes.SERVICE_RESTART;
return CloseCodes.PROTOCOL_ERROR;
case 1013:
// Not in RFC6455
// return CloseCodes.TRY_AGAIN_LATER;
return CloseCodes.PROTOCOL_ERROR;
case 1015:
// Should not be used in a close frame
// return CloseCodes.TLS_HANDSHAKE_FAILURE;
return CloseCodes.PROTOCOL_ERROR;
default:
return CloseCodes.PROTOCOL_ERROR;
}
}
static byte[] generateMask() {
// SecureRandom is not thread-safe so need to make sure only one thread
// uses it at a time. In theory, the pool could grow to the same size
// as the number of request processing threads. In reality it will be
// a lot smaller.
// Get a SecureRandom from the pool
SecureRandom sr = randoms.poll();
// If one isn't available, generate a new one
if (sr == null) {
try {
sr = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
// Fall back to platform default
sr = new SecureRandom();
}
}
// Generate the mask
byte[] result = new byte[4];
sr.nextBytes(result);
// Put the SecureRandom back in the poll
randoms.add(sr);
return result;
}
static Class<?> getMessageType(MessageHandler listener) {
return (Class<?>) Util.getGenericType(MessageHandler.class,
listener.getClass());
}
public static Class<?> getDecoderType(Class<? extends Decoder> Decoder) {
return (Class<?>) Util.getGenericType(Decoder.class, Decoder);
}
static Class<?> getEncoderType(Class<? extends Encoder> encoder) {
return (Class<?>) Util.getGenericType(Encoder.class, encoder);
}
private static <T> Object getGenericType(Class<T> type,
Class<? extends T> clazz) {
// Look to see if this class implements the generic MessageHandler<>
// interface
// Get all the interfaces
Type[] interfaces = clazz.getGenericInterfaces();
for (Type iface : interfaces) {
// Only need to check interfaces that use generics
if (iface instanceof ParameterizedType) {
ParameterizedType pi = (ParameterizedType) iface;
// Look for the MessageHandler<> interface
if (pi.getRawType() instanceof Class) {
if (type.isAssignableFrom((Class<?>) pi.getRawType())) {
return getTypeParameter(
clazz, pi.getActualTypeArguments()[0]);
}
}
}
}
// Interface not found on this class. Look at the superclass.
@SuppressWarnings("unchecked")
Class<? extends T> superClazz =
(Class<? extends T>) clazz.getSuperclass();
Object result = getGenericType(type, superClazz);
if (result instanceof Class<?>) {
// Superclass implements interface and defines explicit type for
// MessageHandler<>
return result;
} else if (result instanceof Integer) {
// Superclass implements interface and defines unknown type for
// MessageHandler<>
// Map that unknown type to the generic types defined in this class
ParameterizedType superClassType =
(ParameterizedType) clazz.getGenericSuperclass();
return getTypeParameter(clazz,
superClassType.getActualTypeArguments()[
((Integer) result).intValue()]);
} else {
// Error will be logged further up the call stack
return null;
}
}
/*
* For a generic parameter, return either the Class used or if the type
* is unknown, the index for the type in definition of the class
*/
private static Object getTypeParameter(Class<?> clazz, Type argType) {
if (argType instanceof Class<?>) {
return argType;
} else {
TypeVariable<?>[] tvs = clazz.getTypeParameters();
for (int i = 0; i < tvs.length; i++) {
if (tvs[i].equals(argType)) {
return Integer.valueOf(i);
}
}
return null;
}
}
public static boolean isPrimitive(Class<?> clazz) {
if (clazz.isPrimitive()) {
return true;
} else if(clazz.equals(Boolean.class) ||
clazz.equals(Byte.class) ||
clazz.equals(Character.class) ||
clazz.equals(Double.class) ||
clazz.equals(Float.class) ||
clazz.equals(Integer.class) ||
clazz.equals(Long.class) ||
clazz.equals(Short.class)) {
return true;
}
return false;
}
public static Object coerceToType(Class<?> type, String value) {
if (type.equals(String.class)) {
return value;
} else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
return Boolean.valueOf(value);
} else if (type.equals(byte.class) || type.equals(Byte.class)) {
return Byte.valueOf(value);
} else if (value.length() == 1 &&
(type.equals(char.class) || type.equals(Character.class))) {
return Character.valueOf(value.charAt(0));
} else if (type.equals(double.class) || type.equals(Double.class)) {
return Double.valueOf(value);
} else if (type.equals(float.class) || type.equals(Float.class)) {
return Float.valueOf(value);
} else if (type.equals(int.class) || type.equals(Integer.class)) {
return Integer.valueOf(value);
} else if (type.equals(long.class) || type.equals(Long.class)) {
return Long.valueOf(value);
} else if (type.equals(short.class) || type.equals(Short.class)) {
return Short.valueOf(value);
} else {
throw new IllegalArgumentException(sm.getString(
"util.invalidType", value, type.getName()));
}
}
public static List<DecoderEntry> getDecoders(
Class<? extends Decoder>[] decoderClazzes)
throws DeploymentException{
List<DecoderEntry> result = new ArrayList<>();
for (Class<? extends Decoder> decoderClazz : decoderClazzes) {
// Need to instantiate decoder to ensure it is valid and that
// deployment can be failed if it is not
@SuppressWarnings("unused")
Decoder instance;
try {
instance = decoderClazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new DeploymentException(
sm.getString("pojoMethodMapping.invalidDecoder",
decoderClazz.getName()), e);
}
DecoderEntry entry = new DecoderEntry(
Util.getDecoderType(decoderClazz), decoderClazz);
result.add(entry);
}
return result;
}
public static Set<MessageHandlerResult> getMessageHandlers(
MessageHandler listener, EndpointConfig endpointConfig) {
Class<?> target = Util.getMessageType(listener);
// Will never be more than 2 types
Set<MessageHandlerResult> results = new HashSet<>(2);
// Simple cases - handlers already accepts one of the types expected by
// the frame handling code
if (String.class.isAssignableFrom(target)) {
MessageHandlerResult result =
new MessageHandlerResult(listener,
MessageHandlerResultType.TEXT);
results.add(result);
} else if (ByteBuffer.class.isAssignableFrom(target)) {
MessageHandlerResult result =
new MessageHandlerResult(listener,
MessageHandlerResultType.BINARY);
results.add(result);
} else if (PongMessage.class.isAssignableFrom(target)) {
MessageHandlerResult result =
new MessageHandlerResult(listener,
MessageHandlerResultType.PONG);
results.add(result);
// Relatively simple cases - handler needs wrapping but no decoder to
// convert it to one of the types expected by the frame handling code
} else if (byte[].class.isAssignableFrom(target)) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeBinary(listener,
getOnMessageMethod(listener), null,
endpointConfig, null, new Object[1], 0, true, -1,
false, -1),
MessageHandlerResultType.BINARY);
results.add(result);
} else if (InputStream.class.isAssignableFrom(target)) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeBinary(listener,
getOnMessageMethod(listener), null,
endpointConfig, null, new Object[1], 0, true, -1,
true, -1),
MessageHandlerResultType.BINARY);
results.add(result);
} else if (Reader.class.isAssignableFrom(target)) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeText(listener,
getOnMessageMethod(listener), null,
endpointConfig, null, new Object[1], 0, true, -1,
-1),
MessageHandlerResultType.TEXT);
results.add(result);
} else {
// More complex case - listener that requires a decoder
DecoderMatch decoderMatch;
try {
List<Class<? extends Decoder>> decoders =
endpointConfig.getDecoders();
@SuppressWarnings("unchecked")
List<DecoderEntry> decoderEntries = getDecoders(
decoders.toArray(new Class[decoders.size()]));
decoderMatch = new DecoderMatch(target, decoderEntries);
} catch (DeploymentException e) {
throw new IllegalArgumentException(e);
}
Method m = getOnMessageMethod(listener);
if (decoderMatch.getBinaryDecoders().size() > 0) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeBinary(listener, m, null,
endpointConfig,
decoderMatch.getBinaryDecoders(), new Object[1],
0, false, -1, false, -1),
MessageHandlerResultType.BINARY);
results.add(result);
}
if (decoderMatch.getTextDecoders().size() > 0) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeText(listener, m, null,
endpointConfig,
decoderMatch.getTextDecoders(), new Object[1],
0, false, -1, -1),
MessageHandlerResultType.TEXT);
results.add(result);
}
}
if (results.size() == 0) {
throw new IllegalArgumentException(
sm.getString("wsSession.unknownHandler", listener, target));
}
return results;
}
private static Method getOnMessageMethod(MessageHandler listener) {
try {
return listener.getClass().getMethod("onMessage", Object.class);
} catch (NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(
sm.getString("util.invalidMessageHandler"), e);
}
}
public static class DecoderMatch {
private final List<Class<? extends Decoder>> textDecoders =
new ArrayList<>();
private final List<Class<? extends Decoder>> binaryDecoders =
new ArrayList<>();
public DecoderMatch(Class<?> target, List<DecoderEntry> decoderEntries) {
for (DecoderEntry decoderEntry : decoderEntries) {
if (decoderEntry.getClazz().isAssignableFrom(target)) {
if (Binary.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
binaryDecoders.add(decoderEntry.getDecoderClazz());
// willDecode() method means this decoder may or may not
// decode a message so need to carry on checking for
// other matches
} else if (BinaryStream.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
binaryDecoders.add(decoderEntry.getDecoderClazz());
// Stream decoders have to process the message so no
// more decoders can be matched
break;
} else if (Text.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
textDecoders.add(decoderEntry.getDecoderClazz());
// willDecode() method means this decoder may or may not
// decode a message so need to carry on checking for
// other matches
} else if (TextStream.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
textDecoders.add(decoderEntry.getDecoderClazz());
// Stream decoders have to process the message so no
// more decoders can be matched
break;
} else {
throw new IllegalArgumentException(
sm.getString("util.unknownDecoderType"));
}
}
}
}
public List<Class<? extends Decoder>> getTextDecoders() {
return textDecoders;
}
public List<Class<? extends Decoder>> getBinaryDecoders() {
return binaryDecoders;
}
public boolean hasMatches() {
return (textDecoders.size() > 0) || (binaryDecoders.size() > 0);
}
}
}
|
55,664
|
Bug 55664 [websocket] NPE in Util$DecoderMatch during application start
| null |
resolved fixed
|
4e4a24a
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-18T07:40:00Z
| 2013-10-17T22:46:40Z
|
test/org/apache/tomcat/websocket/TestUtil.java
|
/*
* 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.websocket;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import org.junit.Assert;
import org.junit.Test;
public class TestUtil {
// Used to init SecureRandom prior to running tests
public static void generateMask() {
Util.generateMask();
}
@Test
public void testGetMessageTypeSimple() {
Assert.assertEquals(
String.class, Util.getMessageType(new SimpleMessageHandler()));
}
@Test
public void testGetMessageTypeSubclass() {
Assert.assertEquals(String.class,
Util.getMessageType(new SubSimpleMessageHandler()));
}
@Test
public void testGetMessageTypeGenericSubclass() {
Assert.assertEquals(String.class,
Util.getMessageType(new GenericSubMessageHandler()));
}
@Test
public void testGetMessageTypeGenericMultipleSubclass() {
Assert.assertEquals(String.class,
Util.getMessageType(new GenericMultipleSubSubMessageHandler()));
}
@Test
public void testGetMessageTypeGenericMultipleSubclassSwap() {
Assert.assertEquals(String.class,
Util.getMessageType(new GenericMultipleSubSubSwapMessageHandler()));
}
@Test
public void testGetEncoderTypeSimple() {
Assert.assertEquals(
String.class, Util.getEncoderType(SimpleEncoder.class));
}
@Test
public void testGetEncoderTypeSubclass() {
Assert.assertEquals(String.class,
Util.getEncoderType(SubSimpleEncoder.class));
}
@Test
public void testGetEncoderTypeGenericSubclass() {
Assert.assertEquals(String.class,
Util.getEncoderType(GenericSubEncoder.class));
}
@Test
public void testGetEncoderTypeGenericMultipleSubclass() {
Assert.assertEquals(String.class,
Util.getEncoderType(GenericMultipleSubSubEncoder.class));
}
@Test
public void testGetEncoderTypeGenericMultipleSubclassSwap() {
Assert.assertEquals(String.class,
Util.getEncoderType(GenericMultipleSubSubSwapEncoder.class));
}
private static class SimpleMessageHandler
implements MessageHandler.Whole<String> {
@Override
public void onMessage(String message) {
// NO-OP
}
}
private static class SubSimpleMessageHandler extends SimpleMessageHandler {
}
private abstract static class GenericMessageHandler<T>
implements MessageHandler.Whole<T> {
}
private static class GenericSubMessageHandler
extends GenericMessageHandler<String>{
@Override
public void onMessage(String message) {
// NO-OP
}
}
private static interface Foo<T> {
void doSomething(T thing);
}
private abstract static class GenericMultipleMessageHandler<A,B>
implements MessageHandler.Whole<A>, Foo<B> {
}
private abstract static class GenericMultipleSubMessageHandler<X,Y>
extends GenericMultipleMessageHandler<X,Y> {
}
private static class GenericMultipleSubSubMessageHandler
extends GenericMultipleSubMessageHandler<String,Boolean> {
@Override
public void onMessage(String message) {
// NO-OP
}
@Override
public void doSomething(Boolean thing) {
// NO-OP
}
}
private abstract static class GenericMultipleSubSwapMessageHandler<Y,X>
extends GenericMultipleMessageHandler<X,Y> {
}
private static class GenericMultipleSubSubSwapMessageHandler
extends GenericMultipleSubSwapMessageHandler<Boolean,String> {
@Override
public void onMessage(String message) {
// NO-OP
}
@Override
public void doSomething(Boolean thing) {
// NO-OP
}
}
private static class SimpleEncoder implements Encoder.Text<String> {
@Override
public void init(EndpointConfig endpointConfig) {
// NO-OP
}
@Override
public void destroy() {
// NO-OP
}
@Override
public String encode(String object) throws EncodeException {
return null;
}
}
private static class SubSimpleEncoder extends SimpleEncoder {
}
private abstract static class GenericEncoder<T> implements Encoder.Text<T> {
@Override
public void init(EndpointConfig endpointConfig) {
// NO-OP
}
@Override
public void destroy() {
// NO-OP
}
}
private static class GenericSubEncoder
extends GenericEncoder<String>{
@Override
public String encode(String object) throws EncodeException {
return null;
}
}
private abstract static class GenericMultipleEncoder<A,B>
implements Encoder.Text<A>, Foo<B> {
@Override
public void init(EndpointConfig endpointConfig) {
// NO-OP
}
@Override
public void destroy() {
// NO-OP
}
}
private abstract static class GenericMultipleSubEncoder<X,Y>
extends GenericMultipleEncoder<X,Y> {
}
private static class GenericMultipleSubSubEncoder
extends GenericMultipleSubEncoder<String,Boolean> {
@Override
public String encode(String object) throws EncodeException {
return null;
}
@Override
public void doSomething(Boolean thing) {
// NO-OP
}
}
private abstract static class GenericMultipleSubSwapEncoder<Y,X>
extends GenericMultipleEncoder<X,Y> {
}
private static class GenericMultipleSubSubSwapEncoder
extends GenericMultipleSubSwapEncoder<Boolean,String> {
@Override
public String encode(String object) throws EncodeException {
return null;
}
@Override
public void doSomething(Boolean thing) {
// NO-OP
}
}
}
|
55,664
|
Bug 55664 [websocket] NPE in Util$DecoderMatch during application start
| null |
resolved fixed
|
4e4a24a
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-18T07:40:00Z
| 2013-10-17T22:46:40Z
|
test/org/apache/tomcat/websocket/pojo/TestEncodingDecoding.java
|
/*
* 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.websocket.pojo;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.servlet.ServletContextEvent;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.DeploymentException;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Extension;
import javax.websocket.MessageHandler;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.descriptor.web.ApplicationListener;
import org.apache.tomcat.websocket.pojo.TesterUtil.ServerConfigListener;
import org.apache.tomcat.websocket.pojo.TesterUtil.SingletonConfigurator;
import org.apache.tomcat.websocket.server.WsContextListener;
public class TestEncodingDecoding extends TomcatBaseTest {
private static final String MESSAGE_ONE = "message-one";
private static final String PATH_PROGRAMMATIC_EP = "/echoProgrammaticEP";
private static final String PATH_ANNOTATED_EP = "/echoAnnotatedEP";
@Test
public void testProgrammaticEndPoints() throws Exception{
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
ctx.addApplicationListener(new ApplicationListener(
ProgramaticServerEndpointConfig.class.getName(), false));
Tomcat.addServlet(ctx, "default", new DefaultServlet());
ctx.addServletMapping("/", "default");
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
tomcat.start();
Client client = new Client();
URI uri = new URI("ws://localhost:" + getPort() + PATH_PROGRAMMATIC_EP);
Session session = wsContainer.connectToServer(client, uri);
MsgString msg1 = new MsgString();
msg1.setData(MESSAGE_ONE);
session.getBasicRemote().sendObject(msg1);
// Should not take very long
int i = 0;
while (i < 20) {
if (MsgStringMessageHandler.received.size() > 0 &&
client.received.size() > 0) {
break;
}
Thread.sleep(100);
i++;
}
// Check messages were received
Assert.assertEquals(1, MsgStringMessageHandler.received.size());
Assert.assertEquals(1, client.received.size());
// Check correct messages were received
Assert.assertEquals(MESSAGE_ONE,
((MsgString) MsgStringMessageHandler.received.peek()).getData());
Assert.assertEquals(MESSAGE_ONE,
new String(((MsgByte) client.received.peek()).getData()));
session.close();
}
@Test
public void testAnnotatedEndPoints() throws Exception {
// Set up utility classes
Server server = new Server();
SingletonConfigurator.setInstance(server);
ServerConfigListener.setPojoClazz(Server.class);
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
Context ctx =
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
ctx.addApplicationListener(new ApplicationListener(
ServerConfigListener.class.getName(), false));
Tomcat.addServlet(ctx, "default", new DefaultServlet());
ctx.addServletMapping("/", "default");
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
tomcat.start();
Client client = new Client();
URI uri = new URI("ws://localhost:" + getPort() + PATH_ANNOTATED_EP);
Session session = wsContainer.connectToServer(client, uri);
MsgString msg1 = new MsgString();
msg1.setData(MESSAGE_ONE);
session.getBasicRemote().sendObject(msg1);
// Should not take very long
int i = 0;
while (i < 20) {
if (server.received.size() > 0 && client.received.size() > 0) {
break;
}
Thread.sleep(100);
}
// Check messages were received
Assert.assertEquals(1, server.received.size());
Assert.assertEquals(1, client.received.size());
// Check correct messages were received
Assert.assertEquals(MESSAGE_ONE,
((MsgString) server.received.peek()).getData());
Assert.assertEquals(MESSAGE_ONE,
((MsgString) client.received.peek()).getData());
session.close();
// Should not take very long but some failures have been seen
i = testEvent(MsgStringEncoder.class.getName()+":init", 0);
i = testEvent(MsgStringDecoder.class.getName()+":init", i);
i = testEvent(MsgByteEncoder.class.getName()+":init", i);
i = testEvent(MsgByteDecoder.class.getName()+":init", i);
i = testEvent(MsgStringEncoder.class.getName()+":destroy", i);
i = testEvent(MsgStringDecoder.class.getName()+":destroy", i);
i = testEvent(MsgByteEncoder.class.getName()+":destroy", i);
i = testEvent(MsgByteDecoder.class.getName()+":destroy", i);
}
private int testEvent(String name, int count) throws InterruptedException {
int i = count;
while (i < 50) {
if (Server.isLifeCycleEventCalled(name)) {
break;
}
i++;
Thread.sleep(100);
}
Assert.assertTrue(Server.isLifeCycleEventCalled(name));
return i;
}
@ClientEndpoint(decoders={MsgStringDecoder.class, MsgByteDecoder.class},
encoders={MsgStringEncoder.class, MsgByteEncoder.class})
public static class Client {
private Queue<Object> received = new ConcurrentLinkedQueue<>();
@OnMessage
public void rx(MsgString in) {
received.add(in);
}
@OnMessage
public void rx(MsgByte in) {
received.add(in);
}
}
@ServerEndpoint(value=PATH_ANNOTATED_EP,
decoders={MsgStringDecoder.class, MsgByteDecoder.class},
encoders={MsgStringEncoder.class, MsgByteEncoder.class},
configurator=SingletonConfigurator.class)
public static class Server {
private Queue<Object> received = new ConcurrentLinkedQueue<>();
static HashMap<String, Boolean> lifeCyclesCalled = new HashMap<>(8);
@OnMessage
public MsgString rx(MsgString in) {
received.add(in);
// Echo the message back
return in;
}
@OnMessage
public MsgByte rx(MsgByte in) {
received.add(in);
// Echo the message back
return in;
}
public static void addLifeCycleEvent(String event){
lifeCyclesCalled.put(event, Boolean.TRUE);
}
public static boolean isLifeCycleEventCalled(String event){
Boolean called = lifeCyclesCalled.get(event);
return called == null ? false : called.booleanValue();
}
}
public static class MsgByteMessageHandler implements
MessageHandler.Whole<MsgByte> {
public static Queue<Object> received = new ConcurrentLinkedQueue<>();
private final Session session;
public MsgByteMessageHandler(Session session) {
this.session = session;
}
@Override
public void onMessage(MsgByte in) {
System.out.println(getClass() + " received");
received.add(in);
try {
MsgByte msg = new MsgByte();
msg.setData("got it".getBytes());
session.getBasicRemote().sendObject(msg);
} catch (IOException | EncodeException e) {
throw new IllegalStateException(e);
}
}
}
public static class MsgStringMessageHandler
implements MessageHandler.Whole<MsgString>{
public static Queue<Object> received = new ConcurrentLinkedQueue<>();
private final Session session;
public MsgStringMessageHandler(Session session) {
this.session = session;
}
@Override
public void onMessage(MsgString in) {
received.add(in);
try {
MsgByte msg = new MsgByte();
msg.setData(MESSAGE_ONE.getBytes());
session.getBasicRemote().sendObject(msg);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
}
public static class ProgrammaticEndpoint extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {
session.addMessageHandler(new MsgStringMessageHandler(session));
}
}
public static class MsgString {
private String data;
public String getData() { return data; }
public void setData(String data) { this.data = data; }
}
public static class MsgStringEncoder implements Encoder.Text<MsgString> {
@Override
public void init(EndpointConfig endpointConfig) {
Server.addLifeCycleEvent(getClass().getName() + ":init");
}
@Override
public void destroy() {
Server.addLifeCycleEvent(getClass().getName() + ":destroy");
}
@Override
public String encode(MsgString msg) throws EncodeException {
return "MsgString:" + msg.getData();
}
}
public static class MsgStringDecoder implements Decoder.Text<MsgString> {
@Override
public void init(EndpointConfig endpointConfig) {
Server.addLifeCycleEvent(getClass().getName() + ":init");
}
@Override
public void destroy() {
Server.addLifeCycleEvent(getClass().getName() + ":destroy");
}
@Override
public MsgString decode(String s) throws DecodeException {
MsgString result = new MsgString();
result.setData(s.substring(10));
return result;
}
@Override
public boolean willDecode(String s) {
return s.startsWith("MsgString:");
}
}
public static class MsgByte {
private byte[] data;
public byte[] getData() { return data; }
public void setData(byte[] data) { this.data = data; }
}
public static class MsgByteEncoder implements Encoder.Binary<MsgByte> {
@Override
public void init(EndpointConfig endpointConfig) {
Server.addLifeCycleEvent(getClass().getName() + ":init");
}
@Override
public void destroy() {
Server.addLifeCycleEvent(getClass().getName() + ":destroy");
}
@Override
public ByteBuffer encode(MsgByte msg) throws EncodeException {
byte[] data = msg.getData();
ByteBuffer reply = ByteBuffer.allocate(2 + data.length);
reply.put((byte) 0x12);
reply.put((byte) 0x34);
reply.put(data);
reply.flip();
return reply;
}
}
public static class MsgByteDecoder implements Decoder.Binary<MsgByte> {
@Override
public void init(EndpointConfig endpointConfig) {
Server.addLifeCycleEvent(getClass().getName() + ":init");
}
@Override
public void destroy() {
Server.addLifeCycleEvent(getClass().getName() + ":destroy");
}
@Override
public MsgByte decode(ByteBuffer bb) throws DecodeException {
MsgByte result = new MsgByte();
byte[] data = new byte[bb.limit() - bb.position()];
bb.get(data);
result.setData(data);
return result;
}
@Override
public boolean willDecode(ByteBuffer bb) {
bb.mark();
if (bb.get() == 0x12 && bb.get() == 0x34) {
return true;
}
bb.reset();
return false;
}
}
public static class ProgramaticServerEndpointConfig extends WsContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
super.contextInitialized(sce);
ServerContainer sc =
(ServerContainer) sce.getServletContext().getAttribute(
org.apache.tomcat.websocket.server.Constants.
SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
try {
sc.addEndpoint(new ServerEndpointConfig() {
@Override
public Map<String, Object> getUserProperties() {
return Collections.emptyMap();
}
@Override
public List<Class<? extends Encoder>> getEncoders() {
List<Class<? extends Encoder>> encoders = new ArrayList<>(2);
encoders.add(MsgStringEncoder.class);
encoders.add(MsgByteEncoder.class);
return encoders;
}
@Override
public List<Class<? extends Decoder>> getDecoders() {
List<Class<? extends Decoder>> decoders = new ArrayList<>(2);
decoders.add(MsgStringDecoder.class);
decoders.add(MsgByteDecoder.class);
return decoders;
}
@Override
public List<String> getSubprotocols() {
return Collections.emptyList();
}
@Override
public String getPath() {
return PATH_PROGRAMMATIC_EP;
}
@Override
public List<Extension> getExtensions() {
return Collections.emptyList();
}
@Override
public Class<?> getEndpointClass() {
return ProgrammaticEndpoint.class;
}
@Override
public Configurator getConfigurator() {
return new ServerEndpointConfig.Configurator() {
};
}
});
} catch (DeploymentException e) {
throw new IllegalStateException(e);
}
}
}
}
|
55,681
|
Bug 55681 JSR-356 message handling: NULL pointer being thrown when DecodeException is caught in PojoMessageHandlerWholeBase<T>.onMessage
|
I am testing what happens when Encode/Decode Exceptions occur during JSR-356 communication. In our case, we do NOT use annotation, but we "extend Endpoint" and "implement Whole<ThingworxMessage>". I was forcing a DecodeException to occur - expecting to my onError to be called with the actual DecodeException. Instead, I got a Null. Stepping the following code in Tomcat: in onMessage, the ((WsSession)session) is NULL. As a result, the actual DecodeException (cause) is lost. // Can this message be decoded? Object payload; try { payload = decode(message); } catch (DecodeException de) { ((WsSession) session).getLocal().onError(session, de); return; } Tracing this further up the stack, I found that Util.getMessageHandlers is initializing it and passing NULL in for the session: if (decoderMatch.getTextDecoders().size() > 0) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeText(listener, m, null, endpointConfig, decoderMatch.getTextDecoders(), new Object[1], 0, false, -1, -1), MessageHandlerResultType.TEXT); results.add(result); } Please let me know if I can provide any more details. -bob
|
resolved fixed
|
514cefb
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-20T21:03:52Z
| 2013-10-20T23:00:00Z
|
java/org/apache/tomcat/websocket/Util.java
|
/*
* 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.websocket;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.websocket.CloseReason.CloseCode;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.Decoder;
import javax.websocket.Decoder.Binary;
import javax.websocket.Decoder.BinaryStream;
import javax.websocket.Decoder.Text;
import javax.websocket.Decoder.TextStream;
import javax.websocket.DeploymentException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.PongMessage;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBinary;
import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeText;
/**
* Utility class for internal use only within the
* {@link org.apache.tomcat.websocket} package.
*/
public class Util {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static final Queue<SecureRandom> randoms =
new ConcurrentLinkedQueue<>();
private Util() {
// Hide default constructor
}
static boolean isControl(byte opCode) {
return (opCode & 0x08) > 0;
}
static boolean isText(byte opCode) {
return opCode == Constants.OPCODE_TEXT;
}
static CloseCode getCloseCode(int code) {
if (code > 2999 && code < 5000) {
return CloseCodes.NORMAL_CLOSURE;
}
switch (code) {
case 1000:
return CloseCodes.NORMAL_CLOSURE;
case 1001:
return CloseCodes.GOING_AWAY;
case 1002:
return CloseCodes.PROTOCOL_ERROR;
case 1003:
return CloseCodes.CANNOT_ACCEPT;
case 1004:
// Should not be used in a close frame
// return CloseCodes.RESERVED;
return CloseCodes.PROTOCOL_ERROR;
case 1005:
// Should not be used in a close frame
// return CloseCodes.NO_STATUS_CODE;
return CloseCodes.PROTOCOL_ERROR;
case 1006:
// Should not be used in a close frame
// return CloseCodes.CLOSED_ABNORMALLY;
return CloseCodes.PROTOCOL_ERROR;
case 1007:
return CloseCodes.NOT_CONSISTENT;
case 1008:
return CloseCodes.VIOLATED_POLICY;
case 1009:
return CloseCodes.TOO_BIG;
case 1010:
return CloseCodes.NO_EXTENSION;
case 1011:
return CloseCodes.UNEXPECTED_CONDITION;
case 1012:
// Not in RFC6455
// return CloseCodes.SERVICE_RESTART;
return CloseCodes.PROTOCOL_ERROR;
case 1013:
// Not in RFC6455
// return CloseCodes.TRY_AGAIN_LATER;
return CloseCodes.PROTOCOL_ERROR;
case 1015:
// Should not be used in a close frame
// return CloseCodes.TLS_HANDSHAKE_FAILURE;
return CloseCodes.PROTOCOL_ERROR;
default:
return CloseCodes.PROTOCOL_ERROR;
}
}
static byte[] generateMask() {
// SecureRandom is not thread-safe so need to make sure only one thread
// uses it at a time. In theory, the pool could grow to the same size
// as the number of request processing threads. In reality it will be
// a lot smaller.
// Get a SecureRandom from the pool
SecureRandom sr = randoms.poll();
// If one isn't available, generate a new one
if (sr == null) {
try {
sr = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
// Fall back to platform default
sr = new SecureRandom();
}
}
// Generate the mask
byte[] result = new byte[4];
sr.nextBytes(result);
// Put the SecureRandom back in the poll
randoms.add(sr);
return result;
}
static Class<?> getMessageType(MessageHandler listener) {
return Util.getGenericType(MessageHandler.class,
listener.getClass()).getClazz();
}
public static Class<?> getDecoderType(Class<? extends Decoder> decoder) {
return Util.getGenericType(Decoder.class, decoder).getClazz();
}
static Class<?> getEncoderType(Class<? extends Encoder> encoder) {
return Util.getGenericType(Encoder.class, encoder).getClazz();
}
private static <T> TypeResult getGenericType(Class<T> type,
Class<? extends T> clazz) {
// Look to see if this class implements the interface of interest
// Get all the interfaces
Type[] interfaces = clazz.getGenericInterfaces();
for (Type iface : interfaces) {
// Only need to check interfaces that use generics
if (iface instanceof ParameterizedType) {
ParameterizedType pi = (ParameterizedType) iface;
// Look for the interface of interest
if (pi.getRawType() instanceof Class) {
if (type.isAssignableFrom((Class<?>) pi.getRawType())) {
return getTypeParameter(
clazz, pi.getActualTypeArguments()[0]);
}
}
}
}
// Interface not found on this class. Look at the superclass.
@SuppressWarnings("unchecked")
Class<? extends T> superClazz =
(Class<? extends T>) clazz.getSuperclass();
TypeResult superClassTypeResult = getGenericType(type, superClazz);
int dimension = superClassTypeResult.getDimension();
if (superClassTypeResult.getIndex() == -1 && dimension == 0) {
// Superclass implements interface and defines explicit type for
// the interface of interest
return superClassTypeResult;
}
if (superClassTypeResult.getIndex() > -1) {
// Superclass implements interface and defines unknown type for
// the interface of interest
// Map that unknown type to the generic types defined in this class
ParameterizedType superClassType =
(ParameterizedType) clazz.getGenericSuperclass();
TypeResult result = getTypeParameter(clazz,
superClassType.getActualTypeArguments()[
superClassTypeResult.getIndex()]);
result.incrementDimension(superClassTypeResult.getDimension());
if (result.getClazz() != null && result.getDimension() > 0) {
superClassTypeResult = result;
} else {
return result;
}
}
if (superClassTypeResult.getDimension() > 0) {
StringBuilder className = new StringBuilder();
for (int i = 0; i < dimension; i++) {
className.append('[');
}
className.append('L');
className.append(superClassTypeResult.getClazz().getCanonicalName());
className.append(';');
Class<?> arrayClazz;
try {
arrayClazz = Class.forName(className.toString());
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
return new TypeResult(arrayClazz, -1, 0);
}
// Error will be logged further up the call stack
return null;
}
/*
* For a generic parameter, return either the Class used or if the type
* is unknown, the index for the type in definition of the class
*/
private static TypeResult getTypeParameter(Class<?> clazz, Type argType) {
if (argType instanceof Class<?>) {
return new TypeResult((Class<?>) argType, -1, 0);
} else if (argType instanceof ParameterizedType) {
return new TypeResult((Class<?>)((ParameterizedType) argType).getRawType(), -1, 0);
} else if (argType instanceof GenericArrayType) {
Type arrayElementType = ((GenericArrayType) argType).getGenericComponentType();
TypeResult result = getTypeParameter(clazz, arrayElementType);
result.incrementDimension(1);
return result;
} else {
TypeVariable<?>[] tvs = clazz.getTypeParameters();
for (int i = 0; i < tvs.length; i++) {
if (tvs[i].equals(argType)) {
return new TypeResult(null, i, 0);
}
}
return null;
}
}
public static boolean isPrimitive(Class<?> clazz) {
if (clazz.isPrimitive()) {
return true;
} else if(clazz.equals(Boolean.class) ||
clazz.equals(Byte.class) ||
clazz.equals(Character.class) ||
clazz.equals(Double.class) ||
clazz.equals(Float.class) ||
clazz.equals(Integer.class) ||
clazz.equals(Long.class) ||
clazz.equals(Short.class)) {
return true;
}
return false;
}
public static Object coerceToType(Class<?> type, String value) {
if (type.equals(String.class)) {
return value;
} else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
return Boolean.valueOf(value);
} else if (type.equals(byte.class) || type.equals(Byte.class)) {
return Byte.valueOf(value);
} else if (value.length() == 1 &&
(type.equals(char.class) || type.equals(Character.class))) {
return Character.valueOf(value.charAt(0));
} else if (type.equals(double.class) || type.equals(Double.class)) {
return Double.valueOf(value);
} else if (type.equals(float.class) || type.equals(Float.class)) {
return Float.valueOf(value);
} else if (type.equals(int.class) || type.equals(Integer.class)) {
return Integer.valueOf(value);
} else if (type.equals(long.class) || type.equals(Long.class)) {
return Long.valueOf(value);
} else if (type.equals(short.class) || type.equals(Short.class)) {
return Short.valueOf(value);
} else {
throw new IllegalArgumentException(sm.getString(
"util.invalidType", value, type.getName()));
}
}
public static List<DecoderEntry> getDecoders(
Class<? extends Decoder>[] decoderClazzes)
throws DeploymentException{
List<DecoderEntry> result = new ArrayList<>();
for (Class<? extends Decoder> decoderClazz : decoderClazzes) {
// Need to instantiate decoder to ensure it is valid and that
// deployment can be failed if it is not
@SuppressWarnings("unused")
Decoder instance;
try {
instance = decoderClazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new DeploymentException(
sm.getString("pojoMethodMapping.invalidDecoder",
decoderClazz.getName()), e);
}
DecoderEntry entry = new DecoderEntry(
Util.getDecoderType(decoderClazz), decoderClazz);
result.add(entry);
}
return result;
}
public static Set<MessageHandlerResult> getMessageHandlers(
MessageHandler listener, EndpointConfig endpointConfig) {
Class<?> target = Util.getMessageType(listener);
// Will never be more than 2 types
Set<MessageHandlerResult> results = new HashSet<>(2);
// Simple cases - handlers already accepts one of the types expected by
// the frame handling code
if (String.class.isAssignableFrom(target)) {
MessageHandlerResult result =
new MessageHandlerResult(listener,
MessageHandlerResultType.TEXT);
results.add(result);
} else if (ByteBuffer.class.isAssignableFrom(target)) {
MessageHandlerResult result =
new MessageHandlerResult(listener,
MessageHandlerResultType.BINARY);
results.add(result);
} else if (PongMessage.class.isAssignableFrom(target)) {
MessageHandlerResult result =
new MessageHandlerResult(listener,
MessageHandlerResultType.PONG);
results.add(result);
// Relatively simple cases - handler needs wrapping but no decoder to
// convert it to one of the types expected by the frame handling code
} else if (byte[].class.isAssignableFrom(target)) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeBinary(listener,
getOnMessageMethod(listener), null,
endpointConfig, null, new Object[1], 0, true, -1,
false, -1),
MessageHandlerResultType.BINARY);
results.add(result);
} else if (InputStream.class.isAssignableFrom(target)) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeBinary(listener,
getOnMessageMethod(listener), null,
endpointConfig, null, new Object[1], 0, true, -1,
true, -1),
MessageHandlerResultType.BINARY);
results.add(result);
} else if (Reader.class.isAssignableFrom(target)) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeText(listener,
getOnMessageMethod(listener), null,
endpointConfig, null, new Object[1], 0, true, -1,
-1),
MessageHandlerResultType.TEXT);
results.add(result);
} else {
// More complex case - listener that requires a decoder
DecoderMatch decoderMatch;
try {
List<Class<? extends Decoder>> decoders =
endpointConfig.getDecoders();
@SuppressWarnings("unchecked")
List<DecoderEntry> decoderEntries = getDecoders(
decoders.toArray(new Class[decoders.size()]));
decoderMatch = new DecoderMatch(target, decoderEntries);
} catch (DeploymentException e) {
throw new IllegalArgumentException(e);
}
Method m = getOnMessageMethod(listener);
if (decoderMatch.getBinaryDecoders().size() > 0) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeBinary(listener, m, null,
endpointConfig,
decoderMatch.getBinaryDecoders(), new Object[1],
0, false, -1, false, -1),
MessageHandlerResultType.BINARY);
results.add(result);
}
if (decoderMatch.getTextDecoders().size() > 0) {
MessageHandlerResult result = new MessageHandlerResult(
new PojoMessageHandlerWholeText(listener, m, null,
endpointConfig,
decoderMatch.getTextDecoders(), new Object[1],
0, false, -1, -1),
MessageHandlerResultType.TEXT);
results.add(result);
}
}
if (results.size() == 0) {
throw new IllegalArgumentException(
sm.getString("wsSession.unknownHandler", listener, target));
}
return results;
}
private static Method getOnMessageMethod(MessageHandler listener) {
try {
return listener.getClass().getMethod("onMessage", Object.class);
} catch (NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(
sm.getString("util.invalidMessageHandler"), e);
}
}
public static class DecoderMatch {
private final List<Class<? extends Decoder>> textDecoders =
new ArrayList<>();
private final List<Class<? extends Decoder>> binaryDecoders =
new ArrayList<>();
public DecoderMatch(Class<?> target, List<DecoderEntry> decoderEntries) {
for (DecoderEntry decoderEntry : decoderEntries) {
if (decoderEntry.getClazz().isAssignableFrom(target)) {
if (Binary.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
binaryDecoders.add(decoderEntry.getDecoderClazz());
// willDecode() method means this decoder may or may not
// decode a message so need to carry on checking for
// other matches
} else if (BinaryStream.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
binaryDecoders.add(decoderEntry.getDecoderClazz());
// Stream decoders have to process the message so no
// more decoders can be matched
break;
} else if (Text.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
textDecoders.add(decoderEntry.getDecoderClazz());
// willDecode() method means this decoder may or may not
// decode a message so need to carry on checking for
// other matches
} else if (TextStream.class.isAssignableFrom(
decoderEntry.getDecoderClazz())) {
textDecoders.add(decoderEntry.getDecoderClazz());
// Stream decoders have to process the message so no
// more decoders can be matched
break;
} else {
throw new IllegalArgumentException(
sm.getString("util.unknownDecoderType"));
}
}
}
}
public List<Class<? extends Decoder>> getTextDecoders() {
return textDecoders;
}
public List<Class<? extends Decoder>> getBinaryDecoders() {
return binaryDecoders;
}
public boolean hasMatches() {
return (textDecoders.size() > 0) || (binaryDecoders.size() > 0);
}
}
private static class TypeResult {
private final Class<?> clazz;
private final int index;
private int dimension;
public TypeResult(Class<?> clazz, int index, int dimension) {
this.clazz= clazz;
this.index = index;
this.dimension = dimension;
}
public Class<?> getClazz() {
return clazz;
}
public int getIndex() {
return index;
}
public int getDimension() {
return dimension;
}
public void incrementDimension(int inc) {
dimension += inc;
}
}
}
|
55,681
|
Bug 55681 JSR-356 message handling: NULL pointer being thrown when DecodeException is caught in PojoMessageHandlerWholeBase<T>.onMessage
|
I am testing what happens when Encode/Decode Exceptions occur during JSR-356 communication. In our case, we do NOT use annotation, but we "extend Endpoint" and "implement Whole<ThingworxMessage>". I was forcing a DecodeException to occur - expecting to my onError to be called with the actual DecodeException. Instead, I got a Null. Stepping the following code in Tomcat: in onMessage, the ((WsSession)session) is NULL. As a result, the actual DecodeException (cause) is lost. // Can this message be decoded? Object payload; try { payload = decode(message); } catch (DecodeException de) { ((WsSession) session).getLocal().onError(session, de); return; } Tracing this further up the stack, I found that Util.getMessageHandlers is initializing it and passing NULL in for the session: if (decoderMatch.getTextDecoders().size() > 0) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeText(listener, m, null, endpointConfig, decoderMatch.getTextDecoders(), new Object[1], 0, false, -1, -1), MessageHandlerResultType.TEXT); results.add(result); } Please let me know if I can provide any more details. -bob
|
resolved fixed
|
514cefb
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-20T21:03:52Z
| 2013-10-20T23:00:00Z
|
java/org/apache/tomcat/websocket/WsSession.java
|
/*
* 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.websocket;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCode;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Extension;
import javax.websocket.MessageHandler;
import javax.websocket.PongMessage;
import javax.websocket.RemoteEndpoint;
import javax.websocket.SendResult;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
public class WsSession implements Session {
// An ellipsis is a single character that looks like three periods in a row
// and is used to indicate a continuation.
private static final byte[] ELLIPSIS_BYTES =
"\u2026".getBytes(StandardCharsets.UTF_8);
// An ellipsis is three bytes in UTF-8
private static final int ELLIPSIS_BYTES_LEN = ELLIPSIS_BYTES.length;
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static AtomicLong ids = new AtomicLong(0);
private final Log log = LogFactory.getLog(WsSession.class);
private final Endpoint localEndpoint;
private final WsRemoteEndpointImplBase wsRemoteEndpoint;
private final RemoteEndpoint.Async remoteEndpointAsync;
private final RemoteEndpoint.Basic remoteEndpointBasic;
private final ClassLoader applicationClassLoader;
private final WsWebSocketContainer webSocketContainer;
private final URI requestUri;
private final Map<String,List<String>> requestParameterMap;
private final String queryString;
private final Principal userPrincipal;
private final EndpointConfig endpointConfig;
private final String subProtocol;
private final Map<String,String> pathParameters;
private final boolean secure;
private final String httpSessionId;
private final String id;
// Expected to handle message types of <String> only
private MessageHandler textMessageHandler = null;
// Expected to handle message types of <ByteBuffer> only
private MessageHandler binaryMessageHandler = null;
private MessageHandler.Whole<PongMessage> pongMessageHandler = null;
private volatile State state = State.OPEN;
private final Object stateLock = new Object();
private final Map<String,Object> userProperties = new ConcurrentHashMap<>();
private volatile int maxBinaryMessageBufferSize =
Constants.DEFAULT_BUFFER_SIZE;
private volatile int maxTextMessageBufferSize =
Constants.DEFAULT_BUFFER_SIZE;
private volatile long maxIdleTimeout = 0;
private volatile long lastActive = System.currentTimeMillis();
private Map<FutureToSendHandler,FutureToSendHandler> futures = new ConcurrentHashMap<>();
/**
* Creates a new WebSocket session for communication between the two
* provided end points. The result of {@link Thread#getContextClassLoader()}
* at the time this constructor is called will be used when calling
* {@link Endpoint#onClose(Session, CloseReason)}.
*
* @param localEndpoint
* @param wsRemoteEndpoint
* @throws DeploymentException
*/
public WsSession(Endpoint localEndpoint,
WsRemoteEndpointImplBase wsRemoteEndpoint,
WsWebSocketContainer wsWebSocketContainer,
URI requestUri, Map<String,List<String>> requestParameterMap,
String queryString, Principal userPrincipal, String httpSessionId,
String subProtocol, Map<String,String> pathParameters,
boolean secure, EndpointConfig endpointConfig)
throws DeploymentException {
this.localEndpoint = localEndpoint;
this.wsRemoteEndpoint = wsRemoteEndpoint;
this.wsRemoteEndpoint.setSession(this);
this.remoteEndpointAsync = new WsRemoteEndpointAsync(wsRemoteEndpoint);
this.remoteEndpointBasic = new WsRemoteEndpointBasic(wsRemoteEndpoint);
this.webSocketContainer = wsWebSocketContainer;
applicationClassLoader = Thread.currentThread().getContextClassLoader();
wsRemoteEndpoint.setSendTimeout(
wsWebSocketContainer.getDefaultAsyncSendTimeout());
this.maxBinaryMessageBufferSize =
webSocketContainer.getDefaultMaxBinaryMessageBufferSize();
this.maxTextMessageBufferSize =
webSocketContainer.getDefaultMaxTextMessageBufferSize();
this.maxIdleTimeout =
webSocketContainer.getDefaultMaxSessionIdleTimeout();
this.requestUri = requestUri;
if (requestParameterMap == null) {
this.requestParameterMap = Collections.emptyMap();
} else {
this.requestParameterMap = requestParameterMap;
}
this.queryString = queryString;
this.userPrincipal = userPrincipal;
this.httpSessionId = httpSessionId;
if (subProtocol == null) {
this.subProtocol = "";
} else {
this.subProtocol = subProtocol;
}
this.pathParameters = pathParameters;
this.secure = secure;
this.wsRemoteEndpoint.setEncoders(endpointConfig);
this.endpointConfig = endpointConfig;
this.userProperties.putAll(endpointConfig.getUserProperties());
this.id = Long.toHexString(ids.getAndIncrement());
}
@Override
public WebSocketContainer getContainer() {
checkState();
return webSocketContainer;
}
@SuppressWarnings("unchecked")
@Override
public void addMessageHandler(MessageHandler listener) {
checkState();
// Message handlers that require decoders may map to text messages,
// binary messages, both or neither.
// The frame processing code expects binary message handlers to
// accept ByteBuffer
// Use the POJO message handler wrappers as they are designed to wrap
// arbitrary objects with MessageHandlers and can wrap MessageHandlers
// just as easily.
Set<MessageHandlerResult> mhResults =
Util.getMessageHandlers(listener, endpointConfig);
for (MessageHandlerResult mhResult : mhResults) {
switch (mhResult.getType()) {
case TEXT: {
if (textMessageHandler != null) {
throw new IllegalStateException(
sm.getString("wsSession.duplicateHandlerText"));
}
textMessageHandler = mhResult.getHandler();
break;
}
case BINARY: {
if (binaryMessageHandler != null) {
throw new IllegalStateException(
sm.getString("wsSession.duplicateHandlerBinary"));
}
binaryMessageHandler = mhResult.getHandler();
break;
}
case PONG: {
if (pongMessageHandler != null) {
throw new IllegalStateException(
sm.getString("wsSession.duplicateHandlerPong"));
}
MessageHandler handler = mhResult.getHandler();
if (handler instanceof MessageHandler.Whole<?>) {
pongMessageHandler =
(MessageHandler.Whole<PongMessage>) handler;
} else {
throw new IllegalStateException(
sm.getString("wsSession.invalidHandlerTypePong"));
}
break;
}
default: {
throw new IllegalArgumentException(sm.getString(
"wsSession.unknownHandlerType", listener,
mhResult.getType()));
}
}
}
}
@Override
public Set<MessageHandler> getMessageHandlers() {
checkState();
Set<MessageHandler> result = new HashSet<>();
if (binaryMessageHandler != null) {
result.add(binaryMessageHandler);
}
if (textMessageHandler != null) {
result.add(textMessageHandler);
}
if (pongMessageHandler != null) {
result.add(pongMessageHandler);
}
return result;
}
@Override
public void removeMessageHandler(MessageHandler listener) {
checkState();
if (listener == null) {
return;
}
MessageHandler wrapped = null;
if (listener instanceof WrappedMessageHandler) {
wrapped = ((WrappedMessageHandler) listener).getWrappedHandler();
}
if (wrapped == null) {
wrapped = listener;
}
boolean removed = false;
if (wrapped.equals(textMessageHandler) ||
listener.equals(textMessageHandler)) {
textMessageHandler = null;
removed = true;
}
if (listener.equals(binaryMessageHandler) ||
listener.equals(binaryMessageHandler)) {
binaryMessageHandler = null;
removed = true;
}
if (listener.equals(pongMessageHandler) ||
listener.equals(pongMessageHandler)) {
pongMessageHandler = null;
removed = true;
}
if (!removed) {
// ISE for now. Could swallow this silently / log this if the ISE
// becomes a problem
throw new IllegalStateException(
sm.getString("wsSession.removeHandlerFailed", listener));
}
}
@Override
public String getProtocolVersion() {
checkState();
return Constants.WS_VERSION_HEADER_VALUE;
}
@Override
public String getNegotiatedSubprotocol() {
checkState();
return subProtocol;
}
@Override
public List<Extension> getNegotiatedExtensions() {
checkState();
return Collections.emptyList();
}
@Override
public boolean isSecure() {
checkState();
return secure;
}
@Override
public boolean isOpen() {
return state == State.OPEN;
}
@Override
public long getMaxIdleTimeout() {
checkState();
return maxIdleTimeout;
}
@Override
public void setMaxIdleTimeout(long timeout) {
checkState();
this.maxIdleTimeout = timeout;
}
@Override
public void setMaxBinaryMessageBufferSize(int max) {
checkState();
this.maxBinaryMessageBufferSize = max;
}
@Override
public int getMaxBinaryMessageBufferSize() {
checkState();
return maxBinaryMessageBufferSize;
}
@Override
public void setMaxTextMessageBufferSize(int max) {
checkState();
this.maxTextMessageBufferSize = max;
}
@Override
public int getMaxTextMessageBufferSize() {
checkState();
return maxTextMessageBufferSize;
}
@Override
public Set<Session> getOpenSessions() {
checkState();
return webSocketContainer.getOpenSessions(localEndpoint.getClass());
}
@Override
public RemoteEndpoint.Async getAsyncRemote() {
checkState();
return remoteEndpointAsync;
}
@Override
public RemoteEndpoint.Basic getBasicRemote() {
checkState();
return remoteEndpointBasic;
}
@Override
public void close() throws IOException {
close(new CloseReason(CloseCodes.NORMAL_CLOSURE, ""));
}
@Override
public void close(CloseReason closeReason) throws IOException {
doClose(closeReason, closeReason);
}
/**
* WebSocket 1.0. Section 2.1.5.
* Need internal close method as spec requires that the local endpoint
* receives a 1006 on timeout.
*/
private void doClose(CloseReason closeReasonMessage,
CloseReason closeReasonLocal) {
// Double-checked locking. OK because state is volatile
if (state != State.OPEN) {
return;
}
synchronized (stateLock) {
if (state != State.OPEN) {
return;
}
state = State.CLOSING;
sendCloseMessage(closeReasonMessage);
fireEndpointOnClose(closeReasonLocal);
state = State.CLOSED;
}
IOException ioe = new IOException(sm.getString("wsSession.messageFailed"));
SendResult sr = new SendResult(ioe);
for (FutureToSendHandler f2sh : futures.keySet()) {
f2sh.onResult(sr);
}
}
/**
* Called when a close message is received. Should only ever happen once.
* Also called after a protocol error when the ProtocolHandler needs to
* force the closing of the connection.
*/
public void onClose(CloseReason closeReason) {
synchronized (stateLock) {
if (state == State.OPEN) {
sendCloseMessage(closeReason);
fireEndpointOnClose(closeReason);
state = State.CLOSED;
}
// Close the socket
wsRemoteEndpoint.close();
}
}
private void fireEndpointOnClose(CloseReason closeReason) {
// Fire the onClose event
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
localEndpoint.onClose(this, closeReason);
} finally {
t.setContextClassLoader(cl);
}
}
private void sendCloseMessage(CloseReason closeReason) {
// 125 is maximum size for the payload of a control message
ByteBuffer msg = ByteBuffer.allocate(125);
CloseCode closeCode = closeReason.getCloseCode();
msg.putShort((short) closeCode.getCode());
String reason = closeReason.getReasonPhrase();
if (reason != null && reason.length() > 0) {
appendCloseReasonWithTruncation(msg, reason);
}
msg.flip();
try {
wsRemoteEndpoint.startMessageBlock(
Constants.OPCODE_CLOSE, msg, true);
} catch (IOException ioe) {
// Failed to send close message. Close the socket and let the caller
// deal with the Exception
if (log.isDebugEnabled()) {
log.debug(sm.getString("wsSession.sendCloseFail"), ioe);
}
wsRemoteEndpoint.close();
// Failure to send a close message is not unexpected in the case of
// an abnormal closure (usually triggered by a failure to read/write
// from/to the client. In this case do not trigger the endpoint's
// error handling
if (closeCode != CloseCodes.CLOSED_ABNORMALLY) {
localEndpoint.onError(this, ioe);
}
} finally {
webSocketContainer.unregisterSession(localEndpoint, this);
}
}
/**
* Use protected so unit tests can access this method directly.
*/
protected static void appendCloseReasonWithTruncation(ByteBuffer msg,
String reason) {
// Once the close code has been added there are a maximum of 123 bytes
// left for the reason phrase. If it is truncated then care needs to be
// taken to ensure the bytes are not truncated in the middle of a
// multi-byte UTF-8 character.
byte[] reasonBytes = reason.getBytes(StandardCharsets.UTF_8);
if (reasonBytes.length <= 123) {
// No need to truncate
msg.put(reasonBytes);
} else {
// Need to truncate
int remaining = 123 - ELLIPSIS_BYTES_LEN;
int pos = 0;
byte[] bytesNext = reason.substring(pos, pos + 1).getBytes(
StandardCharsets.UTF_8);
while (remaining >= bytesNext.length) {
msg.put(bytesNext);
remaining -= bytesNext.length;
pos++;
bytesNext = reason.substring(pos, pos + 1).getBytes(
StandardCharsets.UTF_8);
}
msg.put(ELLIPSIS_BYTES);
}
}
/**
* Make the session aware of a {@link FutureToSendHandler} that will need to
* be forcibly closed if the session closes before the
* {@link FutureToSendHandler} completes.
*/
protected void registerFuture(FutureToSendHandler f2sh) {
futures.put(f2sh, f2sh);
}
/**
* Remove a {@link FutureToSendHandler} from the set of tracked instances.
*/
protected void unregisterFuture(FutureToSendHandler f2sh) {
futures.remove(f2sh);
}
@Override
public URI getRequestURI() {
checkState();
return requestUri;
}
@Override
public Map<String,List<String>> getRequestParameterMap() {
checkState();
return requestParameterMap;
}
@Override
public String getQueryString() {
checkState();
return queryString;
}
@Override
public Principal getUserPrincipal() {
checkState();
return userPrincipal;
}
@Override
public Map<String,String> getPathParameters() {
checkState();
return pathParameters;
}
@Override
public String getId() {
return id;
}
@Override
public Map<String,Object> getUserProperties() {
checkState();
return userProperties;
}
public Endpoint getLocal() {
return localEndpoint;
}
public String getHttpSessionId() {
return httpSessionId;
}
protected MessageHandler getTextMessageHandler() {
return textMessageHandler;
}
protected MessageHandler getBinaryMessageHandler() {
return binaryMessageHandler;
}
protected MessageHandler.Whole<PongMessage> getPongMessageHandler() {
return pongMessageHandler;
}
protected void updateLastActive() {
lastActive = System.currentTimeMillis();
}
protected void checkExpiration() {
long timeout = maxIdleTimeout;
if (timeout < 1) {
return;
}
if (System.currentTimeMillis() - lastActive > timeout) {
String msg = sm.getString("wsSession.timeout");
doClose(new CloseReason(CloseCodes.GOING_AWAY, msg),
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
}
}
private void checkState() {
if (state == State.CLOSED) {
throw new IllegalStateException(sm.getString("wsSession.closed"));
}
}
private static enum State {
OPEN,
CLOSING,
CLOSED
}
}
|
55,691
|
Bug 55691 javax.el.ArrayELResolver.setValue not supporting arrays of primitives
|
was working in tomcat 6.0.20 ERROR javax.faces.context.ExceptionHandlerWrapper - javax.faces.component.UpdateModelException: java.lang.ClassCastException: Unable to add an object of type [java.lang.Integer] to an array of objects of type [int] java.lang.ClassCastException: Unable to add an object of type [java.lang.Integer] to an array of objects of type [int] at javax.el.ArrayELResolver.setValue(ArrayELResolver.java:94) at com.sun.faces.el.DemuxCompositeELResolver._setValue(DemuxCompositeELResolver.java:255) at com.sun.faces.el.DemuxCompositeELResolver.setValue(DemuxCompositeELResolver.java:281) at org.apache.el.parser.AstValue.setValue(AstValue.java:158) at org.apache.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:249) at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:131) at javax.faces.component.UIInput.updateModel(UIInput.java:818) at javax.faces.component.UIInput.processUpdates(UIInput.java:735) at javax.faces.component.UIData.iterate(UIData.java:2001) at javax.faces.component.UIData.processUpdates(UIData.java:1253) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIForm.processUpdates(UIForm.java:281) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231) at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
|
resolved fixed
|
b82c0c6
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-28T20:59:41Z
| 2013-10-23T03:46:40Z
|
java/javax/el/ArrayELResolver.java
|
/*
* 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 javax.el;
import java.beans.FeatureDescriptor;
import java.lang.reflect.Array;
import java.util.Iterator;
public class ArrayELResolver extends ELResolver {
private final boolean readOnly;
public ArrayELResolver() {
this.readOnly = false;
}
public ArrayELResolver(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(base, property);
try {
int idx = coerce(property);
checkBounds(base, idx);
} catch (IllegalArgumentException e) {
// ignore
}
return base.getClass().getComponentType();
}
return null;
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(base, property);
int idx = coerce(property);
if (idx < 0 || idx >= Array.getLength(base)) {
return null;
}
return Array.get(base, idx);
}
return null;
}
@Override
public void setValue(ELContext context, Object base, Object property,
Object value) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(base, property);
if (this.readOnly) {
throw new PropertyNotWritableException(Util.message(context,
"resolverNotWriteable", base.getClass().getName()));
}
int idx = coerce(property);
checkBounds(base, idx);
if (value != null &&
!base.getClass().getComponentType().isAssignableFrom(
value.getClass())) {
throw new ClassCastException(Util.message(context,
"objectNotAssignable", value.getClass().getName(),
base.getClass().getComponentType().getName()));
}
Array.set(base, idx, value);
}
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(base, property);
try {
int idx = coerce(property);
checkBounds(base, idx);
} catch (IllegalArgumentException e) {
// ignore
}
}
return this.readOnly;
}
@Override
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
return null;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
if (base != null && base.getClass().isArray()) {
return Integer.class;
}
return null;
}
private static final void checkBounds(Object base, int idx) {
if (idx < 0 || idx >= Array.getLength(base)) {
throw new PropertyNotFoundException(
new ArrayIndexOutOfBoundsException(idx).getMessage());
}
}
private static final int coerce(Object property) {
if (property instanceof Number) {
return ((Number) property).intValue();
}
if (property instanceof Character) {
return ((Character) property).charValue();
}
if (property instanceof Boolean) {
return (((Boolean) property).booleanValue() ? 1 : 0);
}
if (property instanceof String) {
return Integer.parseInt((String) property);
}
throw new IllegalArgumentException(property != null ?
property.toString() : "null");
}
}
|
55,691
|
Bug 55691 javax.el.ArrayELResolver.setValue not supporting arrays of primitives
|
was working in tomcat 6.0.20 ERROR javax.faces.context.ExceptionHandlerWrapper - javax.faces.component.UpdateModelException: java.lang.ClassCastException: Unable to add an object of type [java.lang.Integer] to an array of objects of type [int] java.lang.ClassCastException: Unable to add an object of type [java.lang.Integer] to an array of objects of type [int] at javax.el.ArrayELResolver.setValue(ArrayELResolver.java:94) at com.sun.faces.el.DemuxCompositeELResolver._setValue(DemuxCompositeELResolver.java:255) at com.sun.faces.el.DemuxCompositeELResolver.setValue(DemuxCompositeELResolver.java:281) at org.apache.el.parser.AstValue.setValue(AstValue.java:158) at org.apache.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:249) at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:131) at javax.faces.component.UIInput.updateModel(UIInput.java:818) at javax.faces.component.UIInput.processUpdates(UIInput.java:735) at javax.faces.component.UIData.iterate(UIData.java:2001) at javax.faces.component.UIData.processUpdates(UIData.java:1253) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIForm.processUpdates(UIForm.java:281) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231) at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
|
resolved fixed
|
b82c0c6
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-28T20:59:41Z
| 2013-10-23T03:46:40Z
|
java/javax/el/Util.java
|
/*
* 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 javax.el;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Util {
/**
* Checks whether the supplied Throwable is one that needs to be
* rethrown and swallows all others.
* @param t the Throwable to check
*/
static void handleThrowable(Throwable t) {
if (t instanceof ThreadDeath) {
throw (ThreadDeath) t;
}
if (t instanceof VirtualMachineError) {
throw (VirtualMachineError) t;
}
// All other instances of Throwable will be silently swallowed
}
static String message(ELContext context, String name, Object... props) {
Locale locale = null;
if (context != null) {
locale = context.getLocale();
}
if (locale == null) {
locale = Locale.getDefault();
if (locale == null) {
return "";
}
}
ResourceBundle bundle = ResourceBundle.getBundle(
"javax.el.LocalStrings", locale);
try {
String template = bundle.getString(name);
if (props != null) {
template = MessageFormat.format(template, props);
}
return template;
} catch (MissingResourceException e) {
return "Missing Resource: '" + name + "' for Locale "
+ locale.getDisplayName();
}
}
private static final CacheValue nullTcclFactory = new CacheValue();
private static final ConcurrentMap<CacheKey, CacheValue> factoryCache =
new ConcurrentHashMap<>();
/**
* Provides a per class loader cache of ExpressionFactory instances without
* pinning any in memory as that could trigger a memory leak.
*/
static ExpressionFactory getExpressionFactory() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
CacheValue cacheValue = null;
ExpressionFactory factory = null;
if (tccl == null) {
cacheValue = nullTcclFactory;
} else {
CacheKey key = new CacheKey(tccl);
cacheValue = factoryCache.get(key);
if (cacheValue == null) {
CacheValue newCacheValue = new CacheValue();
cacheValue = factoryCache.putIfAbsent(key, newCacheValue);
if (cacheValue == null) {
cacheValue = newCacheValue;
}
}
}
final Lock readLock = cacheValue.getLock().readLock();
readLock.lock();
try {
factory = cacheValue.getExpressionFactory();
} finally {
readLock.unlock();
}
if (factory == null) {
final Lock writeLock = cacheValue.getLock().writeLock();
try {
writeLock.lock();
factory = cacheValue.getExpressionFactory();
if (factory == null) {
factory = ExpressionFactory.newInstance();
cacheValue.setExpressionFactory(factory);
}
} finally {
writeLock.unlock();
}
}
return factory;
}
/**
* Key used to cache default ExpressionFactory information per class
* loader. The class loader reference is never {@code null}, because
* {@code null} tccl is handled separately.
*/
private static class CacheKey {
private final int hash;
private final WeakReference<ClassLoader> ref;
public CacheKey(ClassLoader key) {
hash = key.hashCode();
ref = new WeakReference<>(key);
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CacheKey)) {
return false;
}
ClassLoader thisKey = ref.get();
if (thisKey == null) {
return false;
}
return thisKey == ((CacheKey) obj).ref.get();
}
}
private static class CacheValue {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private WeakReference<ExpressionFactory> ref;
public CacheValue() {
}
public ReadWriteLock getLock() {
return lock;
}
public ExpressionFactory getExpressionFactory() {
return ref != null ? ref.get() : null;
}
public void setExpressionFactory(ExpressionFactory factory) {
ref = new WeakReference<>(factory);
}
}
/*
* This method duplicates code in org.apache.el.util.ReflectionUtil. When
* making changes keep the code in sync.
*/
static Method findMethod(Class<?> clazz, String methodName,
Class<?>[] paramTypes, Object[] paramValues) {
if (clazz == null || methodName == null) {
throw new MethodNotFoundException(
message(null, "util.method.notfound", clazz, methodName,
paramString(paramTypes)));
}
if (paramTypes == null) {
paramTypes = getTypesFromValues(paramValues);
}
Method[] methods = clazz.getMethods();
List<Wrapper> wrappers = Wrapper.wrap(methods, methodName);
Wrapper result = findWrapper(
clazz, wrappers, methodName, paramTypes, paramValues);
if (result == null) {
return null;
}
return getMethod(clazz, (Method) result.unWrap());
}
/*
* This method duplicates code in org.apache.el.util.ReflectionUtil. When
* making changes keep the code in sync.
*/
@SuppressWarnings("null")
private static Wrapper findWrapper(Class<?> clazz, List<Wrapper> wrappers,
String name, Class<?>[] paramTypes, Object[] paramValues) {
Map<Wrapper,Integer> candidates = new HashMap<>();
int paramCount;
if (paramTypes == null) {
paramCount = 0;
} else {
paramCount = paramTypes.length;
}
for (Wrapper w : wrappers) {
Class<?>[] mParamTypes = w.getParameterTypes();
int mParamCount;
if (mParamTypes == null) {
mParamCount = 0;
} else {
mParamCount = mParamTypes.length;
}
// Check the number of parameters
if (!(paramCount == mParamCount ||
(w.isVarArgs() && paramCount >= mParamCount))) {
// Method has wrong number of parameters
continue;
}
// Check the parameters match
int exactMatch = 0;
boolean noMatch = false;
for (int i = 0; i < mParamCount; i++) {
// Can't be null
if (mParamTypes[i].equals(paramTypes[i])) {
exactMatch++;
} else if (i == (mParamCount - 1) && w.isVarArgs()) {
Class<?> varType = mParamTypes[i].getComponentType();
for (int j = i; j < paramCount; j++) {
if (!isAssignableFrom(paramTypes[j], varType)) {
if (paramValues == null) {
noMatch = true;
break;
} else {
if (!isCoercibleFrom(paramValues[j], varType)) {
noMatch = true;
break;
}
}
}
// Don't treat a varArgs match as an exact match, it can
// lead to a varArgs method matching when the result
// should be ambiguous
}
} else if (!isAssignableFrom(paramTypes[i], mParamTypes[i])) {
if (paramValues == null) {
noMatch = true;
break;
} else {
if (!isCoercibleFrom(paramValues[i], mParamTypes[i])) {
noMatch = true;
break;
}
}
}
}
if (noMatch) {
continue;
}
// If a method is found where every parameter matches exactly,
// return it
if (exactMatch == paramCount) {
return w;
}
candidates.put(w, Integer.valueOf(exactMatch));
}
// Look for the method that has the highest number of parameters where
// the type matches exactly
int bestMatch = 0;
Wrapper match = null;
boolean multiple = false;
for (Map.Entry<Wrapper, Integer> entry : candidates.entrySet()) {
if (entry.getValue().intValue() > bestMatch ||
match == null) {
bestMatch = entry.getValue().intValue();
match = entry.getKey();
multiple = false;
} else if (entry.getValue().intValue() == bestMatch) {
multiple = true;
}
}
if (multiple) {
if (bestMatch == paramCount - 1) {
// Only one parameter is not an exact match - try using the
// super class
match = resolveAmbiguousWrapper(candidates.keySet(), paramTypes);
} else {
match = null;
}
if (match == null) {
// If multiple methods have the same matching number of parameters
// the match is ambiguous so throw an exception
throw new MethodNotFoundException(message(
null, "util.method.ambiguous", clazz, name,
paramString(paramTypes)));
}
}
// Handle case where no match at all was found
if (match == null) {
throw new MethodNotFoundException(message(
null, "util.method.notfound", clazz, name,
paramString(paramTypes)));
}
return match;
}
private static final String paramString(Class<?>[] types) {
if (types != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < types.length; i++) {
if (types[i] == null) {
sb.append("null, ");
} else {
sb.append(types[i].getName()).append(", ");
}
}
if (sb.length() > 2) {
sb.setLength(sb.length() - 2);
}
return sb.toString();
}
return null;
}
/*
* This method duplicates code in org.apache.el.util.ReflectionUtil. When
* making changes keep the code in sync.
*/
private static Wrapper resolveAmbiguousWrapper(Set<Wrapper> candidates,
Class<?>[] paramTypes) {
// Identify which parameter isn't an exact match
Wrapper w = candidates.iterator().next();
int nonMatchIndex = 0;
Class<?> nonMatchClass = null;
for (int i = 0; i < paramTypes.length; i++) {
if (w.getParameterTypes()[i] != paramTypes[i]) {
nonMatchIndex = i;
nonMatchClass = paramTypes[i];
break;
}
}
if (nonMatchClass == null) {
// Null will always be ambiguous
return null;
}
for (Wrapper c : candidates) {
if (c.getParameterTypes()[nonMatchIndex] ==
paramTypes[nonMatchIndex]) {
// Methods have different non-matching parameters
// Result is ambiguous
return null;
}
}
// Can't be null
Class<?> superClass = nonMatchClass.getSuperclass();
while (superClass != null) {
for (Wrapper c : candidates) {
if (c.getParameterTypes()[nonMatchIndex].equals(superClass)) {
// Found a match
return c;
}
}
superClass = superClass.getSuperclass();
}
// Treat instances of Number as a special case
Wrapper match = null;
if (Number.class.isAssignableFrom(nonMatchClass)) {
for (Wrapper c : candidates) {
Class<?> candidateType = c.getParameterTypes()[nonMatchIndex];
if (Number.class.isAssignableFrom(candidateType) ||
candidateType.isPrimitive()) {
if (match == null) {
match = c;
} else {
// Match still ambiguous
match = null;
break;
}
}
}
}
return match;
}
/*
* This method duplicates code in org.apache.el.util.ReflectionUtil. When
* making changes keep the code in sync.
*/
private static boolean isAssignableFrom(Class<?> src, Class<?> target) {
// src will always be an object
// Short-cut. null is always assignable to an object and in EL null
// can always be coerced to a valid value for a primitive
if (src == null) {
return true;
}
Class<?> targetClass;
if (target.isPrimitive()) {
if (target == Boolean.TYPE) {
targetClass = Boolean.class;
} else if (target == Character.TYPE) {
targetClass = Character.class;
} else if (target == Byte.TYPE) {
targetClass = Byte.class;
} else if (target == Short.TYPE) {
targetClass = Short.class;
} else if (target == Integer.TYPE) {
targetClass = Integer.class;
} else if (target == Long.TYPE) {
targetClass = Long.class;
} else if (target == Float.TYPE) {
targetClass = Float.class;
} else {
targetClass = Double.class;
}
} else {
targetClass = target;
}
return targetClass.isAssignableFrom(src);
}
/*
* This method duplicates code in org.apache.el.util.ReflectionUtil. When
* making changes keep the code in sync.
*/
private static boolean isCoercibleFrom(Object src, Class<?> target) {
// TODO: This isn't pretty but it works. Significant refactoring would
// be required to avoid the exception.
try {
getExpressionFactory().coerceToType(src, target);
} catch (ELException e) {
return false;
}
return true;
}
private static Class<?>[] getTypesFromValues(Object[] values) {
if (values == null) {
return null;
}
Class<?> result[] = new Class<?>[values.length];
for (int i = 0; i < values.length; i++) {
if (values[i] == null) {
result[i] = null;
} else {
result[i] = values[i].getClass();
}
}
return result;
}
/*
* This method duplicates code in org.apache.el.util.ReflectionUtil. When
* making changes keep the code in sync.
*/
static Method getMethod(Class<?> type, Method m) {
if (m == null || Modifier.isPublic(type.getModifiers())) {
return m;
}
Class<?>[] inf = type.getInterfaces();
Method mp = null;
for (int i = 0; i < inf.length; i++) {
try {
mp = inf[i].getMethod(m.getName(), m.getParameterTypes());
mp = getMethod(mp.getDeclaringClass(), mp);
if (mp != null) {
return mp;
}
} catch (NoSuchMethodException e) {
// Ignore
}
}
Class<?> sup = type.getSuperclass();
if (sup != null) {
try {
mp = sup.getMethod(m.getName(), m.getParameterTypes());
mp = getMethod(mp.getDeclaringClass(), mp);
if (mp != null) {
return mp;
}
} catch (NoSuchMethodException e) {
// Ignore
}
}
return null;
}
static Constructor<?> findConstructor(Class<?> clazz, Class<?>[] paramTypes,
Object[] paramValues) {
String methodName = "<init>";
if (clazz == null) {
throw new MethodNotFoundException(
message(null, "util.method.notfound", clazz, methodName,
paramString(paramTypes)));
}
if (paramTypes == null) {
paramTypes = getTypesFromValues(paramValues);
}
Constructor<?>[] constructors = clazz.getConstructors();
List<Wrapper> wrappers = Wrapper.wrap(constructors);
Wrapper result = findWrapper(
clazz, wrappers, methodName, paramTypes, paramValues);
if (result == null) {
return null;
}
return getConstructor(clazz, (Constructor<?>) result.unWrap());
}
static Constructor<?> getConstructor(Class<?> type, Constructor<?> c) {
if (c == null || Modifier.isPublic(type.getModifiers())) {
return c;
}
Constructor<?> cp = null;
Class<?> sup = type.getSuperclass();
if (sup != null) {
try {
cp = sup.getConstructor(c.getParameterTypes());
cp = getConstructor(cp.getDeclaringClass(), cp);
if (cp != null) {
return cp;
}
} catch (NoSuchMethodException e) {
// Ignore
}
}
return null;
}
static Object[] buildParameters(Class<?>[] parameterTypes,
boolean isVarArgs,Object[] params) {
ExpressionFactory factory = getExpressionFactory();
Object[] parameters = null;
if (parameterTypes.length > 0) {
parameters = new Object[parameterTypes.length];
int paramCount = params.length;
if (isVarArgs) {
int varArgIndex = parameterTypes.length - 1;
// First argCount-1 parameters are standard
for (int i = 0; (i < varArgIndex); i++) {
parameters[i] = factory.coerceToType(params[i],
parameterTypes[i]);
}
// Last parameter is the varargs
Class<?> varArgClass =
parameterTypes[varArgIndex].getComponentType();
final Object varargs = Array.newInstance(
varArgClass,
(paramCount - varArgIndex));
for (int i = (varArgIndex); i < paramCount; i++) {
Array.set(varargs, i - varArgIndex,
factory.coerceToType(params[i], varArgClass));
}
parameters[varArgIndex] = varargs;
} else {
parameters = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
parameters[i] = factory.coerceToType(params[i],
parameterTypes[i]);
}
}
}
return parameters;
}
private abstract static class Wrapper {
public static List<Wrapper> wrap(Method[] methods, String name) {
List<Wrapper> result = new ArrayList<>();
for (Method method : methods) {
if (method.getName().equals(name)) {
result.add(new MethodWrapper(method));
}
}
return result;
}
public static List<Wrapper> wrap(Constructor<?>[] constructors) {
List<Wrapper> result = new ArrayList<>();
for (Constructor<?> constructor : constructors) {
result.add(new ConstructorWrapper(constructor));
}
return result;
}
public abstract Object unWrap();
public abstract Class<?>[] getParameterTypes();
public abstract boolean isVarArgs();
}
private static class MethodWrapper extends Wrapper {
private final Method m;
public MethodWrapper(Method m) {
this.m = m;
}
@Override
public Object unWrap() {
return m;
}
@Override
public Class<?>[] getParameterTypes() {
return m.getParameterTypes();
}
@Override
public boolean isVarArgs() {
return m.isVarArgs();
}
}
private static class ConstructorWrapper extends Wrapper {
private final Constructor<?> c;
public ConstructorWrapper(Constructor<?> c) {
this.c = c;
}
@Override
public Object unWrap() {
return c;
}
@Override
public Class<?>[] getParameterTypes() {
return c.getParameterTypes();
}
@Override
public boolean isVarArgs() {
return c.isVarArgs();
}
}
}
|
55,691
|
Bug 55691 javax.el.ArrayELResolver.setValue not supporting arrays of primitives
|
was working in tomcat 6.0.20 ERROR javax.faces.context.ExceptionHandlerWrapper - javax.faces.component.UpdateModelException: java.lang.ClassCastException: Unable to add an object of type [java.lang.Integer] to an array of objects of type [int] java.lang.ClassCastException: Unable to add an object of type [java.lang.Integer] to an array of objects of type [int] at javax.el.ArrayELResolver.setValue(ArrayELResolver.java:94) at com.sun.faces.el.DemuxCompositeELResolver._setValue(DemuxCompositeELResolver.java:255) at com.sun.faces.el.DemuxCompositeELResolver.setValue(DemuxCompositeELResolver.java:281) at org.apache.el.parser.AstValue.setValue(AstValue.java:158) at org.apache.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:249) at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:131) at javax.faces.component.UIInput.updateModel(UIInput.java:818) at javax.faces.component.UIInput.processUpdates(UIInput.java:735) at javax.faces.component.UIData.iterate(UIData.java:2001) at javax.faces.component.UIData.processUpdates(UIData.java:1253) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIForm.processUpdates(UIForm.java:281) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242) at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231) at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
|
resolved fixed
|
b82c0c6
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-28T20:59:41Z
| 2013-10-23T03:46:40Z
|
test/javax/el/TestArrayELResolver.java
|
/*
* 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 javax.el;
import org.junit.Assert;
import org.junit.Test;
public class TestArrayELResolver {
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not an array.
*/
@Test
public void testGetType02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_TYPE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetType03() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Class<?> result = resolver.getType(context, base, new Integer(0));
Assert.assertEquals(base.getClass().getComponentType(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetType04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.getType(context, base, new Integer(1));
}
/**
* Tests that a result is returned even when a coercion cannot be performed.
*/
@Test
public void testGetType05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Class<?> result = resolver.getType(context, base, "index");
Assert.assertEquals(base.getClass().getComponentType(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not an array.
*/
@Test
public void testGetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_VALUE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue03() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Object result = resolver.getValue(context, base, new Integer(0));
Assert.assertEquals("element", result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests a coercion cannot be performed as the key is not integer.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetValue04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.getValue(context, base, "key");
}
/**
* Tests that the key is out of bounds and null will be returned.
*/
@Test
public void testGetValue05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Object result = resolver.getValue(context, base, new Integer(1));
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
result = resolver.getValue(context, base, new Integer(-1));
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that a valid property is not set if base is not an array.
*/
@Test
public void testSetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.SET_VALUE,
false);
}
/**
* Tests that an exception is thrown when readOnly is true.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue03() {
ArrayELResolver resolver = new ArrayELResolver(true);
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
resolver.setValue(context, new String[] {}, new Object(), new Object());
}
/**
* Tests that a valid property is set.
*/
@Test
public void testSetValue04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, new Integer(0), "new-element");
Assert.assertEquals("new-element",
resolver.getValue(context, base, new Integer(0)));
Assert.assertTrue(context.isPropertyResolved());
resolver.setValue(context, base, new Integer(0), null);
Assert.assertEquals(null,
resolver.getValue(context, base, new Integer(0)));
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests a coercion cannot be performed as the key is not integer.
*/
@Test(expected = IllegalArgumentException.class)
public void testSetValue05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, "key", "new-element");
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testSetValue06() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, new Integer(1), "new-element");
}
/**
* Tests that an exception will be thrown if the value is not from the
* corresponding type.
*/
@Test(expected = ClassCastException.class)
public void testSetValue07() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, new Integer(0), new Integer(1));
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is false if base is not an array.
*/
@Test
public void testIsReadOnly02() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new Object(),
new Object());
Assert.assertFalse(result);
Assert.assertFalse(context.isPropertyResolved());
resolver = new ArrayELResolver(true);
result = resolver.isReadOnly(context, new Object(), new Object());
Assert.assertTrue(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that if the ArrayELResolver is constructed with readOnly the method
* will return always true, otherwise false.
*/
@Test
public void testIsReadOnly03() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
boolean result = resolver.isReadOnly(context, base, new Integer(0));
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new ArrayELResolver(true);
result = resolver.isReadOnly(context, base, new Integer(0));
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testIsReadOnly04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.isReadOnly(context, base, new Integer(1));
}
/**
* Tests that a result is returned even when a coercion cannot be performed.
*/
@Test
public void testIsReadOnly05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
boolean result = resolver.isReadOnly(context, base, "key");
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new ArrayELResolver(true);
result = resolver.isReadOnly(context, base, "key");
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
private void doNegativeTest(Object base, Object trigger,
MethodUnderTest method, boolean checkResult) {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, base, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, base, trigger, new Object());
break;
}
case GET_TYPE: {
result = resolver.getType(context, base, trigger);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
if (checkResult) {
Assert.assertNull(result);
}
Assert.assertFalse(context.isPropertyResolved());
}
private static enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE
}
}
|
55,684
|
Bug 55684 WebappClassLoader.getThread want an access to root ThreadGroup
|
Tomcat may not have all permissions granted. The method WebappClassLoader.getThread try to access the root ThreadGroup in order to list all threads. You should either manage SecurityException or avoid to access the parent ThreadGroup of the thread which start Tomcat.
|
resolved fixed
|
d244284
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-29T09:53:27Z
| 2013-10-21T21:13:20Z
|
java/org/apache/catalina/loader/WebappClassLoader.java
|
/*
* 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.loader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.catalina.Globals;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.apache.tomcat.InstrumentableClassLoader;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
* Specialized web application class loader.
* <p>
* This class loader is a full reimplementation of the
* <code>URLClassLoader</code> from the JDK. It is designed to be fully
* compatible with a normal <code>URLClassLoader</code>, although its internal
* behavior may be completely different.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - By default, this class loader follows
* the delegation model required by the specification. The system class
* loader will be queried first, then the local repositories, and only then
* delegation to the parent class loader will occur. This allows the web
* application to override any shared class except the classes from J2SE.
* Special handling is provided from the JAXP XML parser interfaces, the JNDI
* interfaces, and the classes from the servlet API, which are never loaded
* from the webapp repositories. The <code>delegate</code> property
* allows an application to modify this behavior to move the parent class loader
* ahead of the local repositories.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper
* compilation technology, any repository which contains classes from
* the servlet API will be ignored by the class loader.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source
* URLs which include the full JAR URL when a class is loaded from a JAR file,
* which allows setting security permission at the class level, even when a
* class is contained inside a JAR.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in
* the order they are added via the initial constructor and/or any subsequent
* calls to <code>addRepository()</code> or <code>addJar()</code>.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or
* security is made unless a security manager is present.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - As of 8.0, this class
* loader implements {@link InstrumentableClassLoader}, permitting web
* application classes to instrument other classes in the same web
* application. It does not permit instrumentation of system or container
* classes or classes in other web apps.
*
* @author Remy Maucherat
* @author Craig R. McClanahan
* @version $Id$
*/
public class WebappClassLoader extends URLClassLoader
implements Lifecycle, InstrumentableClassLoader {
private static final org.apache.juli.logging.Log log=
org.apache.juli.logging.LogFactory.getLog( WebappClassLoader.class );
/**
* List of ThreadGroup names to ignore when scanning for web application
* started threads that need to be shut down.
*/
private static final List<String> JVM_THREAD_GROUP_NAMES = new ArrayList<>();
private static final String JVN_THREAD_GROUP_SYSTEM = "system";
private static final String CLASS_FILE_SUFFIX = ".class";
static {
JVM_THREAD_GROUP_NAMES.add(JVN_THREAD_GROUP_SYSTEM);
JVM_THREAD_GROUP_NAMES.add("RMI Runtime");
}
protected class PrivilegedFindResourceByName
implements PrivilegedAction<ResourceEntry> {
protected final String name;
protected final String path;
PrivilegedFindResourceByName(String name, String path) {
this.name = name;
this.path = path;
}
@Override
public ResourceEntry run() {
return findResourceInternal(name, path);
}
}
protected static final class PrivilegedGetClassLoader
implements PrivilegedAction<ClassLoader> {
public final Class<?> clazz;
public PrivilegedGetClassLoader(Class<?> clazz){
this.clazz = clazz;
}
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
}
// ------------------------------------------------------- Static Variables
/**
* The set of trigger classes that will cause a proposed repository not
* to be added if this class is visible to the class loader that loaded
* this factory class. Typically, trigger classes will be listed for
* components that have been integrated into the JDK for later versions,
* but where the corresponding JAR files are required to run on
* earlier versions.
*/
protected static final String[] triggers = {
"javax.servlet.Servlet", "javax.el.Expression" // Servlet API
};
/**
* Set of package names which are not allowed to be loaded from a webapp
* class loader without delegating first.
*/
protected static final String[] packageTriggers = {
};
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Use anti JAR locking code, which does URL rerouting when accessing
* resources.
*/
boolean antiJARLocking = false;
// ----------------------------------------------------------- Constructors
/**
* Construct a new ClassLoader with no defined repositories and no
* parent ClassLoader.
*/
public WebappClassLoader() {
super(new URL[0]);
this.parent = getParent();
system = getSystemClassLoader();
securityManager = System.getSecurityManager();
if (securityManager != null) {
refreshPolicy();
}
}
/**
* Construct a new ClassLoader with no defined repositories and the given
* parent ClassLoader.
* <p>
* Method is used via reflection -
* see {@link WebappLoader#createClassLoader()}
*
* @param parent Our parent class loader
*/
public WebappClassLoader(ClassLoader parent) {
super(new URL[0], parent);
this.parent = getParent();
system = getSystemClassLoader();
securityManager = System.getSecurityManager();
if (securityManager != null) {
refreshPolicy();
}
}
// ----------------------------------------------------- Instance Variables
/**
* Associated web resources for this webapp.
* TODO Review the use of resources in this class to see if further
* simplifications can be made.
*/
protected WebResourceRoot resources = null;
/**
* The cache of ResourceEntry for classes and resources we have loaded,
* keyed by resource name.
*/
protected final HashMap<String, ResourceEntry> resourceEntries = new HashMap<>();
/**
* The list of not found resources.
*/
protected final HashMap<String, String> notFoundResources =
new LinkedHashMap<String, String>() {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(
Map.Entry<String, String> eldest) {
return size() > 1000;
}
};
/**
* Should this class loader delegate to the parent class loader
* <strong>before</strong> searching its own repositories (i.e. the
* usual Java2 delegation model)? If set to <code>false</code>,
* this class loader will search its own repositories first, and
* delegate to the parent only if the class or resource is not
* found locally. Note that the default, <code>false</code>, is
* the behavior called for by the servlet specification.
*/
protected boolean delegate = false;
/**
* Last time a JAR was accessed.
*/
protected long lastJarAccessed = 0L;
/**
* The path to the repository for locally loaded classes or resources. This
* would normally be /WEB-INF/classes/.
*/
protected String repositoryPath = null;
/**
* Repositories URLs, used to cache the result of getURLs.
*/
protected URL[] repositoryURLs = null;
/**
* The {@link WebResource} for the repository for locally loaded classes or
* resources. This would normally point to /WEB-INF/classes/.
*/
protected WebResource repository = null;
/**
* The list of JARs, in the order they should be searched
* for locally loaded classes or resources.
*/
protected JarFile[] jarFiles = new JarFile[0];
/**
* The list of JARs, in the order they should be searched
* for locally loaded classes or resources.
*/
protected File[] jarRealFiles = new File[0];
/**
* The path which will be monitored for added Jar files.
*/
protected String jarPath = null;
/**
* The list of JARs, in the order they should be searched
* for locally loaded classes or resources.
*/
protected String[] jarNames = new String[0];
/**
* The list of JARs last modified dates, in the order they should be
* searched for locally loaded classes or resources.
*/
protected long[] lastModifiedDates = new long[0];
/**
* The list of resources which should be checked when checking for
* modifications.
*/
protected String[] paths = new String[0];
/**
* A list of read File and Jndi Permission's required if this loader
* is for a web application context.
*/
protected final ArrayList<Permission> permissionList = new ArrayList<>();
/**
* Path where resources loaded from JARs will be extracted.
*/
protected File loaderDir = null;
protected String canonicalLoaderDir = null;
/**
* The PermissionCollection for each CodeSource for a web
* application context.
*/
protected final HashMap<String, PermissionCollection> loaderPC = new HashMap<>();
/**
* Instance of the SecurityManager installed.
*/
protected final SecurityManager securityManager;
/**
* The parent class loader.
*/
protected ClassLoader parent = null;
/**
* The system class loader.
*/
protected final ClassLoader system;
/**
* Has this component been started?
*/
protected boolean started = false;
/**
* need conversion for properties files
*/
protected boolean needConvert = false;
/**
* All permission.
*/
protected final Permission allPermission = new java.security.AllPermission();
/**
* Should Tomcat attempt to null out any static or final fields from loaded
* classes when a web application is stopped as a work around for apparent
* garbage collection bugs and application coding errors? There have been
* some issues reported with log4j when this option is true. Applications
* without memory leaks using recent JVMs should operate correctly with this
* option set to <code>false</code>. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStatic = false;
/**
* Should Tomcat attempt to terminate threads that have been started by the
* web application? Stopping threads is performed via the deprecated (for
* good reason) <code>Thread.stop()</code> method and is likely to result in
* instability. As such, enabling this should be viewed as an option of last
* resort in a development environment and is not recommended in a
* production environment. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStopThreads = false;
/**
* Should Tomcat attempt to terminate any {@link java.util.TimerThread}s
* that have been started by the web application? If not specified, the
* default value of <code>false</code> will be used.
*/
private boolean clearReferencesStopTimerThreads = false;
/**
* Should Tomcat call {@link org.apache.juli.logging.LogFactory#release()}
* when the class loader is stopped? If not specified, the default value
* of <code>true</code> is used. Changing the default setting is likely to
* lead to memory leaks and other issues.
*/
private boolean clearReferencesLogFactoryRelease = true;
/**
* If an HttpClient keep-alive timer thread has been started by this web
* application and is still running, should Tomcat change the context class
* loader from the current {@link WebappClassLoader} to
* {@link WebappClassLoader#parent} to prevent a memory leak? Note that the
* keep-alive timer thread will stop on its own once the keep-alives all
* expire however, on a busy system that might not happen for some time.
*/
private boolean clearReferencesHttpClientKeepAliveThread = true;
/**
* Holds the class file transformers decorating this class loader. The
* CopyOnWriteArrayList is thread safe. It is expensive on writes, but
* those should be rare. It is very fast on reads, since synchronization
* is not actually used. Importantly, the ClassLoader will never block
* iterating over the transformers while loading a class.
*/
private final List<ClassFileTransformer> transformers = new CopyOnWriteArrayList<>();
// ------------------------------------------------------------- Properties
/**
* Get associated resources.
*/
public WebResourceRoot getResources() {
return this.resources;
}
/**
* Set associated resources.
*/
public void setResources(WebResourceRoot resources) {
this.resources = resources;
}
/**
* Return the context name for this class loader.
*/
public String getContextName() {
if (resources == null) {
return "Unknown";
} else {
return resources.getContext().getName();
}
}
/**
* Return the "delegate first" flag for this class loader.
*/
public boolean getDelegate() {
return (this.delegate);
}
/**
* Set the "delegate first" flag for this class loader.
* If this flag is true, this class loader delegates
* to the parent class loader
* <strong>before</strong> searching its own repositories, as
* in an ordinary (non-servlet) chain of Java class loaders.
* If set to <code>false</code> (the default),
* this class loader will search its own repositories first, and
* delegate to the parent only if the class or resource is not
* found locally, as per the servlet specification.
*
* @param delegate The new "delegate first" flag
*/
public void setDelegate(boolean delegate) {
this.delegate = delegate;
}
/**
* @return Returns the antiJARLocking.
*/
public boolean getAntiJARLocking() {
return antiJARLocking;
}
/**
* @param antiJARLocking The antiJARLocking to set.
*/
public void setAntiJARLocking(boolean antiJARLocking) {
this.antiJARLocking = antiJARLocking;
}
/**
* If there is a Java SecurityManager create a read FilePermission
* or JndiPermission for the file directory path.
*
* @param filepath file directory path
*/
public void addPermission(String filepath) {
if (filepath == null) {
return;
}
String path = filepath;
if (securityManager != null) {
Permission permission = null;
if (!path.endsWith(File.separator)) {
permission = new FilePermission(path, "read");
addPermission(permission);
path = path + File.separator;
}
permission = new FilePermission(path + "-", "read");
addPermission(permission);
}
}
/**
* If there is a Java SecurityManager create a read FilePermission
* or JndiPermission for URL.
*
* @param url URL for a file or directory on local system
*/
public void addPermission(URL url) {
if (url != null) {
addPermission(url.toString());
}
}
/**
* If there is a Java SecurityManager create a Permission.
*
* @param permission The permission
*/
public void addPermission(Permission permission) {
if ((securityManager != null) && (permission != null)) {
permissionList.add(permission);
}
}
/**
* Return the JAR path.
*/
public String getJarPath() {
return this.jarPath;
}
/**
* Change the Jar path.
*/
public void setJarPath(String jarPath) {
this.jarPath = jarPath;
}
/**
* Change the work directory.
*/
public void setWorkDir(File workDir) {
this.loaderDir = new File(workDir, "loader");
if (loaderDir == null) {
canonicalLoaderDir = null;
} else {
try {
canonicalLoaderDir = loaderDir.getCanonicalPath();
if (!canonicalLoaderDir.endsWith(File.separator)) {
canonicalLoaderDir += File.separator;
}
} catch (IOException ioe) {
canonicalLoaderDir = null;
}
}
}
/**
* Utility method for use in subclasses.
* Must be called before Lifecycle methods to have any effect.
*/
protected void setParentClassLoader(ClassLoader pcl) {
parent = pcl;
}
/**
* Return the clearReferencesStatic flag for this Context.
*/
public boolean getClearReferencesStatic() {
return (this.clearReferencesStatic);
}
/**
* Set the clearReferencesStatic feature for this Context.
*
* @param clearReferencesStatic The new flag value
*/
public void setClearReferencesStatic(boolean clearReferencesStatic) {
this.clearReferencesStatic = clearReferencesStatic;
}
/**
* Return the clearReferencesStopThreads flag for this Context.
*/
public boolean getClearReferencesStopThreads() {
return (this.clearReferencesStopThreads);
}
/**
* Set the clearReferencesStopThreads feature for this Context.
*
* @param clearReferencesStopThreads The new flag value
*/
public void setClearReferencesStopThreads(
boolean clearReferencesStopThreads) {
this.clearReferencesStopThreads = clearReferencesStopThreads;
}
/**
* Return the clearReferencesStopTimerThreads flag for this Context.
*/
public boolean getClearReferencesStopTimerThreads() {
return (this.clearReferencesStopTimerThreads);
}
/**
* Set the clearReferencesStopTimerThreads feature for this Context.
*
* @param clearReferencesStopTimerThreads The new flag value
*/
public void setClearReferencesStopTimerThreads(
boolean clearReferencesStopTimerThreads) {
this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads;
}
/**
* Return the clearReferencesLogFactoryRelease flag for this Context.
*/
public boolean getClearReferencesLogFactoryRelease() {
return (this.clearReferencesLogFactoryRelease);
}
/**
* Set the clearReferencesLogFactoryRelease feature for this Context.
*
* @param clearReferencesLogFactoryRelease The new flag value
*/
public void setClearReferencesLogFactoryRelease(
boolean clearReferencesLogFactoryRelease) {
this.clearReferencesLogFactoryRelease =
clearReferencesLogFactoryRelease;
}
/**
* Return the clearReferencesHttpClientKeepAliveThread flag for this
* Context.
*/
public boolean getClearReferencesHttpClientKeepAliveThread() {
return (this.clearReferencesHttpClientKeepAliveThread);
}
/**
* Set the clearReferencesHttpClientKeepAliveThread feature for this
* Context.
*
* @param clearReferencesHttpClientKeepAliveThread The new flag value
*/
public void setClearReferencesHttpClientKeepAliveThread(
boolean clearReferencesHttpClientKeepAliveThread) {
this.clearReferencesHttpClientKeepAliveThread =
clearReferencesHttpClientKeepAliveThread;
}
// ------------------------------------------------------- Reloader Methods
/**
* Adds the specified class file transformer to this class loader. The
* transformer will then be able to modify the bytecode of any classes
* loaded by this class loader after the invocation of this method.
*
* @param transformer The transformer to add to the class loader
*/
@Override
public void addTransformer(ClassFileTransformer transformer) {
if (transformer == null) {
throw new IllegalArgumentException(sm.getString(
"webappClassLoader.addTransformer.illegalArgument", getContextName()));
}
if (this.transformers.contains(transformer)) {
// if the same instance of this transformer was already added, bail out
log.warn(sm.getString("webappClassLoader.addTransformer.duplicate",
transformer, getContextName()));
return;
}
this.transformers.add(transformer);
log.info(sm.getString("webappClassLoader.addTransformer", transformer, getContextName()));
}
/**
* Removes the specified class file transformer from this class loader.
* It will no longer be able to modify the byte code of any classes
* loaded by the class loader after the invocation of this method.
* However, any classes already modified by this transformer will
* remain transformed.
*
* @param transformer The transformer to remove
*/
@Override
public void removeTransformer(ClassFileTransformer transformer) {
if (transformer == null) {
return;
}
if (this.transformers.remove(transformer)) {
log.info(sm.getString("webappClassLoader.removeTransformer",
transformer, getContextName()));
return;
}
}
/**
* Returns a copy of this class loader without any class file
* transformers. This is a tool often used by Java Persistence API
* providers to inspect entity classes in the absence of any
* instrumentation, something that can't be guaranteed within the
* context of a {@link ClassFileTransformer}'s
* {@link ClassFileTransformer#transform(ClassLoader, String, Class,
* ProtectionDomain, byte[]) transform} method.
* <p>
* The returned class loader's resource cache will have been cleared
* so that classes already instrumented will not be retained or
* returned.
*
* @return the transformer-free copy of this class loader.
*/
@Override
public WebappClassLoader copyWithoutTransformers() {
WebappClassLoader loader = new WebappClassLoader(this.parent);
loader.antiJARLocking = this.antiJARLocking;
loader.resources = this.resources;
loader.delegate = this.delegate;
loader.lastJarAccessed = this.lastJarAccessed;
loader.repositoryPath = this.repositoryPath;
loader.repository = this.repository;
loader.jarPath = this.jarPath;
loader.loaderDir = this.loaderDir;
loader.canonicalLoaderDir = this.canonicalLoaderDir;
loader.started = this.started;
loader.needConvert = this.needConvert;
loader.clearReferencesStatic = this.clearReferencesStatic;
loader.clearReferencesStopThreads = this.clearReferencesStopThreads;
loader.clearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads;
loader.clearReferencesLogFactoryRelease = this.clearReferencesLogFactoryRelease;
loader.clearReferencesHttpClientKeepAliveThread = this.clearReferencesHttpClientKeepAliveThread;
loader.repositoryURLs = this.repositoryURLs.clone();
loader.jarFiles = this.jarFiles.clone();
loader.jarRealFiles = this.jarRealFiles.clone();
loader.jarNames = this.jarNames.clone();
loader.lastModifiedDates = this.lastModifiedDates.clone();
loader.paths = this.paths.clone();
loader.notFoundResources.putAll(this.notFoundResources);
loader.permissionList.addAll(this.permissionList);
loader.loaderPC.putAll(this.loaderPC);
return loader;
}
/**
* Set the place this ClassLoader can look for classes to be loaded.
*
* @param path Path of a source of classes to be loaded, such as a
* directory pathname, a JAR file pathname, or a ZIP file pathname
*
* @exception IllegalArgumentException if the specified repository is
* invalid or does not exist
*/
synchronized void setRepository(String path, WebResource repository) {
if (path == null)
return;
if (log.isDebugEnabled())
log.debug("addRepository(" + path + ")");
this.repositoryPath = path;
this.repository = repository;
}
synchronized void addJar(String jar, JarFile jarFile, File file)
throws IOException {
if (jar == null)
return;
if (jarFile == null)
return;
if (file == null)
return;
if (log.isDebugEnabled())
log.debug("addJar(" + jar + ")");
int i;
if ((jarPath != null) && (jar.startsWith(jarPath))) {
String jarName = jar.substring(jarPath.length());
while (jarName.startsWith("/"))
jarName = jarName.substring(1);
String[] result = new String[jarNames.length + 1];
for (i = 0; i < jarNames.length; i++) {
result[i] = jarNames[i];
}
result[jarNames.length] = jarName;
jarNames = result;
}
// Register the JAR for tracking
long lastModified = resources.getResource(jar).getLastModified();
String[] result = new String[paths.length + 1];
for (i = 0; i < paths.length; i++) {
result[i] = paths[i];
}
result[paths.length] = jar;
paths = result;
long[] result3 = new long[lastModifiedDates.length + 1];
for (i = 0; i < lastModifiedDates.length; i++) {
result3[i] = lastModifiedDates[i];
}
result3[lastModifiedDates.length] = lastModified;
lastModifiedDates = result3;
// If the JAR currently contains invalid classes, don't actually use it
// for classloading
if (!validateJarFile(file))
return;
JarFile[] result2 = new JarFile[jarFiles.length + 1];
for (i = 0; i < jarFiles.length; i++) {
result2[i] = jarFiles[i];
}
result2[jarFiles.length] = jarFile;
jarFiles = result2;
// Add the file to the list
File[] result4 = new File[jarRealFiles.length + 1];
for (i = 0; i < jarRealFiles.length; i++) {
result4[i] = jarRealFiles[i];
}
result4[jarRealFiles.length] = file;
jarRealFiles = result4;
}
/**
* Have one or more classes or resources been modified so that a reload
* is appropriate?
*/
public boolean modified() {
if (log.isDebugEnabled())
log.debug("modified()");
// Checking for modified loaded resources
int length = paths.length;
// A rare race condition can occur in the updates of the two arrays
// It's totally ok if the latest class added is not checked (it will
// be checked the next time
int length2 = lastModifiedDates.length;
if (length > length2)
length = length2;
for (int i = 0; i < length; i++) {
long lastModified =
resources.getResource(paths[i]).getLastModified();
if (lastModified != lastModifiedDates[i]) {
if( log.isDebugEnabled() )
log.debug(" Resource '" + paths[i]
+ "' was modified; Date is now: "
+ new java.util.Date(lastModified) + " Was: "
+ new java.util.Date(lastModifiedDates[i]));
return true;
}
}
length = jarNames.length;
// Check if JARs have been added or removed
if (getJarPath() != null) {
WebResource[] jars = resources.listResources(getJarPath());
int i = 0;
int j = 0;
for (; j < jars.length && i < length; j++) {
// Ignore non JARs present in the lib folder
String name = jars[j].getName();
if (!name.endsWith(".jar"))
continue;
if (!name.equals(jarNames[i])) {
// Missing JAR
log.info(" One or more JARs have been added : '"
+ name + "'");
return true;
}
i++;
}
if (j < jars.length ) {
for (; j < jars.length; j++) {
// Additional non-JAR files are allowed
if (jars[j].getName().endsWith(".jar")) {
// There was more JARs
log.info(" Additional JARs have been added");
return true;
}
}
} else if (i < jarNames.length) {
// There was less JARs
log.info(" One or more JARs have been removed");
return (true);
}
}
// No classes have been modified
return false;
}
/**
* Render a String representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("WebappClassLoader\r\n");
sb.append(" context: ");
sb.append(getContextName());
sb.append("\r\n");
sb.append(" delegate: ");
sb.append(delegate);
sb.append("\r\n");
sb.append(" repositoryPath: ");
sb.append(repositoryPath);
sb.append("\r\n");
if (this.parent != null) {
sb.append("----------> Parent Classloader:\r\n");
sb.append(this.parent.toString());
sb.append("\r\n");
}
if (this.transformers.size() > 0) {
sb.append("----------> Class file transformers:\r\n");
for (ClassFileTransformer transformer : this.transformers) {
sb.append(transformer).append("\r\n");
}
}
return (sb.toString());
}
// ---------------------------------------------------- ClassLoader Methods
/**
* Expose this method for use by the unit tests.
*/
protected final Class<?> doDefineClass(String name, byte[] b, int off, int len,
ProtectionDomain protectionDomain) {
return super.defineClass(name, b, off, len, protectionDomain);
}
/**
* Find the specified class in our local repositories, if possible. If
* not found, throw <code>ClassNotFoundException</code>.
*
* @param name Name of the class to be loaded
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
if (log.isDebugEnabled())
log.debug(" findClass(" + name + ")");
// Cannot load anything from local repositories if class loader is stopped
if (!started) {
throw new ClassNotFoundException(name);
}
// (1) Permission to define this class when using a SecurityManager
if (securityManager != null) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
if (log.isTraceEnabled())
log.trace(" securityManager.checkPackageDefinition");
securityManager.checkPackageDefinition(name.substring(0,i));
} catch (Exception se) {
if (log.isTraceEnabled())
log.trace(" -->Exception-->ClassNotFoundException", se);
throw new ClassNotFoundException(name, se);
}
}
}
// Ask our superclass to locate this class, if possible
// (throws ClassNotFoundException if it is not found)
Class<?> clazz = null;
try {
if (log.isTraceEnabled())
log.trace(" findClassInternal(" + name + ")");
try {
clazz = findClassInternal(name);
} catch(ClassNotFoundException cnfe) {
if (log.isDebugEnabled())
log.debug(" --> Returning ClassNotFoundException");
throw cnfe;
} catch(AccessControlException ace) {
log.warn("WebappClassLoader.findClassInternal(" + name
+ ") security exception: " + ace.getMessage(), ace);
throw new ClassNotFoundException(name, ace);
} catch (RuntimeException e) {
if (log.isTraceEnabled())
log.trace(" -->RuntimeException Rethrown", e);
throw e;
}
} catch (ClassNotFoundException e) {
if (log.isTraceEnabled())
log.trace(" --> Passing on ClassNotFoundException");
throw e;
}
// Return the class we have located
if (log.isTraceEnabled())
log.debug(" Returning class " + clazz);
if (log.isTraceEnabled()) {
ClassLoader cl;
if (Globals.IS_SECURITY_ENABLED){
cl = AccessController.doPrivileged(
new PrivilegedGetClassLoader(clazz));
} else {
cl = clazz.getClassLoader();
}
log.debug(" Loaded by " + cl.toString());
}
return (clazz);
}
/**
* Find the specified resource in our local repository, and return a
* <code>URL</code> referring to it, or <code>null</code> if this resource
* cannot be found.
*
* @param name Name of the resource to be found
*/
@Override
public URL findResource(final String name) {
if (log.isDebugEnabled())
log.debug(" findResource(" + name + ")");
URL url = null;
ResourceEntry entry = resourceEntries.get(name);
if (entry == null) {
if (securityManager != null) {
PrivilegedAction<ResourceEntry> dp =
new PrivilegedFindResourceByName(name, name);
entry = AccessController.doPrivileged(dp);
} else {
entry = findResourceInternal(name, name);
}
}
if (entry != null) {
url = entry.source;
}
if (log.isDebugEnabled()) {
if (url != null)
log.debug(" --> Returning '" + url.toString() + "'");
else
log.debug(" --> Resource not found, returning null");
}
return (url);
}
/**
* Return an enumeration of <code>URLs</code> representing all of the
* resources with the given name. If no resources with this name are
* found, return an empty enumeration.
*
* @param name Name of the resources to be found
*
* @exception IOException if an input/output error occurs
*/
@Override
public Enumeration<URL> findResources(String name) throws IOException {
if (log.isDebugEnabled())
log.debug(" findResources(" + name + ")");
LinkedHashSet<URL> result = new LinkedHashSet<>();
int jarFilesLength = jarFiles.length;
if (repositoryPath != null) {
// Looking at the repository
WebResource[] webResources = resources.getResources(repositoryPath + name);
for (WebResource webResource : webResources) {
if (webResource.exists()) {
result.add(webResource.getURL());
}
}
}
// Looking at the JAR files
synchronized (jarFiles) {
if (openJARs()) {
for (int i = 0; i < jarFilesLength; i++) {
JarEntry jarEntry = jarFiles[i].getJarEntry(name);
if (jarEntry != null) {
try {
String jarFakeUrl = getURI(jarRealFiles[i]).toString();
jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name;
result.add(new URL(jarFakeUrl));
} catch (MalformedURLException e) {
// Ignore
}
}
}
}
}
return Collections.enumeration(result);
}
/**
* Find the resource with the given name. A resource is some data
* (images, audio, text, etc.) that can be accessed by class code in a
* way that is independent of the location of the code. The name of a
* resource is a "/"-separated path name that identifies the resource.
* If the resource cannot be found, return <code>null</code>.
* <p>
* This method searches according to the following algorithm, returning
* as soon as it finds the appropriate URL. If the resource cannot be
* found, returns <code>null</code>.
* <ul>
* <li>If the <code>delegate</code> property is set to <code>true</code>,
* call the <code>getResource()</code> method of the parent class
* loader, if any.</li>
* <li>Call <code>findResource()</code> to find this resource in our
* locally defined repositories.</li>
* <li>Call the <code>getResource()</code> method of the parent class
* loader, if any.</li>
* </ul>
*
* @param name Name of the resource to return a URL for
*/
@Override
public URL getResource(String name) {
if (log.isDebugEnabled())
log.debug("getResource(" + name + ")");
URL url = null;
// (1) Delegate to parent if requested
if (delegate) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
url = loader.getResource(name);
if (url != null) {
if (log.isDebugEnabled())
log.debug(" --> Returning '" + url.toString() + "'");
return (url);
}
}
// (2) Search local repositories
url = findResource(name);
if (url != null) {
// Locating the repository for special handling in the case
// of a JAR
if (antiJARLocking) {
ResourceEntry entry = resourceEntries.get(name);
try {
String repository = entry.codeBase.toString();
if ((repository.endsWith(".jar"))
&& (!(name.endsWith(CLASS_FILE_SUFFIX)))) {
// Copy binary content to the work directory if not present
File resourceFile = new File(loaderDir, name);
url = getURI(resourceFile);
}
} catch (Exception e) {
// Ignore
}
}
if (log.isDebugEnabled())
log.debug(" --> Returning '" + url.toString() + "'");
return (url);
}
// (3) Delegate to parent unconditionally if not already attempted
if( !delegate ) {
ClassLoader loader = parent;
if (loader == null)
loader = system;
url = loader.getResource(name);
if (url != null) {
if (log.isDebugEnabled())
log.debug(" --> Returning '" + url.toString() + "'");
return (url);
}
}
// (4) Resource was not found
if (log.isDebugEnabled())
log.debug(" --> Resource not found, returning null");
return (null);
}
/**
* Find the resource with the given name, and return an input stream
* that can be used for reading it. The search order is as described
* for <code>getResource()</code>, after checking to see if the resource
* data has been previously cached. If the resource cannot be found,
* return <code>null</code>.
*
* @param name Name of the resource to return an input stream for
*/
@Override
public InputStream getResourceAsStream(String name) {
if (log.isDebugEnabled())
log.debug("getResourceAsStream(" + name + ")");
InputStream stream = null;
// (0) Check for a cached copy of this resource
stream = findLoadedResource(name);
if (stream != null) {
if (log.isDebugEnabled())
log.debug(" --> Returning stream from cache");
return (stream);
}
// (1) Delegate to parent if requested
if (delegate) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
stream = loader.getResourceAsStream(name);
if (stream != null) {
// FIXME - cache???
if (log.isDebugEnabled())
log.debug(" --> Returning stream from parent");
return (stream);
}
}
// (2) Search local repositories
if (log.isDebugEnabled())
log.debug(" Searching local repositories");
URL url = findResource(name);
if (url != null) {
// FIXME - cache???
if (log.isDebugEnabled())
log.debug(" --> Returning stream from local");
stream = findLoadedResource(name);
if (stream != null)
return (stream);
}
// (3) Delegate to parent unconditionally
if (!delegate) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader unconditionally " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
stream = loader.getResourceAsStream(name);
if (stream != null) {
// FIXME - cache???
if (log.isDebugEnabled())
log.debug(" --> Returning stream from parent");
return (stream);
}
}
// (4) Resource was not found
if (log.isDebugEnabled())
log.debug(" --> Resource not found, returning null");
return (null);
}
/**
* Load the class with the specified name. This method searches for
* classes in the same manner as <code>loadClass(String, boolean)</code>
* with <code>false</code> as the second argument.
*
* @param name Name of the class to be loaded
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return (loadClass(name, false));
}
/**
* Load the class with the specified name, searching using the following
* algorithm until it finds and returns the class. If the class cannot
* be found, returns <code>ClassNotFoundException</code>.
* <ul>
* <li>Call <code>findLoadedClass(String)</code> to check if the
* class has already been loaded. If it has, the same
* <code>Class</code> object is returned.</li>
* <li>If the <code>delegate</code> property is set to <code>true</code>,
* call the <code>loadClass()</code> method of the parent class
* loader, if any.</li>
* <li>Call <code>findClass()</code> to find this class in our locally
* defined repositories.</li>
* <li>Call the <code>loadClass()</code> method of our parent
* class loader, if any.</li>
* </ul>
* If the class was found using the above steps, and the
* <code>resolve</code> flag is <code>true</code>, this method will then
* call <code>resolveClass(Class)</code> on the resulting Class object.
*
* @param name Name of the class to be loaded
* @param resolve If <code>true</code> then resolve the class
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (log.isDebugEnabled())
log.debug("loadClass(" + name + ", " + resolve + ")");
Class<?> clazz = null;
// Log access to stopped classloader
if (!started) {
try {
throw new IllegalStateException();
} catch (IllegalStateException e) {
log.info(sm.getString("webappClassLoader.stopped", name), e);
}
}
// (0) Check our previously loaded local class cache
clazz = findLoadedClass0(name);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Returning class from cache");
if (resolve)
resolveClass(clazz);
return (clazz);
}
// (0.1) Check our previously loaded class cache
clazz = findLoadedClass(name);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Returning class from cache");
if (resolve)
resolveClass(clazz);
return (clazz);
}
// (0.2) Try loading the class with the system class loader, to prevent
// the webapp from overriding J2SE classes
try {
clazz = system.loadClass(name);
if (clazz != null) {
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
// (0.5) Permission to access this class when using a SecurityManager
if (securityManager != null) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
securityManager.checkPackageAccess(name.substring(0,i));
} catch (SecurityException se) {
String error = "Security Violation, attempt to use " +
"Restricted Class: " + name;
log.info(error, se);
throw new ClassNotFoundException(error, se);
}
}
}
boolean delegateLoad = delegate || filter(name);
// (1) Delegate to our parent if requested
if (delegateLoad) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader1 " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
try {
clazz = Class.forName(name, false, loader);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Loading class from parent");
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
}
// (2) Search local repositories
if (log.isDebugEnabled())
log.debug(" Searching local repositories");
try {
clazz = findClass(name);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Loading class from local repository");
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
// (3) Delegate to parent unconditionally
if (!delegateLoad) {
if (log.isDebugEnabled())
log.debug(" Delegating to parent classloader at end: " + parent);
ClassLoader loader = parent;
if (loader == null)
loader = system;
try {
clazz = Class.forName(name, false, loader);
if (clazz != null) {
if (log.isDebugEnabled())
log.debug(" Loading class from parent");
if (resolve)
resolveClass(clazz);
return (clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
}
throw new ClassNotFoundException(name);
}
/**
* Get the Permissions for a CodeSource. If this instance
* of WebappClassLoader is for a web application context,
* add read FilePermission or JndiPermissions for the base
* directory (if unpacked),
* the context URL, and jar file resources.
*
* @param codeSource where the code was loaded from
* @return PermissionCollection for CodeSource
*/
@Override
protected PermissionCollection getPermissions(CodeSource codeSource) {
String codeUrl = codeSource.getLocation().toString();
PermissionCollection pc;
if ((pc = loaderPC.get(codeUrl)) == null) {
pc = super.getPermissions(codeSource);
if (pc != null) {
Iterator<Permission> perms = permissionList.iterator();
while (perms.hasNext()) {
Permission p = perms.next();
pc.add(p);
}
loaderPC.put(codeUrl,pc);
}
}
return (pc);
}
/**
* Returns the search path of URLs for loading classes and resources.
* This includes the original list of URLs specified to the constructor,
* along with any URLs subsequently appended by the addURL() method.
* @return the search path of URLs for loading classes and resources.
*/
@Override
public URL[] getURLs() {
if (repositoryURLs != null) {
return repositoryURLs.clone();
}
int resultLength;
if (repository == null) {
resultLength = jarRealFiles.length;
} else {
resultLength = jarRealFiles.length + 1;
}
int off = 0;
try {
URL[] urls = new URL[resultLength];
if (repository != null) {
urls[off ++] = repository.getURL();
}
for (File jarRealFile : jarRealFiles) {
urls[off++] = getURI(jarRealFile);
}
repositoryURLs = urls;
} catch (MalformedURLException e) {
repositoryURLs = new URL[0];
}
return repositoryURLs.clone();
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Add a lifecycle event listener to this component.
*
* @param listener The listener to add
*/
@Override
public void addLifecycleListener(LifecycleListener listener) {
// NOOP
}
/**
* Get the lifecycle listeners associated with this lifecycle. If this
* Lifecycle has no listeners registered, a zero-length array is returned.
*/
@Override
public LifecycleListener[] findLifecycleListeners() {
return new LifecycleListener[0];
}
/**
* Remove a lifecycle event listener from this component.
*
* @param listener The listener to remove
*/
@Override
public void removeLifecycleListener(LifecycleListener listener) {
// NOOP
}
/**
* Obtain the current state of the source component.
*
* @return The current state of the source component.
*/
@Override
public LifecycleState getState() {
return LifecycleState.NEW;
}
/**
* {@inheritDoc}
*/
@Override
public String getStateName() {
return getState().toString();
}
@Override
public void init() {
// NOOP
}
/**
* Start the class loader.
*
* @exception LifecycleException if a lifecycle error occurs
*/
@Override
public void start() throws LifecycleException {
started = true;
String encoding = null;
try {
encoding = System.getProperty("file.encoding");
} catch (SecurityException e) {
return;
}
if (encoding.indexOf("EBCDIC")!=-1) {
needConvert = true;
}
}
public boolean isStarted() {
return started;
}
/**
* Stop the class loader.
*
* @exception LifecycleException if a lifecycle error occurs
*/
@Override
public void stop() throws LifecycleException {
// Clearing references should be done before setting started to
// false, due to possible side effects
clearReferences();
started = false;
int length = jarFiles.length;
for (int i = 0; i < length; i++) {
try {
if (jarFiles[i] != null) {
jarFiles[i].close();
}
} catch (IOException e) {
// Ignore
}
jarFiles[i] = null;
}
notFoundResources.clear();
resourceEntries.clear();
resources = null;
repositoryPath = null;
repositoryURLs = null;
repository = null;
jarFiles = null;
jarRealFiles = null;
jarPath = null;
jarNames = null;
lastModifiedDates = null;
paths = null;
parent = null;
permissionList.clear();
loaderPC.clear();
if (loaderDir != null) {
deleteDir(loaderDir);
}
}
@Override
public void destroy() {
// NOOP
}
/**
* Used to periodically signal to the classloader to release
* JAR resources.
*/
public void closeJARs(boolean force) {
if (jarFiles.length > 0) {
synchronized (jarFiles) {
if (force || (System.currentTimeMillis()
> (lastJarAccessed + 90000))) {
for (int i = 0; i < jarFiles.length; i++) {
try {
if (jarFiles[i] != null) {
jarFiles[i].close();
jarFiles[i] = null;
}
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("Failed to close JAR", e);
}
}
}
}
}
}
}
// ------------------------------------------------------ Protected Methods
/**
* Clear references.
*/
protected void clearReferences() {
// De-register any remaining JDBC drivers
clearReferencesJdbc();
// Stop any threads the web application started
clearReferencesThreads();
// Check for leaks triggered by ThreadLocals loaded by this class loader
checkThreadLocalsForLeaks();
// Clear RMI Targets loaded by this class loader
clearReferencesRmiTargets();
// Null out any static or final fields from loaded classes,
// as a workaround for apparent garbage collection bugs
if (clearReferencesStatic) {
clearReferencesStaticFinal();
}
// Clear the IntrospectionUtils cache.
IntrospectionUtils.clear();
// Clear the classloader reference in common-logging
if (clearReferencesLogFactoryRelease) {
org.apache.juli.logging.LogFactory.release(this);
}
// Clear the resource bundle cache
// This shouldn't be necessary, the cache uses weak references but
// it has caused leaks. Oddly, using the leak detection code in
// standard host allows the class loader to be GC'd. This has been seen
// on Sun but not IBM JREs. Maybe a bug in Sun's GC impl?
clearReferencesResourceBundles();
// Clear the classloader reference in the VM's bean introspector
java.beans.Introspector.flushCaches();
// Clear any custom URLStreamHandlers
TomcatURLStreamHandlerFactory.release(this);
}
/**
* Deregister any JDBC drivers registered by the webapp that the webapp
* forgot. This is made unnecessary complex because a) DriverManager
* checks the class loader of the calling class (it would be much easier
* if it checked the context class loader) b) using reflection would
* create a dependency on the DriverManager implementation which can,
* and has, changed.
*
* We can't just create an instance of JdbcLeakPrevention as it will be
* loaded by the common class loader (since it's .class file is in the
* $CATALINA_HOME/lib directory). This would fail DriverManager's check
* on the class loader of the calling class. So, we load the bytes via
* our parent class loader but define the class with this class loader
* so the JdbcLeakPrevention looks like a webapp class to the
* DriverManager.
*
* If only apps cleaned up after themselves...
*/
private final void clearReferencesJdbc() {
InputStream is = getResourceAsStream(
"org/apache/catalina/loader/JdbcLeakPrevention.class");
// We know roughly how big the class will be (~ 1K) so allow 2k as a
// starting point
byte[] classBytes = new byte[2048];
int offset = 0;
try {
int read = is.read(classBytes, offset, classBytes.length-offset);
while (read > -1) {
offset += read;
if (offset == classBytes.length) {
// Buffer full - double size
byte[] tmp = new byte[classBytes.length * 2];
System.arraycopy(classBytes, 0, tmp, 0, classBytes.length);
classBytes = tmp;
}
read = is.read(classBytes, offset, classBytes.length-offset);
}
Class<?> lpClass =
defineClass("org.apache.catalina.loader.JdbcLeakPrevention",
classBytes, 0, offset, this.getClass().getProtectionDomain());
Object obj = lpClass.newInstance();
@SuppressWarnings("unchecked")
List<String> driverNames = (List<String>) obj.getClass().getMethod(
"clearJdbcDriverRegistrations").invoke(obj);
for (String name : driverNames) {
log.error(sm.getString("webappClassLoader.clearJdbc",
getContextName(), name));
}
} catch (Exception e) {
// So many things to go wrong above...
Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString(
"webappClassLoader.jdbcRemoveFailed", getContextName()), t);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
log.warn(sm.getString(
"webappClassLoader.jdbcRemoveStreamError",
getContextName()), ioe);
}
}
}
}
private final void clearReferencesStaticFinal() {
@SuppressWarnings("unchecked")
Collection<ResourceEntry> values =
((HashMap<String,ResourceEntry>) resourceEntries.clone()).values();
Iterator<ResourceEntry> loadedClasses = values.iterator();
//
// walk through all loaded class to trigger initialization for
// any uninitialized classes, otherwise initialization of
// one class may call a previously cleared class.
while(loadedClasses.hasNext()) {
ResourceEntry entry = loadedClasses.next();
if (entry.loadedClass != null) {
Class<?> clazz = entry.loadedClass;
try {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if(Modifier.isStatic(fields[i].getModifiers())) {
fields[i].get(null);
break;
}
}
} catch(Throwable t) {
// Ignore
}
}
}
loadedClasses = values.iterator();
while (loadedClasses.hasNext()) {
ResourceEntry entry = loadedClasses.next();
if (entry.loadedClass != null) {
Class<?> clazz = entry.loadedClass;
try {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int mods = field.getModifiers();
if (field.getType().isPrimitive()
|| (field.getName().indexOf("$") != -1)) {
continue;
}
if (Modifier.isStatic(mods)) {
try {
field.setAccessible(true);
if (Modifier.isFinal(mods)) {
if (!((field.getType().getName().startsWith("java."))
|| (field.getType().getName().startsWith("javax.")))) {
nullInstance(field.get(null));
}
} else {
field.set(null, null);
if (log.isDebugEnabled()) {
log.debug("Set field " + field.getName()
+ " to null in class " + clazz.getName());
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug("Could not set field " + field.getName()
+ " to null in class " + clazz.getName(), t);
}
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug("Could not clean fields for class " + clazz.getName(), t);
}
}
}
}
}
private void nullInstance(Object instance) {
if (instance == null) {
return;
}
Field[] fields = instance.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int mods = field.getModifiers();
if (field.getType().isPrimitive()
|| (field.getName().indexOf("$") != -1)) {
continue;
}
try {
field.setAccessible(true);
if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
// Doing something recursively is too risky
continue;
}
Object value = field.get(instance);
if (null != value) {
Class<? extends Object> valueClass = value.getClass();
if (!loadedByThisOrChild(valueClass)) {
if (log.isDebugEnabled()) {
log.debug("Not setting field " + field.getName() +
" to null in object of class " +
instance.getClass().getName() +
" because the referenced object was of type " +
valueClass.getName() +
" which was not loaded by this WebappClassLoader.");
}
} else {
field.set(instance, null);
if (log.isDebugEnabled()) {
log.debug("Set field " + field.getName()
+ " to null in class " + instance.getClass().getName());
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug("Could not set field " + field.getName()
+ " to null in object instance of class "
+ instance.getClass().getName(), t);
}
}
}
}
@SuppressWarnings("deprecation") // thread.stop()
private void clearReferencesThreads() {
Thread[] threads = getThreads();
List<Thread> executorThreadsToStop = new ArrayList<>();
// Iterate over the set of threads
for (Thread thread : threads) {
if (thread != null) {
ClassLoader ccl = thread.getContextClassLoader();
if (ccl == this) {
// Don't warn about this thread
if (thread == Thread.currentThread()) {
continue;
}
// JVM controlled threads
ThreadGroup tg = thread.getThreadGroup();
if (tg != null &&
JVM_THREAD_GROUP_NAMES.contains(tg.getName())) {
// HttpClient keep-alive threads
if (clearReferencesHttpClientKeepAliveThread &&
thread.getName().equals("Keep-Alive-Timer")) {
thread.setContextClassLoader(parent);
log.debug(sm.getString(
"webappClassLoader.checkThreadsHttpClient"));
}
// Don't warn about remaining JVM controlled threads
continue;
}
// Skip threads that have already died
if (!thread.isAlive()) {
continue;
}
// TimerThread can be stopped safely so treat separately
// "java.util.TimerThread" in Sun/Oracle JDK
// "java.util.Timer$TimerImpl" in Apache Harmony and in IBM JDK
if (thread.getClass().getName().startsWith("java.util.Timer") &&
clearReferencesStopTimerThreads) {
clearReferencesStopTimerThread(thread);
continue;
}
if (isRequestThread(thread)) {
log.error(sm.getString("webappClassLoader.warnRequestThread",
getContextName(), thread.getName()));
} else {
log.error(sm.getString("webappClassLoader.warnThread",
getContextName(), thread.getName()));
}
// Don't try an stop the threads unless explicitly
// configured to do so
if (!clearReferencesStopThreads) {
continue;
}
// If the thread has been started via an executor, try
// shutting down the executor
boolean usingExecutor = false;
try {
// Runnable wrapped by Thread
// "target" in Sun/Oracle JDK
// "runnable" in IBM JDK
// "action" in Apache Harmony
Object target = null;
for (String fieldName : new String[] { "target",
"runnable", "action" }) {
try {
Field targetField = thread.getClass()
.getDeclaredField(fieldName);
targetField.setAccessible(true);
target = targetField.get(thread);
break;
} catch (NoSuchFieldException nfe) {
continue;
}
}
// "java.util.concurrent" code is in public domain,
// so all implementations are similar
if (target != null &&
target.getClass().getCanonicalName() != null
&& target.getClass().getCanonicalName().equals(
"java.util.concurrent.ThreadPoolExecutor.Worker")) {
Field executorField =
target.getClass().getDeclaredField("this$0");
executorField.setAccessible(true);
Object executor = executorField.get(target);
if (executor instanceof ThreadPoolExecutor) {
((ThreadPoolExecutor) executor).shutdownNow();
usingExecutor = true;
}
}
} catch (SecurityException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
} catch (NoSuchFieldException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
} catch (IllegalArgumentException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
} catch (IllegalAccessException e) {
log.warn(sm.getString(
"webappClassLoader.stopThreadFail",
thread.getName(), getContextName()), e);
}
if (usingExecutor) {
// Executor may take a short time to stop all the
// threads. Make a note of threads that should be
// stopped and check them at the end of the method.
executorThreadsToStop.add(thread);
} else {
// This method is deprecated and for good reason. This
// is very risky code but is the only option at this
// point. A *very* good reason for apps to do this
// clean-up themselves.
thread.stop();
}
}
}
}
// If thread stopping is enabled, executor threads should have been
// stopped above when the executor was shut down but that depends on the
// thread correctly handling the interrupt. Give all the executor
// threads a few seconds shutdown and if they are still running
// Give threads up to 2 seconds to shutdown
int count = 0;
for (Thread t : executorThreadsToStop) {
while (t.isAlive() && count < 100) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// Quit the while loop
break;
}
count++;
}
if (t.isAlive()) {
// This method is deprecated and for good reason. This is
// very risky code but is the only option at this point.
// A *very* good reason for apps to do this clean-up
// themselves.
t.stop();
}
}
}
/*
* Look at a threads stack trace to see if it is a request thread or not. It
* isn't perfect, but it should be good-enough for most cases.
*/
private boolean isRequestThread(Thread thread) {
StackTraceElement[] elements = thread.getStackTrace();
if (elements == null || elements.length == 0) {
// Must have stopped already. Too late to ignore it. Assume not a
// request processing thread.
return false;
}
// Step through the methods in reverse order looking for calls to any
// CoyoteAdapter method. All request threads will have this unless
// Tomcat has been heavily modified - in which case there isn't much we
// can do.
for (int i = 0; i < elements.length; i++) {
StackTraceElement element = elements[elements.length - (i+1)];
if ("org.apache.catalina.connector.CoyoteAdapter".equals(
element.getClassName())) {
return true;
}
}
return false;
}
private void clearReferencesStopTimerThread(Thread thread) {
// Need to get references to:
// in Sun/Oracle JDK:
// - newTasksMayBeScheduled field (in java.util.TimerThread)
// - queue field
// - queue.clear()
// in IBM JDK, Apache Harmony:
// - cancel() method (in java.util.Timer$TimerImpl)
try {
try {
Field newTasksMayBeScheduledField =
thread.getClass().getDeclaredField("newTasksMayBeScheduled");
newTasksMayBeScheduledField.setAccessible(true);
Field queueField = thread.getClass().getDeclaredField("queue");
queueField.setAccessible(true);
Object queue = queueField.get(thread);
Method clearMethod = queue.getClass().getDeclaredMethod("clear");
clearMethod.setAccessible(true);
synchronized(queue) {
newTasksMayBeScheduledField.setBoolean(thread, false);
clearMethod.invoke(queue);
queue.notify(); // In case queue was already empty.
}
}catch (NoSuchFieldException nfe){
Method cancelMethod = thread.getClass().getDeclaredMethod("cancel");
synchronized(thread) {
cancelMethod.setAccessible(true);
cancelMethod.invoke(thread);
}
}
log.error(sm.getString("webappClassLoader.warnTimerThread",
getContextName(), thread.getName()));
} catch (Exception e) {
// So many things to go wrong above...
Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString(
"webappClassLoader.stopTimerThreadFail",
thread.getName(), getContextName()), t);
}
}
private void checkThreadLocalsForLeaks() {
Thread[] threads = getThreads();
try {
// Make the fields in the Thread class that store ThreadLocals
// accessible
Field threadLocalsField =
Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Field inheritableThreadLocalsField =
Thread.class.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocalsField.setAccessible(true);
// Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
// accessible
Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = tlmClass.getDeclaredField("table");
tableField.setAccessible(true);
Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries");
expungeStaleEntriesMethod.setAccessible(true);
for (int i = 0; i < threads.length; i++) {
Object threadLocalMap;
if (threads[i] != null) {
// Clear the first map
threadLocalMap = threadLocalsField.get(threads[i]);
if (null != threadLocalMap){
expungeStaleEntriesMethod.invoke(threadLocalMap);
checkThreadLocalMapForLeaks(threadLocalMap, tableField);
}
// Clear the second map
threadLocalMap =inheritableThreadLocalsField.get(threads[i]);
if (null != threadLocalMap){
expungeStaleEntriesMethod.invoke(threadLocalMap);
checkThreadLocalMapForLeaks(threadLocalMap, tableField);
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaksFail",
getContextName()), t);
}
}
/**
* Analyzes the given thread local map object. Also pass in the field that
* points to the internal table to save re-calculating it on every
* call to this method.
*/
private void checkThreadLocalMapForLeaks(Object map,
Field internalTableField) throws IllegalAccessException,
NoSuchFieldException {
if (map != null) {
Object[] table = (Object[]) internalTableField.get(map);
if (table != null) {
for (int j =0; j < table.length; j++) {
Object obj = table[j];
if (obj != null) {
boolean potentialLeak = false;
// Check the key
Object key = ((Reference<?>) obj).get();
if (this.equals(key) || loadedByThisOrChild(key)) {
potentialLeak = true;
}
// Check the value
Field valueField =
obj.getClass().getDeclaredField("value");
valueField.setAccessible(true);
Object value = valueField.get(obj);
if (this.equals(value) || loadedByThisOrChild(value)) {
potentialLeak = true;
}
if (potentialLeak) {
Object[] args = new Object[5];
args[0] = getContextName();
if (key != null) {
args[1] = getPrettyClassName(key.getClass());
try {
args[2] = key.toString();
} catch (Exception e) {
log.error(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.badKey",
args[1]), e);
args[2] = sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.unknown");
}
}
if (value != null) {
args[3] = getPrettyClassName(value.getClass());
try {
args[4] = value.toString();
} catch (Exception e) {
log.error(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.badValue",
args[3]), e);
args[4] = sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks.unknown");
}
}
if (value == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaksDebug",
args));
}
} else {
log.error(sm.getString(
"webappClassLoader.checkThreadLocalsForLeaks",
args));
}
}
}
}
}
}
}
private String getPrettyClassName(Class<?> clazz) {
String name = clazz.getCanonicalName();
if (name==null){
name = clazz.getName();
}
return name;
}
/**
* @param o object to test, may be null
* @return <code>true</code> if o has been loaded by the current classloader
* or one of its descendants.
*/
private boolean loadedByThisOrChild(Object o) {
if (o == null) {
return false;
}
Class<?> clazz;
if (o instanceof Class) {
clazz = (Class<?>) o;
} else {
clazz = o.getClass();
}
ClassLoader cl = clazz.getClassLoader();
while (cl != null) {
if (cl == this) {
return true;
}
cl = cl.getParent();
}
if (o instanceof Collection<?>) {
Iterator<?> iter = ((Collection<?>) o).iterator();
try {
while (iter.hasNext()) {
Object entry = iter.next();
if (loadedByThisOrChild(entry)) {
return true;
}
}
} catch (ConcurrentModificationException e) {
log.warn(sm.getString(
"webappClassLoader", clazz.getName(), getContextName()),
e);
}
}
return false;
}
/*
* Get the set of current threads as an array.
*/
private Thread[] getThreads() {
// Get the current thread group
ThreadGroup tg = Thread.currentThread().getThreadGroup();
// Find the root thread group
while (tg.getParent() != null) {
tg = tg.getParent();
}
int threadCountGuess = tg.activeCount() + 50;
Thread[] threads = new Thread[threadCountGuess];
int threadCountActual = tg.enumerate(threads);
// Make sure we don't miss any threads
while (threadCountActual == threadCountGuess) {
threadCountGuess *=2;
threads = new Thread[threadCountGuess];
// Note tg.enumerate(Thread[]) silently ignores any threads that
// can't fit into the array
threadCountActual = tg.enumerate(threads);
}
return threads;
}
/**
* This depends on the internals of the Sun JVM so it does everything by
* reflection.
*/
private void clearReferencesRmiTargets() {
try {
// Need access to the ccl field of sun.rmi.transport.Target
Class<?> objectTargetClass =
Class.forName("sun.rmi.transport.Target");
Field cclField = objectTargetClass.getDeclaredField("ccl");
cclField.setAccessible(true);
// Clear the objTable map
Class<?> objectTableClass =
Class.forName("sun.rmi.transport.ObjectTable");
Field objTableField = objectTableClass.getDeclaredField("objTable");
objTableField.setAccessible(true);
Object objTable = objTableField.get(null);
if (objTable == null) {
return;
}
// Iterate over the values in the table
if (objTable instanceof Map<?,?>) {
Iterator<?> iter = ((Map<?,?>) objTable).values().iterator();
while (iter.hasNext()) {
Object obj = iter.next();
Object cclObject = cclField.get(obj);
if (this == cclObject) {
iter.remove();
}
}
}
// Clear the implTable map
Field implTableField = objectTableClass.getDeclaredField("implTable");
implTableField.setAccessible(true);
Object implTable = implTableField.get(null);
if (implTable == null) {
return;
}
// Iterate over the values in the table
if (implTable instanceof Map<?,?>) {
Iterator<?> iter = ((Map<?,?>) implTable).values().iterator();
while (iter.hasNext()) {
Object obj = iter.next();
Object cclObject = cclField.get(obj);
if (this == cclObject) {
iter.remove();
}
}
}
} catch (ClassNotFoundException e) {
log.info(sm.getString("webappClassLoader.clearRmiInfo",
getContextName()), e);
} catch (SecurityException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
} catch (NoSuchFieldException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
} catch (IllegalArgumentException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
} catch (IllegalAccessException e) {
log.warn(sm.getString("webappClassLoader.clearRmiFail",
getContextName()), e);
}
}
/**
* Clear the {@link ResourceBundle} cache of any bundles loaded by this
* class loader or any class loader where this loader is a parent class
* loader. Whilst {@link ResourceBundle#clearCache()} could be used there
* are complications around the
* {@link org.apache.jasper.servlet.JasperLoader} that mean a reflection
* based approach is more likely to be complete.
*
* The ResourceBundle is using WeakReferences so it shouldn't be pinning the
* class loader in memory. However, it is. Therefore clear ou the
* references.
*/
private void clearReferencesResourceBundles() {
// Get a reference to the cache
try {
Field cacheListField =
ResourceBundle.class.getDeclaredField("cacheList");
cacheListField.setAccessible(true);
// Java 6 uses ConcurrentMap
// Java 5 uses SoftCache extends Abstract Map
// So use Map and it *should* work with both
Map<?,?> cacheList = (Map<?,?>) cacheListField.get(null);
// Get the keys (loader references are in the key)
Set<?> keys = cacheList.keySet();
Field loaderRefField = null;
// Iterate over the keys looking at the loader instances
Iterator<?> keysIter = keys.iterator();
int countRemoved = 0;
while (keysIter.hasNext()) {
Object key = keysIter.next();
if (loaderRefField == null) {
loaderRefField =
key.getClass().getDeclaredField("loaderRef");
loaderRefField.setAccessible(true);
}
WeakReference<?> loaderRef =
(WeakReference<?>) loaderRefField.get(key);
ClassLoader loader = (ClassLoader) loaderRef.get();
while (loader != null && loader != this) {
loader = loader.getParent();
}
if (loader != null) {
keysIter.remove();
countRemoved++;
}
}
if (countRemoved > 0 && log.isDebugEnabled()) {
log.debug(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesCount",
Integer.valueOf(countRemoved), getContextName()));
}
} catch (SecurityException e) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
} catch (NoSuchFieldException e) {
if (System.getProperty("java.vendor").startsWith("Sun")) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
} else {
log.debug(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
}
} catch (IllegalArgumentException e) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
} catch (IllegalAccessException e) {
log.error(sm.getString(
"webappClassLoader.clearReferencesResourceBundlesFail",
getContextName()), e);
}
}
/**
* Used to periodically signal to the classloader to release JAR resources.
*/
protected boolean openJARs() {
if (started && (jarFiles.length > 0)) {
lastJarAccessed = System.currentTimeMillis();
if (jarFiles[0] == null) {
for (int i = 0; i < jarFiles.length; i++) {
try {
jarFiles[i] = new JarFile(jarRealFiles[i]);
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("Failed to open JAR", e);
}
return false;
}
}
}
}
return true;
}
/**
* Find specified class in local repositories.
*
* @return the loaded class, or null if the class isn't found
*/
protected Class<?> findClassInternal(String name)
throws ClassNotFoundException {
if (!validate(name))
throw new ClassNotFoundException(name);
String tempPath = name.replace('.', '/');
String classPath = tempPath + CLASS_FILE_SUFFIX;
ResourceEntry entry = null;
if (securityManager != null) {
PrivilegedAction<ResourceEntry> dp =
new PrivilegedFindResourceByName(name, classPath);
entry = AccessController.doPrivileged(dp);
} else {
entry = findResourceInternal(name, classPath);
}
if (entry == null)
throw new ClassNotFoundException(name);
Class<?> clazz = entry.loadedClass;
if (clazz != null)
return clazz;
synchronized (this) {
clazz = entry.loadedClass;
if (clazz != null)
return clazz;
if (entry.binaryContent == null)
throw new ClassNotFoundException(name);
// Looking up the package
String packageName = null;
int pos = name.lastIndexOf('.');
if (pos != -1)
packageName = name.substring(0, pos);
Package pkg = null;
if (packageName != null) {
pkg = getPackage(packageName);
// Define the package (if null)
if (pkg == null) {
try {
if (entry.manifest == null) {
definePackage(packageName, null, null, null, null,
null, null, null);
} else {
definePackage(packageName, entry.manifest,
entry.codeBase);
}
} catch (IllegalArgumentException e) {
// Ignore: normal error due to dual definition of package
}
pkg = getPackage(packageName);
}
}
if (securityManager != null) {
// Checking sealing
if (pkg != null) {
boolean sealCheck = true;
if (pkg.isSealed()) {
sealCheck = pkg.isSealed(entry.codeBase);
} else {
sealCheck = (entry.manifest == null)
|| !isPackageSealed(packageName, entry.manifest);
}
if (!sealCheck)
throw new SecurityException
("Sealing violation loading " + name + " : Package "
+ packageName + " is sealed.");
}
}
try {
clazz = defineClass(name, entry.binaryContent, 0,
entry.binaryContent.length,
new CodeSource(entry.codeBase, entry.certificates));
} catch (UnsupportedClassVersionError ucve) {
throw new UnsupportedClassVersionError(
ucve.getLocalizedMessage() + " " +
sm.getString("webappClassLoader.wrongVersion",
name));
}
entry.loadedClass = clazz;
entry.binaryContent = null;
entry.source = null;
entry.codeBase = null;
entry.manifest = null;
entry.certificates = null;
}
return clazz;
}
/**
* Find specified resource in local repositories.
*
* @return the loaded resource, or null if the resource isn't found
*/
protected ResourceEntry findResourceInternal(final String name, final String path) {
if (!started) {
log.info(sm.getString("webappClassLoader.stopped", name));
return null;
}
if ((name == null) || (path == null))
return null;
ResourceEntry entry = resourceEntries.get(name);
if (entry != null)
return entry;
int contentLength = -1;
InputStream binaryStream = null;
boolean isClassResource = path.endsWith(CLASS_FILE_SUFFIX);
int jarFilesLength = jarFiles.length;
WebResource resource = null;
boolean fileNeedConvert = false;
if (repositoryPath != null) {
String fullPath = repositoryPath + path;
resource = resources.getResource(fullPath);
if (resource.exists()) {
contentLength = (int) resource.getContentLength();
entry = new ResourceEntry();
entry.source = resource.getURL();
entry.codeBase = entry.source;
entry.lastModified = resource.getLastModified();
binaryStream = resource.getInputStream();
if (needConvert) {
if (path.endsWith(".properties")) {
fileNeedConvert = true;
}
}
// Register the full path for modification checking
// Note: Only syncing on a 'constant' object is needed
synchronized (allPermission) {
int j;
long[] result2 =
new long[lastModifiedDates.length + 1];
for (j = 0; j < lastModifiedDates.length; j++) {
result2[j] = lastModifiedDates[j];
}
result2[lastModifiedDates.length] = entry.lastModified;
lastModifiedDates = result2;
String[] result = new String[paths.length + 1];
for (j = 0; j < paths.length; j++) {
result[j] = paths[j];
}
result[paths.length] = fullPath;
paths = result;
}
}
}
if ((entry == null) && (notFoundResources.containsKey(name)))
return null;
JarEntry jarEntry = null;
synchronized (jarFiles) {
try {
if (!openJARs()) {
return null;
}
for (int i = 0; (entry == null) && (i < jarFilesLength); i++) {
jarEntry = jarFiles[i].getJarEntry(path);
if (jarEntry != null) {
entry = new ResourceEntry();
try {
entry.codeBase = getURI(jarRealFiles[i]);
String jarFakeUrl = entry.codeBase.toString();
jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path;
entry.source = new URL(jarFakeUrl);
entry.lastModified = jarRealFiles[i].lastModified();
} catch (MalformedURLException e) {
return null;
}
contentLength = (int) jarEntry.getSize();
try {
entry.manifest = jarFiles[i].getManifest();
binaryStream = jarFiles[i].getInputStream(jarEntry);
} catch (IOException e) {
return null;
}
// Extract resources contained in JAR to the workdir
if (antiJARLocking && !(path.endsWith(CLASS_FILE_SUFFIX))) {
byte[] buf = new byte[1024];
File resourceFile = new File
(loaderDir, jarEntry.getName());
if (!resourceFile.exists()) {
Enumeration<JarEntry> entries =
jarFiles[i].entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry2 = entries.nextElement();
if (!(jarEntry2.isDirectory())
&& (!jarEntry2.getName().endsWith
(CLASS_FILE_SUFFIX))) {
resourceFile = new File
(loaderDir, jarEntry2.getName());
try {
if (!resourceFile.getCanonicalPath().startsWith(
canonicalLoaderDir)) {
throw new IllegalArgumentException(
sm.getString("webappClassLoader.illegalJarPath",
jarEntry2.getName()));
}
} catch (IOException ioe) {
throw new IllegalArgumentException(
sm.getString("webappClassLoader.validationErrorJarPath",
jarEntry2.getName()), ioe);
}
File parentFile = resourceFile.getParentFile();
if (!parentFile.mkdirs() && !parentFile.exists()) {
// Ignore the error (like the IOExceptions below)
}
FileOutputStream os = null;
InputStream is = null;
try {
is = jarFiles[i].getInputStream
(jarEntry2);
os = new FileOutputStream
(resourceFile);
while (true) {
int n = is.read(buf);
if (n <= 0) {
break;
}
os.write(buf, 0, n);
}
resourceFile.setLastModified(
jarEntry2.getTime());
} catch (IOException e) {
// Ignore
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
// Ignore
}
}
}
}
}
}
}
}
if (entry == null) {
synchronized (notFoundResources) {
notFoundResources.put(name, name);
}
return null;
}
/* Only cache the binary content if there is some content
* available and either:
* a) It is a class file since the binary content is only cached
* until the class has been loaded
* or
* b) The file needs conversion to address encoding issues (see
* below)
*
* In all other cases do not cache the content to prevent
* excessive memory usage if large resources are present (see
* https://issues.apache.org/bugzilla/show_bug.cgi?id=53081).
*/
if (binaryStream != null &&
(isClassResource || fileNeedConvert)) {
byte[] binaryContent = new byte[contentLength];
int pos = 0;
try {
while (true) {
int n = binaryStream.read(binaryContent, pos,
binaryContent.length - pos);
if (n <= 0)
break;
pos += n;
}
} catch (IOException e) {
log.error(sm.getString("webappClassLoader.readError", name), e);
return null;
}
if (fileNeedConvert) {
// Workaround for certain files on platforms that use
// EBCDIC encoding, when they are read through FileInputStream.
// See commit message of rev.303915 for details
// http://svn.apache.org/viewvc?view=revision&revision=303915
String str = new String(binaryContent,0,pos);
try {
binaryContent = str.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
return null;
}
}
entry.binaryContent = binaryContent;
// The certificates are only available after the JarEntry
// associated input stream has been fully read
if (jarEntry != null) {
entry.certificates = jarEntry.getCertificates();
}
}
} finally {
if (binaryStream != null) {
try {
binaryStream.close();
} catch (IOException e) { /* Ignore */}
}
}
}
if (isClassResource && entry.binaryContent != null &&
this.transformers.size() > 0) {
// If the resource is a class just being loaded, decorate it
// with any attached transformers
String className = name.endsWith(CLASS_FILE_SUFFIX) ?
name.substring(0, name.length() - CLASS_FILE_SUFFIX.length()) : name;
String internalName = className.replace(".", "/");
for (ClassFileTransformer transformer : this.transformers) {
try {
byte[] transformed = transformer.transform(
this, internalName, null, null, entry.binaryContent
);
if (transformed != null) {
entry.binaryContent = transformed;
}
} catch (IllegalClassFormatException e) {
log.error(sm.getString("webappClassLoader.transformError", name), e);
return null;
}
}
}
// Add the entry in the local resource repository
synchronized (resourceEntries) {
// Ensures that all the threads which may be in a race to load
// a particular class all end up with the same ResourceEntry
// instance
ResourceEntry entry2 = resourceEntries.get(name);
if (entry2 == null) {
resourceEntries.put(name, entry);
} else {
entry = entry2;
}
}
return entry;
}
/**
* Returns true if the specified package name is sealed according to the
* given manifest.
*/
protected boolean isPackageSealed(String name, Manifest man) {
String path = name.replace('.', '/') + '/';
Attributes attr = man.getAttributes(path);
String sealed = null;
if (attr != null) {
sealed = attr.getValue(Name.SEALED);
}
if (sealed == null) {
if ((attr = man.getMainAttributes()) != null) {
sealed = attr.getValue(Name.SEALED);
}
}
return "true".equalsIgnoreCase(sealed);
}
/**
* Finds the resource with the given name if it has previously been
* loaded and cached by this class loader, and return an input stream
* to the resource data. If this resource has not been cached, return
* <code>null</code>.
*
* @param name Name of the resource to return
*/
protected InputStream findLoadedResource(String name) {
ResourceEntry entry = resourceEntries.get(name);
if (entry != null) {
if (entry.binaryContent != null)
return new ByteArrayInputStream(entry.binaryContent);
else {
try {
return entry.source.openStream();
} catch (IOException ioe) {
// Ignore
}
}
}
return null;
}
/**
* Finds the class with the given name if it has previously been
* loaded and cached by this class loader, and return the Class object.
* If this class has not been cached, return <code>null</code>.
*
* @param name Name of the resource to return
*/
protected Class<?> findLoadedClass0(String name) {
ResourceEntry entry = resourceEntries.get(name);
if (entry != null) {
return entry.loadedClass;
}
return (null); // FIXME - findLoadedResource()
}
/**
* Refresh the system policy file, to pick up eventual changes.
*/
protected void refreshPolicy() {
try {
// The policy file may have been modified to adjust
// permissions, so we're reloading it when loading or
// reloading a Context
Policy policy = Policy.getPolicy();
policy.refresh();
} catch (AccessControlException e) {
// Some policy files may restrict this, even for the core,
// so this exception is ignored
}
}
/**
* Filter classes.
*
* @param name class name
* @return true if the class should be filtered
*/
protected boolean filter(String name) {
if (name == null)
return false;
// Looking up the package
String packageName = null;
int pos = name.lastIndexOf('.');
if (pos != -1)
packageName = name.substring(0, pos);
else
return false;
for (int i = 0; i < packageTriggers.length; i++) {
if (packageName.startsWith(packageTriggers[i]))
return true;
}
return false;
}
/**
* Validate a classname. As per SRV.9.7.2, we must restrict loading of
* classes from J2SE (java.*) and most classes of the servlet API
* (javax.servlet.*). That should enhance robustness and prevent a number
* of user error (where an older version of servlet.jar would be present
* in /WEB-INF/lib).
*
* @param name class name
* @return true if the name is valid
*/
protected boolean validate(String name) {
// Need to be careful with order here
if (name == null) {
// Can't load a class without a name
return false;
}
if (name.startsWith("java.")) {
// Must never load java.* classes
return false;
}
if (name.startsWith("javax.servlet.jsp.jstl")) {
// OK for web apps to package JSTL
return true;
}
if (name.startsWith("javax.servlet.")) {
// Web apps should never package any other Servlet or JSP classes
return false;
}
if (name.startsWith("javax.el")) {
// Must never load javax.el.* classes
return false;
}
// Assume everything else is OK
return true;
}
/**
* Check the specified JAR file, and return <code>true</code> if it does
* not contain any of the trigger classes.
*
* @param file The JAR file to be checked
*
* @exception IOException if an input/output error occurs
*/
protected boolean validateJarFile(File file)
throws IOException {
if (triggers == null)
return (true);
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
for (int i = 0; i < triggers.length; i++) {
Class<?> clazz = null;
try {
if (parent != null) {
clazz = parent.loadClass(triggers[i]);
} else {
clazz = Class.forName(triggers[i]);
}
} catch (Exception e) {
clazz = null;
}
if (clazz == null)
continue;
String name = triggers[i].replace('.', '/') + CLASS_FILE_SUFFIX;
if (log.isDebugEnabled())
log.debug(" Checking for " + name);
JarEntry jarEntry = jarFile.getJarEntry(name);
if (jarEntry != null) {
log.info("validateJarFile(" + file +
") - jar not loaded. See Servlet Spec 3.1, "
+ "section 10.7.2. Offending class: " + name);
return false;
}
}
return true;
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException ioe) {
// Ignore
}
}
}
}
/**
* Get the URI for the given file.
*/
protected URL getURI(File file)
throws MalformedURLException {
File realFile = file;
try {
realFile = realFile.getCanonicalFile();
} catch (IOException e) {
// Ignore
}
return realFile.toURI().toURL();
}
/**
* Delete the specified directory, including all of its contents and
* subdirectories recursively.
*
* @param dir File object representing the directory to be deleted
*/
protected static void deleteDir(File dir) {
String files[] = dir.list();
if (files == null) {
files = new String[0];
}
for (int i = 0; i < files.length; i++) {
File file = new File(dir, files[i]);
if (file.isDirectory()) {
deleteDir(file);
} else {
file.delete();
}
}
dir.delete();
}
}
|
55,702
|
Bug 55702 TLD cannot be loaded if CATALINA_HOME contains spaces
|
A web application containing an own TLD within its WEB-INF directory fails to render a JSP page referencing that TLD if Tomcat it installed into a directory with spaces in the path, such as "C:\Program Files\...". After moving the entire Tomcat installation directory to a path without spaces (such as "C:\1\Tomcat8"), the application can render that same JSP page. Following stacktrace is printed. Note the %20 in the file path org.apache.jasper.JasperException: /jsp/layouts/standard.jsp (line: 7, column: 69) File "file:/C:/Program%20Files/Apache/Tomcat-8.0.0-RC5/webapps/mywebapp/WEB-INF/tlds/mywebapp-tags.tld" not found org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42) org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:276) org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:92) org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:166) org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:410) org.apache.jasper.compiler.Parser.parseDirective(Parser.java:476) org.apache.jasper.compiler.Parser.parseElements(Parser.java:1451) org.apache.jasper.compiler.Parser.parse(Parser.java:138) org.apache.jasper.compiler.ParserController.doParse(ParserController.java:242) org.apache.jasper.compiler.ParserController.parse(ParserController.java:102) org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198) org.apache.jasper.compiler.Compiler.compile(Compiler.java:373) org.apache.jasper.compiler.Compiler.compile(Compiler.java:353) org.apache.jasper.compiler.Compiler.compile(Compiler.java:340) org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:606) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) Java version used: Oracle JDK 7 Update 45 (64 Bit) Active Tomcat connector: ["http-nio-8080"]
|
resolved fixed
|
ad50e54
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-29T13:00:00Z
| 2013-10-25T14:06:40Z
|
java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
|
/*
* 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.jasper.compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import javax.servlet.jsp.tagext.FunctionInfo;
import javax.servlet.jsp.tagext.PageData;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.TagFileInfo;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import javax.servlet.jsp.tagext.TagLibraryValidator;
import javax.servlet.jsp.tagext.TagVariableInfo;
import javax.servlet.jsp.tagext.ValidationMessage;
import javax.servlet.jsp.tagext.VariableInfo;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
import org.apache.jasper.util.ExceptionUtils;
import org.apache.jasper.xmlparser.ParserUtils;
import org.apache.jasper.xmlparser.TreeNode;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* Implementation of the TagLibraryInfo class from the JSP spec.
*
* @author Anil K. Vijendran
* @author Mandar Raje
* @author Pierre Delisle
* @author Kin-man Chung
* @author Jan Luehe
*/
class TagLibraryInfoImpl extends TagLibraryInfo implements TagConstants {
// Logger
private final Log log = LogFactory.getLog(TagLibraryInfoImpl.class);
private final JspCompilationContext ctxt;
private final PageInfo pi;
private final ErrorDispatcher err;
private final ParserController parserController;
private final void print(String name, String value, PrintWriter w) {
if (value != null) {
w.print(name + " = {\n\t");
w.print(value);
w.print("\n}\n");
}
}
@Override
public String toString() {
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
print("tlibversion", tlibversion, out);
print("jspversion", jspversion, out);
print("shortname", shortname, out);
print("urn", urn, out);
print("info", info, out);
print("uri", uri, out);
print("tagLibraryValidator", "" + tagLibraryValidator, out);
for (int i = 0; i < tags.length; i++)
out.println(tags[i].toString());
for (int i = 0; i < tagFiles.length; i++)
out.println(tagFiles[i].toString());
for (int i = 0; i < functions.length; i++)
out.println(functions[i].toString());
return sw.toString();
}
// XXX FIXME
// resolveRelativeUri and/or getResourceAsStream don't seem to properly
// handle relative paths when dealing when home and getDocBase are set
// the following is a workaround until these problems are resolved.
private InputStream getResourceAsStream(String uri)
throws FileNotFoundException {
// Is uri absolute?
if (uri.startsWith("file:")) {
return new FileInputStream(new File(uri.substring(5)));
} else {
try {
// see if file exists on the filesystem
String real = ctxt.getRealPath(uri);
if (real == null) {
return ctxt.getResourceAsStream(uri);
} else {
return new FileInputStream(real);
}
} catch (FileNotFoundException ex) {
// if file not found on filesystem, get the resource through
// the context
return ctxt.getResourceAsStream(uri);
}
}
}
/**
* Constructor.
*/
public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc,
PageInfo pi, String prefix, String uriIn, TldLocation location,
ErrorDispatcher err, Mark mark)
throws JasperException {
super(prefix, uriIn);
this.ctxt = ctxt;
this.parserController = pc;
this.pi = pi;
this.err = err;
InputStream in = null;
if (location == null) {
// The URI points to the TLD itself or to a JAR file in which the
// TLD is stored
location = generateTLDLocation(uri, ctxt);
}
String tldName = location.getName();
JarResource jarResource = location.getJarResource();
try {
if (jarResource == null) {
// Location points directly to TLD file
try {
in = getResourceAsStream(tldName);
if (in == null) {
throw new FileNotFoundException(tldName);
}
} catch (FileNotFoundException ex) {
err.jspError(mark, "jsp.error.file.not.found", tldName);
}
parseTLD(tldName, in, null);
// Add TLD to dependency list
PageInfo pageInfo = ctxt.createCompiler().getPageInfo();
if (pageInfo != null) {
pageInfo.addDependant(tldName,
ctxt.getLastModified(tldName));
}
} else {
// Tag library is packaged in JAR file
try {
in = jarResource.getEntry(tldName).openStream();
parseTLD(jarResource.getUrl(), in, jarResource);
} catch (Exception ex) {
err.jspError(mark, "jsp.error.tld.unable_to_read", jarResource.getUrl(),
tldName, ex.toString());
}
}
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
}
}
@Override
public TagLibraryInfo[] getTagLibraryInfos() {
Collection<TagLibraryInfo> coll = pi.getTaglibs();
return coll.toArray(new TagLibraryInfo[0]);
}
/*
* @param ctxt The JSP compilation context @param uri The TLD's uri @param
* in The TLD's input stream @param jarFileUrl The JAR file containing the
* TLD, or null if the tag library is not packaged in a JAR
*/
private void parseTLD(String uri, InputStream in, JarResource jarResource)
throws JasperException {
Vector<TagInfo> tagVector = new Vector<>();
Vector<TagFileInfo> tagFileVector = new Vector<>();
Hashtable<String, FunctionInfo> functionTable = new Hashtable<>();
// Create an iterator over the child elements of our <taglib> element
ParserUtils pu = new ParserUtils();
TreeNode tld = pu.parseXMLDocument(uri, in);
// Check to see if the <taglib> root element contains a 'version'
// attribute, which was added in JSP 2.0 to replace the <jsp-version>
// subelement
this.jspversion = tld.findAttribute("version");
// Process each child element of our <taglib> element
Iterator<TreeNode> list = tld.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("tlibversion".equals(tname) // JSP 1.1
|| "tlib-version".equals(tname)) { // JSP 1.2
this.tlibversion = element.getBody();
} else if ("jspversion".equals(tname)
|| "jsp-version".equals(tname)) {
this.jspversion = element.getBody();
} else if ("shortname".equals(tname) || "short-name".equals(tname))
this.shortname = element.getBody();
else if ("uri".equals(tname))
this.urn = element.getBody();
else if ("info".equals(tname) || "description".equals(tname))
this.info = element.getBody();
else if ("validator".equals(tname))
this.tagLibraryValidator = createValidator(element);
else if ("tag".equals(tname))
tagVector.addElement(createTagInfo(element, jspversion));
else if ("tag-file".equals(tname)) {
TagFileInfo tagFileInfo = createTagFileInfo(element,
jarResource);
tagFileVector.addElement(tagFileInfo);
} else if ("function".equals(tname)) { // JSP2.0
FunctionInfo funcInfo = createFunctionInfo(element);
String funcName = funcInfo.getName();
if (functionTable.containsKey(funcName)) {
err.jspError("jsp.error.tld.fn.duplicate.name", funcName,
uri);
}
functionTable.put(funcName, funcInfo);
} else if ("display-name".equals(tname) ||
"small-icon".equals(tname) || "large-icon".equals(tname)
|| "listener".equals(tname)) {
// Ignored elements
} else if ("taglib-extension".equals(tname)) {
// Recognized but ignored
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.taglib", tname));
}
}
}
if (tlibversion == null) {
err.jspError("jsp.error.tld.mandatory.element.missing",
"tlib-version", uri);
}
if (jspversion == null) {
err.jspError("jsp.error.tld.mandatory.element.missing",
"jsp-version", uri);
}
this.tags = new TagInfo[tagVector.size()];
tagVector.copyInto(this.tags);
this.tagFiles = new TagFileInfo[tagFileVector.size()];
tagFileVector.copyInto(this.tagFiles);
this.functions = new FunctionInfo[functionTable.size()];
int i = 0;
Enumeration<FunctionInfo> enumeration = functionTable.elements();
while (enumeration.hasMoreElements()) {
this.functions[i++] = enumeration.nextElement();
}
}
/*
* @param uri The uri of the TLD
* @param ctxt The compilation context
*
* @return the location of the TLD identified by the uri
*/
@SuppressWarnings("null") // url can't be null
private TldLocation generateTLDLocation(String uri, JspCompilationContext ctxt)
throws JasperException {
// TODO: this matches the current implementation but the URL logic looks fishy
// map URI to location per JSP 7.3.6.2
if (uri.indexOf(':') != -1) {
// abs_uri, this was not found in the taglibMap so raise an error
err.jspError("jsp.error.taglibDirective.absUriCannotBeResolved", uri);
} else if (uri.charAt(0) != '/') {
// noroot_rel_uri, resolve against the current JSP page
uri = ctxt.resolveRelativeUri(uri);
}
if (uri.endsWith(".jar")) {
URL url = null;
try {
url = ctxt.getResource(uri);
} catch (Exception ex) {
err.jspError("jsp.error.tld.unable_to_get_jar", uri, ex
.toString());
}
if (url == null) {
err.jspError("jsp.error.tld.missing_jar", uri);
}
return new TldLocation("META-INF/taglib.tld", url.toString());
} else {
return new TldLocation(uri);
}
}
private TagInfo createTagInfo(TreeNode elem, String jspVersion)
throws JasperException {
String tagName = null;
String tagClassName = null;
String teiClassName = null;
/*
* Default body content for JSP 1.2 tag handlers (<body-content> has
* become mandatory in JSP 2.0, because the default would be invalid for
* simple tag handlers)
*/
String bodycontent = "JSP";
String info = null;
String displayName = null;
String smallIcon = null;
String largeIcon = null;
boolean dynamicAttributes = false;
Vector<TagAttributeInfo> attributeVector = new Vector<>();
Vector<TagVariableInfo> variableVector = new Vector<>();
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("name".equals(tname)) {
tagName = element.getBody();
} else if ("tagclass".equals(tname) || "tag-class".equals(tname)) {
tagClassName = element.getBody();
} else if ("teiclass".equals(tname) || "tei-class".equals(tname)) {
teiClassName = element.getBody();
} else if ("bodycontent".equals(tname)
|| "body-content".equals(tname)) {
bodycontent = element.getBody();
} else if ("display-name".equals(tname)) {
displayName = element.getBody();
} else if ("small-icon".equals(tname)) {
smallIcon = element.getBody();
} else if ("large-icon".equals(tname)) {
largeIcon = element.getBody();
} else if ("icon".equals(tname)) {
TreeNode icon = element.findChild("small-icon");
if (icon != null) {
smallIcon = icon.getBody();
}
icon = element.findChild("large-icon");
if (icon != null) {
largeIcon = icon.getBody();
}
} else if ("info".equals(tname) || "description".equals(tname)) {
info = element.getBody();
} else if ("variable".equals(tname)) {
variableVector.addElement(createVariable(element));
} else if ("attribute".equals(tname)) {
attributeVector
.addElement(createAttribute(element, jspVersion));
} else if ("dynamic-attributes".equals(tname)) {
dynamicAttributes = JspUtil.booleanValue(element.getBody());
} else if ("example".equals(tname)) {
// Ignored elements
} else if ("tag-extension".equals(tname)) {
// Ignored
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.tag", tname));
}
}
}
TagExtraInfo tei = null;
if (teiClassName != null && !teiClassName.equals("")) {
try {
Class<?> teiClass =
ctxt.getClassLoader().loadClass(teiClassName);
tei = (TagExtraInfo) teiClass.newInstance();
} catch (Exception e) {
err.jspError(e, "jsp.error.teiclass.instantiation",
teiClassName);
}
}
TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector
.size()];
attributeVector.copyInto(tagAttributeInfo);
TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector
.size()];
variableVector.copyInto(tagVariableInfos);
TagInfo taginfo = new TagInfo(tagName, tagClassName, bodycontent, info,
this, tei, tagAttributeInfo, displayName, smallIcon, largeIcon,
tagVariableInfos, dynamicAttributes);
return taginfo;
}
/*
* Parses the tag file directives of the given TagFile and turns them into a
* TagInfo.
*
* @param elem The <tag-file> element in the TLD @param uri The location of
* the TLD, in case the tag file is specified relative to it @param jarFile
* The JAR file, in case the tag file is packaged in a JAR
*
* @return TagInfo corresponding to tag file directives
*/
private TagFileInfo createTagFileInfo(TreeNode elem, JarResource jarResource)
throws JasperException {
String name = null;
String path = null;
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode child = list.next();
String tname = child.getName();
if ("name".equals(tname)) {
name = child.getBody();
} else if ("path".equals(tname)) {
path = child.getBody();
} else if ("example".equals(tname)) {
// Ignore <example> element: Bugzilla 33538
} else if ("tag-extension".equals(tname)) {
// Ignore <tag-extension> element: Bugzilla 33538
} else if ("icon".equals(tname)
|| "display-name".equals(tname)
|| "description".equals(tname)) {
// Ignore these elements: Bugzilla 38015
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.tagfile", tname));
}
}
}
if (path == null) {
// path is required
err.jspError("jsp.error.tagfile.missingPath");
} else if (path.startsWith("/META-INF/tags")) {
// Tag file packaged in JAR
// See https://issues.apache.org/bugzilla/show_bug.cgi?id=46471
// This needs to be removed once all the broken code that depends on
// it has been removed
ctxt.setTagFileJarResource(path, jarResource);
} else if (!path.startsWith("/WEB-INF/tags")) {
err.jspError("jsp.error.tagfile.illegalPath", path);
}
TagInfo tagInfo = TagFileProcessor.parseTagFileDirectives(
parserController, name, path, jarResource, this);
return new TagFileInfo(name, path, tagInfo);
}
TagAttributeInfo createAttribute(TreeNode elem, String jspVersion) {
String name = null;
String type = null;
String expectedType = null;
String methodSignature = null;
boolean required = false, rtexprvalue = false, isFragment = false, deferredValue = false, deferredMethod = false;
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("name".equals(tname)) {
name = element.getBody();
} else if ("required".equals(tname)) {
String s = element.getBody();
if (s != null)
required = JspUtil.booleanValue(s);
} else if ("rtexprvalue".equals(tname)) {
String s = element.getBody();
if (s != null)
rtexprvalue = JspUtil.booleanValue(s);
} else if ("type".equals(tname)) {
type = element.getBody();
if ("1.2".equals(jspVersion)
&& (type.equals("Boolean") || type.equals("Byte")
|| type.equals("Character")
|| type.equals("Double")
|| type.equals("Float")
|| type.equals("Integer")
|| type.equals("Long") || type.equals("Object")
|| type.equals("Short") || type
.equals("String"))) {
type = "java.lang." + type;
}
} else if ("fragment".equals(tname)) {
String s = element.getBody();
if (s != null) {
isFragment = JspUtil.booleanValue(s);
}
} else if ("deferred-value".equals(tname)) {
deferredValue = true;
type = "javax.el.ValueExpression";
TreeNode child = element.findChild("type");
if (child != null) {
expectedType = child.getBody();
if (expectedType != null) {
expectedType = expectedType.trim();
}
} else {
expectedType = "java.lang.Object";
}
} else if ("deferred-method".equals(tname)) {
deferredMethod = true;
type = "javax.el.MethodExpression";
TreeNode child = element.findChild("method-signature");
if (child != null) {
methodSignature = child.getBody();
if (methodSignature != null) {
methodSignature = methodSignature.trim();
}
} else {
methodSignature = "java.lang.Object method()";
}
} else if ("description".equals(tname) || false) {
// Ignored elements
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.attribute", tname));
}
}
}
if (isFragment) {
/*
* According to JSP.C-3 ("TLD Schema Element Structure - tag"),
* 'type' and 'rtexprvalue' must not be specified if 'fragment' has
* been specified (this will be enforced by validating parser).
* Also, if 'fragment' is TRUE, 'type' is fixed at
* javax.servlet.jsp.tagext.JspFragment, and 'rtexprvalue' is fixed
* at true. See also JSP.8.5.2.
*/
type = "javax.servlet.jsp.tagext.JspFragment";
rtexprvalue = true;
}
if (!rtexprvalue && type == null) {
// According to JSP spec, for static values (those determined at
// translation time) the type is fixed at java.lang.String.
type = "java.lang.String";
}
return new TagAttributeInfo(name, required, type, rtexprvalue,
isFragment, null, deferredValue, deferredMethod, expectedType,
methodSignature);
}
TagVariableInfo createVariable(TreeNode elem) {
String nameGiven = null;
String nameFromAttribute = null;
String className = "java.lang.String";
boolean declare = true;
int scope = VariableInfo.NESTED;
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("name-given".equals(tname))
nameGiven = element.getBody();
else if ("name-from-attribute".equals(tname))
nameFromAttribute = element.getBody();
else if ("variable-class".equals(tname))
className = element.getBody();
else if ("declare".equals(tname)) {
String s = element.getBody();
if (s != null)
declare = JspUtil.booleanValue(s);
} else if ("scope".equals(tname)) {
String s = element.getBody();
if (s != null) {
if ("NESTED".equals(s)) {
scope = VariableInfo.NESTED;
} else if ("AT_BEGIN".equals(s)) {
scope = VariableInfo.AT_BEGIN;
} else if ("AT_END".equals(s)) {
scope = VariableInfo.AT_END;
}
}
} else if ("description".equals(tname) || // Ignored elements
false) {
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.variable", tname));
}
}
}
return new TagVariableInfo(nameGiven, nameFromAttribute, className,
declare, scope);
}
private TagLibraryValidator createValidator(TreeNode elem)
throws JasperException {
String validatorClass = null;
Map<String,Object> initParams = new Hashtable<>();
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("validator-class".equals(tname))
validatorClass = element.getBody();
else if ("init-param".equals(tname)) {
String[] initParam = createInitParam(element);
initParams.put(initParam[0], initParam[1]);
} else if ("description".equals(tname) || // Ignored elements
false) {
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.validator", tname));
}
}
}
TagLibraryValidator tlv = null;
if (validatorClass != null && !validatorClass.equals("")) {
try {
Class<?> tlvClass = ctxt.getClassLoader()
.loadClass(validatorClass);
tlv = (TagLibraryValidator) tlvClass.newInstance();
} catch (Exception e) {
err.jspError(e, "jsp.error.tlvclass.instantiation",
validatorClass);
}
}
if (tlv != null) {
tlv.setInitParameters(initParams);
}
return tlv;
}
String[] createInitParam(TreeNode elem) {
String[] initParam = new String[2];
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("param-name".equals(tname)) {
initParam[0] = element.getBody();
} else if ("param-value".equals(tname)) {
initParam[1] = element.getBody();
} else if ("description".equals(tname)) {
// Do nothing
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.initParam", tname));
}
}
}
return initParam;
}
FunctionInfo createFunctionInfo(TreeNode elem) {
String name = null;
String klass = null;
String signature = null;
Iterator<TreeNode> list = elem.findChildren();
while (list.hasNext()) {
TreeNode element = list.next();
String tname = element.getName();
if ("name".equals(tname)) {
name = element.getBody();
} else if ("function-class".equals(tname)) {
klass = element.getBody();
} else if ("function-signature".equals(tname)) {
signature = element.getBody();
} else if ("display-name".equals(tname) || // Ignored elements
"small-icon".equals(tname) || "large-icon".equals(tname)
|| "description".equals(tname) || "example".equals(tname)) {
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage(
"jsp.warning.unknown.element.in.function", tname));
}
}
}
return new FunctionInfo(name, klass, signature);
}
// *********************************************************************
// Until javax.servlet.jsp.tagext.TagLibraryInfo is fixed
/**
* The instance (if any) for the TagLibraryValidator class.
*
* @return The TagLibraryValidator instance, if any.
*/
public TagLibraryValidator getTagLibraryValidator() {
return tagLibraryValidator;
}
/**
* Translation-time validation of the XML document associated with the JSP
* page. This is a convenience method on the associated TagLibraryValidator
* class.
*
* @param thePage
* The JSP page object
* @return A string indicating whether the page is valid or not.
*/
public ValidationMessage[] validate(PageData thePage) {
TagLibraryValidator tlv = getTagLibraryValidator();
if (tlv == null)
return null;
String uri = getURI();
if (uri.startsWith("/")) {
uri = URN_JSPTLD + uri;
}
return tlv.validate(getPrefixString(), uri, thePage);
}
private TagLibraryValidator tagLibraryValidator;
}
|
55,715
|
Bug 55715 RemoteEndpoint.Async#sendText(String, SendHandler) can cause StackOverflowErrors and contradicts Oracle's JavaDoc
| null |
resolved fixed
|
3f316f1
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-30T11:20:08Z
| 2013-10-28T19:53:20Z
|
java/org/apache/tomcat/websocket/server/Constants.java
|
/*
* 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.websocket.server;
/**
* Internal implementation constants.
*/
public class Constants {
protected static final String PACKAGE_NAME =
Constants.class.getPackage().getName();
public static final String BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM =
"org.apache.tomcat.websocket.binaryBufferSize";
public static final String TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM =
"org.apache.tomcat.websocket.textBufferSize";
public static final String ENFORCE_NO_ADD_AFTER_HANDSHAKE_CONTEXT_INIT_PARAM =
"org.apache.tomcat.websocket.noAddAfterHandshake";
public static final String SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE =
"javax.websocket.server.ServerContainer";
private Constants() {
// Hide default constructor
}
}
|
55,715
|
Bug 55715 RemoteEndpoint.Async#sendText(String, SendHandler) can cause StackOverflowErrors and contradicts Oracle's JavaDoc
| null |
resolved fixed
|
3f316f1
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-30T11:20:08Z
| 2013-10-28T19:53:20Z
|
java/org/apache/tomcat/websocket/server/WsContextListener.java
|
/*
* 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.websocket.server;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* In normal usage, this {@link ServletContextListener} does not need to be
* explicitly configured as the {@link WsSci} performs all the necessary
* bootstrap and installs this listener in the {@link ServletContext}. If the
* {@link WsSci} is disabled, this listener must be added manually to every
* {@link ServletContext} that uses WebSocket to bootstrap the
* {@link WsServerContainer} correctly.
*/
public class WsContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
// Don't trigger WebSocket initialization if a WebSocket Server
// Container is already present
if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) {
WsSci.init(sce.getServletContext(), false);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
Object obj = sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
if (obj instanceof WsServerContainer) {
((WsServerContainer) obj).destroy();
}
}
}
|
55,715
|
Bug 55715 RemoteEndpoint.Async#sendText(String, SendHandler) can cause StackOverflowErrors and contradicts Oracle's JavaDoc
| null |
resolved fixed
|
3f316f1
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-30T11:20:08Z
| 2013-10-28T19:53:20Z
|
java/org/apache/tomcat/websocket/server/WsHttpUpgradeHandler.java
|
/*
* 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.websocket.server;
import java.io.EOFException;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.WebConnection;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.WsIOException;
import org.apache.tomcat.websocket.WsSession;
/**
* Servlet 3.1 HTTP upgrade handler for WebSocket connections.
*/
public class WsHttpUpgradeHandler implements HttpUpgradeHandler {
private static final Log log =
LogFactory.getLog(WsHttpUpgradeHandler.class);
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private final ClassLoader applicationClassLoader;
private Endpoint ep;
private EndpointConfig endpointConfig;
private WsServerContainer webSocketContainer;
private WsHandshakeRequest handshakeRequest;
private String subProtocol;
private Map<String,String> pathParameters;
private boolean secure;
private WebConnection connection;
private WsSession wsSession;
public WsHttpUpgradeHandler() {
applicationClassLoader = Thread.currentThread().getContextClassLoader();
}
public void preInit(Endpoint ep, EndpointConfig endpointConfig,
WsServerContainer wsc, WsHandshakeRequest handshakeRequest,
String subProtocol, Map<String,String> pathParameters,
boolean secure) {
this.ep = ep;
this.endpointConfig = endpointConfig;
this.webSocketContainer = wsc;
this.handshakeRequest = handshakeRequest;
this.subProtocol = subProtocol;
this.pathParameters = pathParameters;
this.secure = secure;
}
@Override
public void init(WebConnection connection) {
if (ep == null) {
throw new IllegalStateException(
sm.getString("wsHttpUpgradeHandler.noPreInit"));
}
this.connection = connection;
ServletInputStream sis;
ServletOutputStream sos;
try {
sis = connection.getInputStream();
sos = connection.getOutputStream();
} catch (IOException e) {
throw new IllegalStateException(e);
}
String httpSessionId = null;
Object session = handshakeRequest.getHttpSession();
if (session != null ) {
httpSessionId = ((HttpSession) session).getId();
}
// Need to call onOpen using the web application's class loader
// Create the frame using the application's class loader so it can pick
// up application specific config from the ServerContainerImpl
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
WsRemoteEndpointImplServer wsRemoteEndpointServer =
new WsRemoteEndpointImplServer(sos, webSocketContainer);
wsSession = new WsSession(ep, wsRemoteEndpointServer,
webSocketContainer, handshakeRequest.getRequestURI(),
handshakeRequest.getParameterMap(),
handshakeRequest.getQueryString(),
handshakeRequest.getUserPrincipal(), httpSessionId,
subProtocol, pathParameters, secure, endpointConfig);
WsFrameServer wsFrame = new WsFrameServer(
sis,
wsSession);
sos.setWriteListener(
new WsWriteListener(this, wsRemoteEndpointServer));
ep.onOpen(wsSession, endpointConfig);
webSocketContainer.registerSession(ep, wsSession);
sis.setReadListener(new WsReadListener(this, wsFrame));
} catch (DeploymentException e) {
throw new IllegalArgumentException(e);
} finally {
t.setContextClassLoader(cl);
}
}
@Override
public void destroy() {
try {
connection.close();
} catch (Exception e) {
log.error(sm.getString("wsHttpUpgradeHandler.destroyFailed"), e);
}
}
private void onError(Throwable throwable) {
// Need to call onError using the web application's class loader
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
ep.onError(wsSession, throwable);
} finally {
t.setContextClassLoader(cl);
}
}
private void close(CloseReason cr) {
/*
* Any call to this method is a result of a problem reading from the
* client. At this point that state of the connection is unknown.
* Attempt to send a close frame to the client and then close the socket
* immediately. There is no point in waiting for a close frame from the
* client because there is no guarantee that we can recover from
* whatever messed up state the client put the connection into.
*/
wsSession.onClose(cr);
}
private static class WsReadListener implements ReadListener {
private final WsHttpUpgradeHandler wsProtocolHandler;
private final WsFrameServer wsFrame;
private WsReadListener(WsHttpUpgradeHandler wsProtocolHandler,
WsFrameServer wsFrame) {
this.wsProtocolHandler = wsProtocolHandler;
this.wsFrame = wsFrame;
}
@Override
public void onDataAvailable() {
try {
wsFrame.onDataAvailable();
} catch (WsIOException ws) {
wsProtocolHandler.close(ws.getCloseReason());
} catch (EOFException eof) {
CloseReason cr = new CloseReason(
CloseCodes.CLOSED_ABNORMALLY, eof.getMessage());
wsProtocolHandler.close(cr);
} catch (IOException ioe) {
onError(ioe);
CloseReason cr = new CloseReason(
CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
wsProtocolHandler.close(cr);
}
}
@Override
public void onAllDataRead() {
// Will never happen with WebSocket
throw new IllegalStateException();
}
@Override
public void onError(Throwable throwable) {
wsProtocolHandler.onError(throwable);
}
}
private static class WsWriteListener implements WriteListener {
private final WsHttpUpgradeHandler wsProtocolHandler;
private final WsRemoteEndpointImplServer wsRemoteEndpointServer;
private WsWriteListener(WsHttpUpgradeHandler wsProtocolHandler,
WsRemoteEndpointImplServer wsRemoteEndpointServer) {
this.wsProtocolHandler = wsProtocolHandler;
this.wsRemoteEndpointServer = wsRemoteEndpointServer;
}
@Override
public void onWritePossible() {
wsRemoteEndpointServer.onWritePossible();
}
@Override
public void onError(Throwable throwable) {
wsProtocolHandler.onError(throwable);
wsRemoteEndpointServer.close();
}
}
}
|
55,715
|
Bug 55715 RemoteEndpoint.Async#sendText(String, SendHandler) can cause StackOverflowErrors and contradicts Oracle's JavaDoc
| null |
resolved fixed
|
3f316f1
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-30T11:20:08Z
| 2013-10-28T19:53:20Z
|
java/org/apache/tomcat/websocket/server/WsRemoteEndpointImplServer.java
|
/*
* 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.websocket.server;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import javax.servlet.ServletOutputStream;
import javax.websocket.SendHandler;
import javax.websocket.SendResult;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.WsRemoteEndpointImplBase;
/**
* This is the server side {@link javax.websocket.RemoteEndpoint} implementation
* - i.e. what the server uses to send data to the client. Communication is over
* a {@link ServletOutputStream}.
*/
public class WsRemoteEndpointImplServer extends WsRemoteEndpointImplBase {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static final Log log =
LogFactory.getLog(WsHttpUpgradeHandler.class);
private final ServletOutputStream sos;
private final WsWriteTimeout wsWriteTimeout;
private volatile SendHandler handler = null;
private volatile ByteBuffer[] buffers = null;
private volatile long timeoutExpiry = -1;
private volatile boolean close;
public WsRemoteEndpointImplServer(ServletOutputStream sos,
WsServerContainer serverContainer) {
this.sos = sos;
this.wsWriteTimeout = serverContainer.getTimeout();
}
@Override
protected final boolean isMasked() {
return false;
}
@Override
protected void doWrite(SendHandler handler, ByteBuffer... buffers) {
this.handler = handler;
this.buffers = buffers;
onWritePossible();
}
public void onWritePossible() {
boolean complete = true;
try {
// If this is false there will be a call back when it is true
while (sos.isReady()) {
complete = true;
for (ByteBuffer buffer : buffers) {
if (buffer.hasRemaining()) {
complete = false;
sos.write(buffer.array(), buffer.arrayOffset(),
buffer.limit());
buffer.position(buffer.limit());
break;
}
}
if (complete) {
wsWriteTimeout.unregister(this);
clearHandler(null);
if (close) {
close();
}
break;
}
}
} catch (IOException ioe) {
wsWriteTimeout.unregister(this);
clearHandler(ioe);
close();
}
if (!complete) {
// Async write is in progress
long timeout = getSendTimeout();
if (timeout > 0) {
// Register with timeout thread
timeoutExpiry = timeout + System.currentTimeMillis();
wsWriteTimeout.register(this);
}
}
}
@Override
protected void doClose() {
if (handler != null) {
clearHandler(new EOFException());
}
try {
sos.close();
} catch (IOException e) {
if (log.isInfoEnabled()) {
log.info(sm.getString("wsRemoteEndpointServer.closeFailed"), e);
}
}
wsWriteTimeout.unregister(this);
}
protected long getTimeoutExpiry() {
return timeoutExpiry;
}
protected void onTimeout() {
if (handler != null) {
clearHandler(new SocketTimeoutException());
}
close();
}
private void clearHandler(Throwable t) {
// Setting the result marks this (partial) message as
// complete which means the next one may be sent which
// could update the value of the handler. Therefore, keep a
// local copy before signalling the end of the (partial)
// message.
SendHandler sh = handler;
handler = null;
if (sh != null) {
if (t == null) {
sh.onResult(new SendResult());
} else {
sh.onResult(new SendResult(t));
}
}
}
}
|
55,715
|
Bug 55715 RemoteEndpoint.Async#sendText(String, SendHandler) can cause StackOverflowErrors and contradicts Oracle's JavaDoc
| null |
resolved fixed
|
3f316f1
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-30T11:20:08Z
| 2013-10-28T19:53:20Z
|
java/org/apache/tomcat/websocket/server/WsServerContainer.java
|
/*
* 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.websocket.server;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Encoder;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.WsSession;
import org.apache.tomcat.websocket.WsWebSocketContainer;
import org.apache.tomcat.websocket.pojo.PojoEndpointServer;
import org.apache.tomcat.websocket.pojo.PojoMethodMapping;
/**
* Provides a per class loader (i.e. per web application) instance of a
* ServerContainer. Web application wide defaults may be configured by setting
* the following servlet context initialisation parameters to the desired
* values.
* <ul>
* <li>{@link Constants#BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li>
* <li>{@link Constants#TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li>
* </ul>
*/
public class WsServerContainer extends WsWebSocketContainer
implements ServerContainer {
private static final StringManager sm =
StringManager.getManager(Constants.PACKAGE_NAME);
private static final CloseReason AUTHENTICATED_HTTP_SESSION_CLOSED =
new CloseReason(CloseCodes.VIOLATED_POLICY,
"This connection was established under an authenticated " +
"HTTP session that has ended.");
private final WsWriteTimeout wsWriteTimeout = new WsWriteTimeout();
private final ServletContext servletContext;
private final Map<String,ServerEndpointConfig> configExactMatchMap =
new ConcurrentHashMap<>();
private final ConcurrentHashMap<Integer,SortedSet<TemplatePathMatch>>
configTemplateMatchMap = new ConcurrentHashMap<>();
private volatile boolean enforceNoAddAfterHandshake =
org.apache.tomcat.websocket.Constants.STRICT_SPEC_COMPLIANCE;
private volatile boolean addAllowed = true;
private final ConcurrentHashMap<String,Set<WsSession>> authenticatedSessions =
new ConcurrentHashMap<>();
WsServerContainer(ServletContext servletContext) {
this.servletContext = servletContext;
// Configure servlet context wide defaults
String value = servletContext.getInitParameter(
Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
if (value != null) {
setDefaultMaxBinaryMessageBufferSize(Integer.parseInt(value));
}
value = servletContext.getInitParameter(
Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM);
if (value != null) {
setDefaultMaxTextMessageBufferSize(Integer.parseInt(value));
}
value = servletContext.getInitParameter(
Constants.ENFORCE_NO_ADD_AFTER_HANDSHAKE_CONTEXT_INIT_PARAM);
if (value != null) {
setEnforceNoAddAfterHandshake(Boolean.parseBoolean(value));
}
FilterRegistration.Dynamic fr = servletContext.addFilter(
WsFilter.class.getName(), new WsFilter());
fr.setAsyncSupported(true);
EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.REQUEST,
DispatcherType.FORWARD);
fr.addMappingForUrlPatterns(types, true, "/*");
}
/**
* Published the provided endpoint implementation at the specified path with
* the specified configuration. {@link #WsServerContainer(ServletContext)}
* must be called before calling this method.
*
* @param sec The configuration to use when creating endpoint instances
* @throws DeploymentException
*/
@Override
public void addEndpoint(ServerEndpointConfig sec)
throws DeploymentException {
if (enforceNoAddAfterHandshake && !addAllowed) {
throw new DeploymentException(
sm.getString("serverContainer.addNotAllowed"));
}
if (servletContext == null) {
throw new DeploymentException(
sm.getString("serverContainer.servletContextMissing"));
}
String path = sec.getPath();
UriTemplate uriTemplate = new UriTemplate(path);
if (uriTemplate.hasParameters()) {
Integer key = Integer.valueOf(uriTemplate.getSegmentCount());
SortedSet<TemplatePathMatch> templateMatches =
configTemplateMatchMap.get(key);
if (templateMatches == null) {
// Ensure that if concurrent threads execute this block they
// both end up using the same TreeSet instance
templateMatches = new TreeSet<>(
TemplatePathMatchComparator.getInstance());
configTemplateMatchMap.putIfAbsent(key, templateMatches);
templateMatches = configTemplateMatchMap.get(key);
}
if (!templateMatches.add(new TemplatePathMatch(sec, uriTemplate))) {
// Duplicate uriTemplate;
throw new DeploymentException(
sm.getString("serverContainer.duplicatePaths", path));
}
} else {
// Exact match
ServerEndpointConfig old = configExactMatchMap.put(path, sec);
if (old != null) {
// Duplicate path mappings
throw new DeploymentException(
sm.getString("serverContainer.duplicatePaths", path));
}
}
}
/**
* Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)}
* for publishing plain old java objects (POJOs) that have been annotated as
* WebSocket endpoints.
*
* @param pojo The annotated POJO
*/
@Override
public void addEndpoint(Class<?> pojo) throws DeploymentException {
ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
if (annotation == null) {
throw new DeploymentException(
sm.getString("serverContainer.missingAnnotation",
pojo.getName()));
}
String path = annotation.value();
// Validate encoders
validateEncoders(annotation.encoders());
// Method mapping
PojoMethodMapping methodMapping = new PojoMethodMapping(pojo,
annotation.decoders(), path);
// ServerEndpointConfig
ServerEndpointConfig sec;
Class<? extends Configurator> configuratorClazz =
annotation.configurator();
Configurator configurator = null;
if (!configuratorClazz.equals(Configurator.class)) {
try {
configurator = annotation.configurator().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new DeploymentException(sm.getString(
"serverContainer.configuratorFail",
annotation.configurator().getName(),
pojo.getClass().getName()), e);
}
}
sec = ServerEndpointConfig.Builder.create(pojo, path).
decoders(Arrays.asList(annotation.decoders())).
encoders(Arrays.asList(annotation.encoders())).
subprotocols(Arrays.asList(annotation.subprotocols())).
configurator(configurator).
build();
sec.getUserProperties().put(
PojoEndpointServer.POJO_METHOD_MAPPING_KEY,
methodMapping);
addEndpoint(sec);
}
public void doUpgrade(HttpServletRequest request,
HttpServletResponse response, ServerEndpointConfig sec,
Map<String,String> pathParams)
throws ServletException, IOException {
UpgradeUtil.doUpgrade(this, request, response, sec, pathParams);
}
public WsMappingResult findMapping(String path) {
// Prevent registering additional endpoints once the first attempt has
// been made to use one
if (addAllowed) {
addAllowed = false;
}
// Check an exact match. Simple case as there are no templates.
ServerEndpointConfig sec = configExactMatchMap.get(path);
if (sec != null) {
return new WsMappingResult(sec,
Collections.<String, String> emptyMap());
}
// No exact match. Need to look for template matches.
UriTemplate pathUriTemplate = null;
try {
pathUriTemplate = new UriTemplate(path);
} catch (DeploymentException e) {
// Path is not valid so can't be matched to a WebSocketEndpoint
return null;
}
// Number of segments has to match
Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount());
SortedSet<TemplatePathMatch> templateMatches =
configTemplateMatchMap.get(key);
if (templateMatches == null) {
// No templates with an equal number of segments so there will be
// no matches
return null;
}
// List is in alphabetical order of normalised templates.
// Correct match is the first one that matches.
Map<String,String> pathParams = null;
for (TemplatePathMatch templateMatch : templateMatches) {
pathParams = templateMatch.getUriTemplate().match(pathUriTemplate);
if (pathParams != null) {
sec = templateMatch.getConfig();
break;
}
}
if (sec == null) {
// No match
return null;
}
if (!PojoEndpointServer.class.isAssignableFrom(sec.getEndpointClass())) {
// Need to make path params available to POJO
sec.getUserProperties().put(
PojoEndpointServer.POJO_PATH_PARAM_KEY,
pathParams);
}
return new WsMappingResult(sec, pathParams);
}
public boolean isEnforceNoAddAfterHandshake() {
return enforceNoAddAfterHandshake;
}
public void setEnforceNoAddAfterHandshake(
boolean enforceNoAddAfterHandshake) {
this.enforceNoAddAfterHandshake = enforceNoAddAfterHandshake;
}
protected WsWriteTimeout getTimeout() {
return wsWriteTimeout;
}
/**
* {@inheritDoc}
*
* Overridden to make it visible to other classes in this package.
*/
@Override
protected void registerSession(Endpoint endpoint, WsSession wsSession) {
super.registerSession(endpoint, wsSession);
if (wsSession.isOpen() &&
wsSession.getUserPrincipal() != null &&
wsSession.getHttpSessionId() != null) {
registerAuthenticatedSession(wsSession,
wsSession.getHttpSessionId());
}
}
/**
* {@inheritDoc}
*
* Overridden to make it visible to other classes in this package.
*/
@Override
protected void unregisterSession(Endpoint endpoint, WsSession wsSession) {
if (wsSession.getUserPrincipal() != null &&
wsSession.getHttpSessionId() != null) {
unregisterAuthenticatedSession(wsSession,
wsSession.getHttpSessionId());
}
super.unregisterSession(endpoint, wsSession);
}
private void registerAuthenticatedSession(WsSession wsSession,
String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
if (wsSessions == null) {
wsSessions = Collections.newSetFromMap(
new ConcurrentHashMap<WsSession,Boolean>());
authenticatedSessions.putIfAbsent(httpSessionId, wsSessions);
wsSessions = authenticatedSessions.get(httpSessionId);
}
wsSessions.add(wsSession);
}
private void unregisterAuthenticatedSession(WsSession wsSession,
String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId);
wsSessions.remove(wsSession);
}
public void closeAuthenticatedSession(String httpSessionId) {
Set<WsSession> wsSessions = authenticatedSessions.remove(httpSessionId);
if (wsSessions != null && !wsSessions.isEmpty()) {
for (WsSession wsSession : wsSessions) {
try {
wsSession.close(AUTHENTICATED_HTTP_SESSION_CLOSED);
} catch (IOException e) {
// Any IOExceptions during close will have been caught and the
// onError method called.
}
}
}
}
private static void validateEncoders(Class<? extends Encoder>[] encoders)
throws DeploymentException {
for (Class<? extends Encoder> encoder : encoders) {
// Need to instantiate decoder to ensure it is valid and that
// deployment can be failed if it is not
@SuppressWarnings("unused")
Encoder instance;
try {
encoder.newInstance();
} catch(InstantiationException | IllegalAccessException e) {
throw new DeploymentException(sm.getString(
"serverContainer.encoderFail", encoder.getName()), e);
}
}
}
private static class TemplatePathMatch {
private final ServerEndpointConfig config;
private final UriTemplate uriTemplate;
public TemplatePathMatch(ServerEndpointConfig config,
UriTemplate uriTemplate) {
this.config = config;
this.uriTemplate = uriTemplate;
}
public ServerEndpointConfig getConfig() {
return config;
}
public UriTemplate getUriTemplate() {
return uriTemplate;
}
}
/**
* This Comparator implementation is thread-safe so only create a single
* instance.
*/
private static class TemplatePathMatchComparator
implements Comparator<TemplatePathMatch> {
private static final TemplatePathMatchComparator INSTANCE =
new TemplatePathMatchComparator();
public static TemplatePathMatchComparator getInstance() {
return INSTANCE;
}
private TemplatePathMatchComparator() {
// Hide default constructor
}
@Override
public int compare(TemplatePathMatch tpm1, TemplatePathMatch tpm2) {
return tpm1.getUriTemplate().getNormalizedPath().compareTo(
tpm2.getUriTemplate().getNormalizedPath());
}
}
}
|
55,715
|
Bug 55715 RemoteEndpoint.Async#sendText(String, SendHandler) can cause StackOverflowErrors and contradicts Oracle's JavaDoc
| null |
resolved fixed
|
3f316f1
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-10-30T11:20:08Z
| 2013-10-28T19:53:20Z
|
java/org/apache/tomcat/websocket/server/WsWriteTimeout.java
|
/*
* 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.websocket.server;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.tomcat.websocket.BackgroundProcess;
import org.apache.tomcat.websocket.BackgroundProcessManager;
/**
* Provides timeouts for asynchronous web socket writes. On the server side we
* only have access to {@link javax.servlet.ServletOutputStream} and
* {@link javax.servlet.ServletInputStream} so there is no way to set a timeout
* for writes to the client.
*/
public class WsWriteTimeout implements BackgroundProcess {
private final Set<WsRemoteEndpointImplServer> endpoints =
new ConcurrentSkipListSet<>(new EndpointComparator());
private final AtomicInteger count = new AtomicInteger(0);
private int backgroundProcessCount = 0;
private volatile int processPeriod = 1;
@Override
public void backgroundProcess() {
// This method gets called once a second.
backgroundProcessCount ++;
if (backgroundProcessCount >= processPeriod) {
backgroundProcessCount = 0;
long now = System.currentTimeMillis();
Iterator<WsRemoteEndpointImplServer> iter = endpoints.iterator();
while (iter.hasNext()) {
WsRemoteEndpointImplServer endpoint = iter.next();
if (endpoint.getTimeoutExpiry() < now) {
endpoint.onTimeout();
} else {
// Endpoints are ordered by timeout expiry so if this point
// is reached there is no need to check the remaining
// endpoints
break;
}
}
}
}
@Override
public void setProcessPeriod(int period) {
this.processPeriod = period;
}
/**
* {@inheritDoc}
*
* The default value is 1 which means asynchronous write timeouts are
* processed every 1 second.
*/
@Override
public int getProcessPeriod() {
return processPeriod;
}
public void register(WsRemoteEndpointImplServer endpoint) {
boolean result = endpoints.add(endpoint);
if (result) {
int newCount = count.incrementAndGet();
if (newCount == 1) {
BackgroundProcessManager.getInstance().register(this);
}
}
}
public void unregister(WsRemoteEndpointImplServer endpoint) {
boolean result = endpoints.remove(endpoint);
if (result) {
int newCount = count.decrementAndGet();
if (newCount == 0) {
BackgroundProcessManager.getInstance().unregister(this);
}
}
}
/**
* Note: this comparator imposes orderings that are inconsistent with equals
*/
private static class EndpointComparator implements
Comparator<WsRemoteEndpointImplServer> {
@Override
public int compare(WsRemoteEndpointImplServer o1,
WsRemoteEndpointImplServer o2) {
long t1 = o1.getTimeoutExpiry();
long t2 = o2.getTimeoutExpiry();
if (t1 < t2) {
return -1;
} else if (t1 == t2) {
return 0;
} else {
return 1;
}
}
}
}
|
55,735
|
Bug 55735 Additional quote entity in html element attribute evaluated in tagx if attribute contains EL expression
| null |
resolved fixed
|
7ee1275
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-11-05T22:46:35Z
| 2013-11-02T11:00:00Z
|
java/org/apache/jasper/compiler/Validator.java
|
/*
* 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.jasper.compiler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import javax.el.ELException;
import javax.el.ExpressionFactory;
import javax.el.FunctionMapper;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.tagext.FunctionInfo;
import javax.servlet.jsp.tagext.PageData;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import javax.servlet.jsp.tagext.ValidationMessage;
import org.apache.jasper.JasperException;
import org.apache.jasper.el.ELContextImpl;
import org.xml.sax.Attributes;
/**
* Performs validation on the page elements. Attributes are checked for
* mandatory presence, entry value validity, and consistency. As a side effect,
* some page global value (such as those from page directives) are stored, for
* later use.
*
* @author Kin-man Chung
* @author Jan Luehe
* @author Shawn Bayern
* @author Mark Roth
*/
class Validator {
/**
* A visitor to validate and extract page directive info
*/
private static class DirectiveVisitor extends Node.Visitor {
private final PageInfo pageInfo;
private final ErrorDispatcher err;
private static final JspUtil.ValidAttribute[] pageDirectiveAttrs = {
new JspUtil.ValidAttribute("language"),
new JspUtil.ValidAttribute("extends"),
new JspUtil.ValidAttribute("import"),
new JspUtil.ValidAttribute("session"),
new JspUtil.ValidAttribute("buffer"),
new JspUtil.ValidAttribute("autoFlush"),
new JspUtil.ValidAttribute("isThreadSafe"),
new JspUtil.ValidAttribute("info"),
new JspUtil.ValidAttribute("errorPage"),
new JspUtil.ValidAttribute("isErrorPage"),
new JspUtil.ValidAttribute("contentType"),
new JspUtil.ValidAttribute("pageEncoding"),
new JspUtil.ValidAttribute("isELIgnored"),
new JspUtil.ValidAttribute("deferredSyntaxAllowedAsLiteral"),
new JspUtil.ValidAttribute("trimDirectiveWhitespaces")
};
private boolean pageEncodingSeen = false;
/*
* Constructor
*/
DirectiveVisitor(Compiler compiler) {
this.pageInfo = compiler.getPageInfo();
this.err = compiler.getErrorDispatcher();
}
@Override
public void visit(Node.IncludeDirective n) throws JasperException {
// Since pageDirectiveSeen flag only applies to the Current page
// save it here and restore it after the file is included.
boolean pageEncodingSeenSave = pageEncodingSeen;
pageEncodingSeen = false;
visitBody(n);
pageEncodingSeen = pageEncodingSeenSave;
}
@Override
public void visit(Node.PageDirective n) throws JasperException {
JspUtil.checkAttributes("Page directive", n, pageDirectiveAttrs,
err);
// JSP.2.10.1
Attributes attrs = n.getAttributes();
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
String attr = attrs.getQName(i);
String value = attrs.getValue(i);
if ("language".equals(attr)) {
if (pageInfo.getLanguage(false) == null) {
pageInfo.setLanguage(value, n, err, true);
} else if (!pageInfo.getLanguage(false).equals(value)) {
err.jspError(n, "jsp.error.page.conflict.language",
pageInfo.getLanguage(false), value);
}
} else if ("extends".equals(attr)) {
if (pageInfo.getExtends(false) == null) {
pageInfo.setExtends(value, n);
} else if (!pageInfo.getExtends(false).equals(value)) {
err.jspError(n, "jsp.error.page.conflict.extends",
pageInfo.getExtends(false), value);
}
} else if ("contentType".equals(attr)) {
if (pageInfo.getContentType() == null) {
pageInfo.setContentType(value);
} else if (!pageInfo.getContentType().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.contenttype",
pageInfo.getContentType(), value);
}
} else if ("session".equals(attr)) {
if (pageInfo.getSession() == null) {
pageInfo.setSession(value, n, err);
} else if (!pageInfo.getSession().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.session",
pageInfo.getSession(), value);
}
} else if ("buffer".equals(attr)) {
if (pageInfo.getBufferValue() == null) {
pageInfo.setBufferValue(value, n, err);
} else if (!pageInfo.getBufferValue().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.buffer",
pageInfo.getBufferValue(), value);
}
} else if ("autoFlush".equals(attr)) {
if (pageInfo.getAutoFlush() == null) {
pageInfo.setAutoFlush(value, n, err);
} else if (!pageInfo.getAutoFlush().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.autoflush",
pageInfo.getAutoFlush(), value);
}
} else if ("isThreadSafe".equals(attr)) {
if (pageInfo.getIsThreadSafe() == null) {
pageInfo.setIsThreadSafe(value, n, err);
} else if (!pageInfo.getIsThreadSafe().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.isthreadsafe",
pageInfo.getIsThreadSafe(), value);
}
} else if ("isELIgnored".equals(attr)) {
if (pageInfo.getIsELIgnored() == null) {
pageInfo.setIsELIgnored(value, n, err, true);
} else if (!pageInfo.getIsELIgnored().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.iselignored",
pageInfo.getIsELIgnored(), value);
}
} else if ("isErrorPage".equals(attr)) {
if (pageInfo.getIsErrorPage() == null) {
pageInfo.setIsErrorPage(value, n, err);
} else if (!pageInfo.getIsErrorPage().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.iserrorpage",
pageInfo.getIsErrorPage(), value);
}
} else if ("errorPage".equals(attr)) {
if (pageInfo.getErrorPage() == null) {
pageInfo.setErrorPage(value);
} else if (!pageInfo.getErrorPage().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.errorpage",
pageInfo.getErrorPage(), value);
}
} else if ("info".equals(attr)) {
if (pageInfo.getInfo() == null) {
pageInfo.setInfo(value);
} else if (!pageInfo.getInfo().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.info",
pageInfo.getInfo(), value);
}
} else if ("pageEncoding".equals(attr)) {
if (pageEncodingSeen)
err.jspError(n, "jsp.error.page.multi.pageencoding");
// 'pageEncoding' can occur at most once per file
pageEncodingSeen = true;
String actual = comparePageEncodings(value, n);
n.getRoot().setPageEncoding(actual);
} else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) {
if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) {
pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n,
err, true);
} else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral()
.equals(value)) {
err
.jspError(
n,
"jsp.error.page.conflict.deferredsyntaxallowedasliteral",
pageInfo
.getDeferredSyntaxAllowedAsLiteral(),
value);
}
} else if ("trimDirectiveWhitespaces".equals(attr)) {
if (pageInfo.getTrimDirectiveWhitespaces() == null) {
pageInfo.setTrimDirectiveWhitespaces(value, n, err,
true);
} else if (!pageInfo.getTrimDirectiveWhitespaces().equals(
value)) {
err
.jspError(
n,
"jsp.error.page.conflict.trimdirectivewhitespaces",
pageInfo.getTrimDirectiveWhitespaces(),
value);
}
}
}
// Check for bad combinations
if (pageInfo.getBuffer() == 0 && !pageInfo.isAutoFlush())
err.jspError(n, "jsp.error.page.badCombo");
// Attributes for imports for this node have been processed by
// the parsers, just add them to pageInfo.
pageInfo.addImports(n.getImports());
}
@Override
public void visit(Node.TagDirective n) throws JasperException {
// Note: Most of the validation is done in TagFileProcessor
// when it created a TagInfo object from the
// tag file in which the directive appeared.
// This method does additional processing to collect page info
Attributes attrs = n.getAttributes();
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
String attr = attrs.getQName(i);
String value = attrs.getValue(i);
if ("language".equals(attr)) {
if (pageInfo.getLanguage(false) == null) {
pageInfo.setLanguage(value, n, err, false);
} else if (!pageInfo.getLanguage(false).equals(value)) {
err.jspError(n, "jsp.error.tag.conflict.language",
pageInfo.getLanguage(false), value);
}
} else if ("isELIgnored".equals(attr)) {
if (pageInfo.getIsELIgnored() == null) {
pageInfo.setIsELIgnored(value, n, err, false);
} else if (!pageInfo.getIsELIgnored().equals(value)) {
err.jspError(n, "jsp.error.tag.conflict.iselignored",
pageInfo.getIsELIgnored(), value);
}
} else if ("pageEncoding".equals(attr)) {
if (pageEncodingSeen)
err.jspError(n, "jsp.error.tag.multi.pageencoding");
pageEncodingSeen = true;
compareTagEncodings(value, n);
n.getRoot().setPageEncoding(value);
} else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) {
if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) {
pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n,
err, false);
} else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral()
.equals(value)) {
err
.jspError(
n,
"jsp.error.tag.conflict.deferredsyntaxallowedasliteral",
pageInfo
.getDeferredSyntaxAllowedAsLiteral(),
value);
}
} else if ("trimDirectiveWhitespaces".equals(attr)) {
if (pageInfo.getTrimDirectiveWhitespaces() == null) {
pageInfo.setTrimDirectiveWhitespaces(value, n, err,
false);
} else if (!pageInfo.getTrimDirectiveWhitespaces().equals(
value)) {
err
.jspError(
n,
"jsp.error.tag.conflict.trimdirectivewhitespaces",
pageInfo.getTrimDirectiveWhitespaces(),
value);
}
}
}
// Attributes for imports for this node have been processed by
// the parsers, just add them to pageInfo.
pageInfo.addImports(n.getImports());
}
@Override
public void visit(Node.AttributeDirective n) throws JasperException {
// Do nothing, since this attribute directive has already been
// validated by TagFileProcessor when it created a TagInfo object
// from the tag file in which the directive appeared
}
@Override
public void visit(Node.VariableDirective n) throws JasperException {
// Do nothing, since this variable directive has already been
// validated by TagFileProcessor when it created a TagInfo object
// from the tag file in which the directive appeared
}
/*
* Compares page encodings specified in various places, and throws
* exception in case of page encoding mismatch.
*
* @param pageDirEnc The value of the pageEncoding attribute of the page
* directive @param pageDir The page directive node
*
* @throws JasperException in case of page encoding mismatch
*/
private String comparePageEncodings(String thePageDirEnc,
Node.PageDirective pageDir) throws JasperException {
Node.Root root = pageDir.getRoot();
String configEnc = root.getJspConfigPageEncoding();
String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH);
/*
* Compare the 'pageEncoding' attribute of the page directive with
* the encoding specified in the JSP config element whose URL
* pattern matches this page. Treat "UTF-16", "UTF-16BE", and
* "UTF-16LE" as identical.
*/
if (configEnc != null) {
configEnc = configEnc.toUpperCase(Locale.ENGLISH);
if (!pageDirEnc.equals(configEnc)
&& (!pageDirEnc.startsWith("UTF-16") || !configEnc
.startsWith("UTF-16"))) {
err.jspError(pageDir,
"jsp.error.config_pagedir_encoding_mismatch",
configEnc, pageDirEnc);
} else {
return configEnc;
}
}
/*
* Compare the 'pageEncoding' attribute of the page directive with
* the encoding specified in the XML prolog (only for XML syntax,
* and only if JSP document contains XML prolog with encoding
* declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as
* identical.
*/
if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) {
String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH);
if (!pageDirEnc.equals(pageEnc)
&& (!pageDirEnc.startsWith("UTF-16") || !pageEnc
.startsWith("UTF-16"))) {
err.jspError(pageDir,
"jsp.error.prolog_pagedir_encoding_mismatch",
pageEnc, pageDirEnc);
} else {
return pageEnc;
}
}
return pageDirEnc;
}
/*
* Compares page encodings specified in various places, and throws
* exception in case of page encoding mismatch.
*
* @param thePageDirEnc The value of the pageEncoding attribute of the page
* directive @param pageDir The page directive node
*
* @throws JasperException in case of page encoding mismatch
*/
private void compareTagEncodings(String thePageDirEnc,
Node.TagDirective pageDir) throws JasperException {
Node.Root root = pageDir.getRoot();
String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH);
/*
* Compare the 'pageEncoding' attribute of the page directive with
* the encoding specified in the XML prolog (only for XML syntax,
* and only if JSP document contains XML prolog with encoding
* declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as
* identical.
*/
if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) {
String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH);
if (!pageDirEnc.equals(pageEnc)
&& (!pageDirEnc.startsWith("UTF-16") || !pageEnc
.startsWith("UTF-16"))) {
err.jspError(pageDir,
"jsp.error.prolog_pagedir_encoding_mismatch",
pageEnc, pageDirEnc);
}
}
}
}
/**
* A visitor for validating nodes other than page directives
*/
private static class ValidateVisitor extends Node.Visitor {
private final PageInfo pageInfo;
private final ErrorDispatcher err;
private final ClassLoader loader;
private final StringBuilder buf = new StringBuilder(32);
private static final JspUtil.ValidAttribute[] jspRootAttrs = {
new JspUtil.ValidAttribute("xsi:schemaLocation"),
new JspUtil.ValidAttribute("version", true) };
private static final JspUtil.ValidAttribute[] includeDirectiveAttrs = { new JspUtil.ValidAttribute(
"file", true) };
private static final JspUtil.ValidAttribute[] taglibDirectiveAttrs = {
new JspUtil.ValidAttribute("uri"),
new JspUtil.ValidAttribute("tagdir"),
new JspUtil.ValidAttribute("prefix", true) };
private static final JspUtil.ValidAttribute[] includeActionAttrs = {
new JspUtil.ValidAttribute("page", true),
new JspUtil.ValidAttribute("flush") };
private static final JspUtil.ValidAttribute[] paramActionAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("value", true) };
private static final JspUtil.ValidAttribute[] forwardActionAttrs = {
new JspUtil.ValidAttribute("page", true) };
private static final JspUtil.ValidAttribute[] getPropertyAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("property", true) };
private static final JspUtil.ValidAttribute[] setPropertyAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("property", true),
new JspUtil.ValidAttribute("value", false),
new JspUtil.ValidAttribute("param") };
private static final JspUtil.ValidAttribute[] useBeanAttrs = {
new JspUtil.ValidAttribute("id", true),
new JspUtil.ValidAttribute("scope"),
new JspUtil.ValidAttribute("class"),
new JspUtil.ValidAttribute("type"),
new JspUtil.ValidAttribute("beanName", false) };
private static final JspUtil.ValidAttribute[] plugInAttrs = {
new JspUtil.ValidAttribute("type", true),
new JspUtil.ValidAttribute("code", true),
new JspUtil.ValidAttribute("codebase"),
new JspUtil.ValidAttribute("align"),
new JspUtil.ValidAttribute("archive"),
new JspUtil.ValidAttribute("height", false),
new JspUtil.ValidAttribute("hspace"),
new JspUtil.ValidAttribute("jreversion"),
new JspUtil.ValidAttribute("name"),
new JspUtil.ValidAttribute("vspace"),
new JspUtil.ValidAttribute("width", false),
new JspUtil.ValidAttribute("nspluginurl"),
new JspUtil.ValidAttribute("iepluginurl") };
private static final JspUtil.ValidAttribute[] attributeAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("trim"),
new JspUtil.ValidAttribute("omit")};
private static final JspUtil.ValidAttribute[] invokeAttrs = {
new JspUtil.ValidAttribute("fragment", true),
new JspUtil.ValidAttribute("var"),
new JspUtil.ValidAttribute("varReader"),
new JspUtil.ValidAttribute("scope") };
private static final JspUtil.ValidAttribute[] doBodyAttrs = {
new JspUtil.ValidAttribute("var"),
new JspUtil.ValidAttribute("varReader"),
new JspUtil.ValidAttribute("scope") };
private static final JspUtil.ValidAttribute[] jspOutputAttrs = {
new JspUtil.ValidAttribute("omit-xml-declaration"),
new JspUtil.ValidAttribute("doctype-root-element"),
new JspUtil.ValidAttribute("doctype-public"),
new JspUtil.ValidAttribute("doctype-system") };
private final ExpressionFactory expressionFactory;
/*
* Constructor
*/
ValidateVisitor(Compiler compiler) {
this.pageInfo = compiler.getPageInfo();
this.err = compiler.getErrorDispatcher();
this.loader = compiler.getCompilationContext().getClassLoader();
// Get the cached EL expression factory for this context
expressionFactory =
JspFactory.getDefaultFactory().getJspApplicationContext(
compiler.getCompilationContext().getServletContext()).
getExpressionFactory();
}
@Override
public void visit(Node.JspRoot n) throws JasperException {
JspUtil.checkAttributes("Jsp:root", n, jspRootAttrs, err);
String version = n.getTextAttribute("version");
if (!version.equals("1.2") && !version.equals("2.0") &&
!version.equals("2.1") && !version.equals("2.2") &&
!version.equals("2.3")) {
err.jspError(n, "jsp.error.jsproot.version.invalid", version);
}
visitBody(n);
}
@Override
public void visit(Node.IncludeDirective n) throws JasperException {
JspUtil.checkAttributes("Include directive", n,
includeDirectiveAttrs, err);
visitBody(n);
}
@Override
public void visit(Node.TaglibDirective n) throws JasperException {
JspUtil.checkAttributes("Taglib directive", n,
taglibDirectiveAttrs, err);
// Either 'uri' or 'tagdir' attribute must be specified
String uri = n.getAttributeValue("uri");
String tagdir = n.getAttributeValue("tagdir");
if (uri == null && tagdir == null) {
err.jspError(n, "jsp.error.taglibDirective.missing.location");
}
if (uri != null && tagdir != null) {
err
.jspError(n,
"jsp.error.taglibDirective.both_uri_and_tagdir");
}
}
@Override
public void visit(Node.ParamAction n) throws JasperException {
JspUtil.checkAttributes("Param action", n, paramActionAttrs, err);
// make sure the value of the 'name' attribute is not a
// request-time expression
throwErrorIfExpression(n, "name", "jsp:param");
n.setValue(getJspAttribute(null, "value", null, null, n
.getAttributeValue("value"), n, false));
visitBody(n);
}
@Override
public void visit(Node.ParamsAction n) throws JasperException {
// Make sure we've got at least one nested jsp:param
Node.Nodes subElems = n.getBody();
if (subElems == null) {
err.jspError(n, "jsp.error.params.emptyBody");
}
visitBody(n);
}
@Override
public void visit(Node.IncludeAction n) throws JasperException {
JspUtil.checkAttributes("Include action", n, includeActionAttrs,
err);
n.setPage(getJspAttribute(null, "page", null, null, n
.getAttributeValue("page"), n, false));
visitBody(n);
}
@Override
public void visit(Node.ForwardAction n) throws JasperException {
JspUtil.checkAttributes("Forward", n, forwardActionAttrs, err);
n.setPage(getJspAttribute(null, "page", null, null, n
.getAttributeValue("page"), n, false));
visitBody(n);
}
@Override
public void visit(Node.GetProperty n) throws JasperException {
JspUtil.checkAttributes("GetProperty", n, getPropertyAttrs, err);
}
@Override
public void visit(Node.SetProperty n) throws JasperException {
JspUtil.checkAttributes("SetProperty", n, setPropertyAttrs, err);
String property = n.getTextAttribute("property");
String param = n.getTextAttribute("param");
String value = n.getAttributeValue("value");
n.setValue(getJspAttribute(null, "value", null, null, value,
n, false));
boolean valueSpecified = n.getValue() != null;
if ("*".equals(property)) {
if (param != null || valueSpecified)
err.jspError(n, "jsp.error.setProperty.invalid");
} else if (param != null && valueSpecified) {
err.jspError(n, "jsp.error.setProperty.invalid");
}
visitBody(n);
}
@Override
public void visit(Node.UseBean n) throws JasperException {
JspUtil.checkAttributes("UseBean", n, useBeanAttrs, err);
String name = n.getTextAttribute("id");
String scope = n.getTextAttribute("scope");
JspUtil.checkScope(scope, n, err);
String className = n.getTextAttribute("class");
String type = n.getTextAttribute("type");
BeanRepository beanInfo = pageInfo.getBeanRepository();
if (className == null && type == null)
err.jspError(n, "jsp.error.usebean.missingType");
if (beanInfo.checkVariable(name))
err.jspError(n, "jsp.error.usebean.duplicate");
if ("session".equals(scope) && !pageInfo.isSession())
err.jspError(n, "jsp.error.usebean.noSession");
Node.JspAttribute jattr = getJspAttribute(null, "beanName", null,
null, n.getAttributeValue("beanName"), n, false);
n.setBeanName(jattr);
if (className != null && jattr != null)
err.jspError(n, "jsp.error.usebean.notBoth");
if (className == null)
className = type;
beanInfo.addBean(n, name, className, scope);
visitBody(n);
}
@SuppressWarnings("null") // type can't be null after initial test
@Override
public void visit(Node.PlugIn n) throws JasperException {
JspUtil.checkAttributes("Plugin", n, plugInAttrs, err);
throwErrorIfExpression(n, "type", "jsp:plugin");
throwErrorIfExpression(n, "code", "jsp:plugin");
throwErrorIfExpression(n, "codebase", "jsp:plugin");
throwErrorIfExpression(n, "align", "jsp:plugin");
throwErrorIfExpression(n, "archive", "jsp:plugin");
throwErrorIfExpression(n, "hspace", "jsp:plugin");
throwErrorIfExpression(n, "jreversion", "jsp:plugin");
throwErrorIfExpression(n, "name", "jsp:plugin");
throwErrorIfExpression(n, "vspace", "jsp:plugin");
throwErrorIfExpression(n, "nspluginurl", "jsp:plugin");
throwErrorIfExpression(n, "iepluginurl", "jsp:plugin");
String type = n.getTextAttribute("type");
if (type == null)
err.jspError(n, "jsp.error.plugin.notype");
if (!type.equals("bean") && !type.equals("applet"))
err.jspError(n, "jsp.error.plugin.badtype");
if (n.getTextAttribute("code") == null)
err.jspError(n, "jsp.error.plugin.nocode");
Node.JspAttribute width = getJspAttribute(null, "width", null,
null, n.getAttributeValue("width"), n, false);
n.setWidth(width);
Node.JspAttribute height = getJspAttribute(null, "height", null,
null, n.getAttributeValue("height"), n, false);
n.setHeight(height);
visitBody(n);
}
@Override
public void visit(Node.NamedAttribute n) throws JasperException {
JspUtil.checkAttributes("Attribute", n, attributeAttrs, err);
n.setOmit(getJspAttribute(null, "omit", null, null, n
.getAttributeValue("omit"), n, true));
visitBody(n);
}
@Override
public void visit(Node.JspBody n) throws JasperException {
visitBody(n);
}
@Override
public void visit(Node.Declaration n) throws JasperException {
if (pageInfo.isScriptingInvalid()) {
err.jspError(n.getStart(), "jsp.error.no.scriptlets");
}
}
@Override
public void visit(Node.Expression n) throws JasperException {
if (pageInfo.isScriptingInvalid()) {
err.jspError(n.getStart(), "jsp.error.no.scriptlets");
}
}
@Override
public void visit(Node.Scriptlet n) throws JasperException {
if (pageInfo.isScriptingInvalid()) {
err.jspError(n.getStart(), "jsp.error.no.scriptlets");
}
}
@Override
public void visit(Node.ELExpression n) throws JasperException {
// exit if we are ignoring EL all together
if (pageInfo.isELIgnored())
return;
// JSP.2.2 - '#{' not allowed in template text
if (n.getType() == '#') {
if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) {
err.jspError(n, "jsp.error.el.template.deferred");
} else {
return;
}
}
// build expression
StringBuilder expr = this.getBuffer();
expr.append(n.getType()).append('{').append(n.getText())
.append('}');
ELNode.Nodes el = ELParser.parse(expr.toString(), pageInfo
.isDeferredSyntaxAllowedAsLiteral());
// validate/prepare expression
prepareExpression(el, n, expr.toString());
// store it
n.setEL(el);
}
@Override
public void visit(Node.UninterpretedTag n) throws JasperException {
if (n.getNamedAttributeNodes().size() != 0) {
err.jspError(n, "jsp.error.namedAttribute.invalidUse");
}
Attributes attrs = n.getAttributes();
if (attrs != null) {
int attrSize = attrs.getLength();
Node.JspAttribute[] jspAttrs = new Node.JspAttribute[attrSize];
for (int i = 0; i < attrSize; i++) {
// JSP.2.2 - '#{' not allowed in template text
String value = attrs.getValue(i);
if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) {
if (containsDeferredSyntax(value)) {
err.jspError(n, "jsp.error.el.template.deferred");
}
}
jspAttrs[i] = getJspAttribute(null, attrs.getQName(i),
attrs.getURI(i), attrs.getLocalName(i), value, n,
false);
}
n.setJspAttributes(jspAttrs);
}
visitBody(n);
}
/*
* Look for a #{ sequence that isn't preceded by \.
*/
private boolean containsDeferredSyntax(String value) {
if (value == null) {
return false;
}
int i = 0;
int len = value.length();
boolean prevCharIsEscape = false;
while (i < value.length()) {
char c = value.charAt(i);
if (c == '#' && (i+1) < len && value.charAt(i+1) == '{' && !prevCharIsEscape) {
return true;
} else if (c == '\\') {
prevCharIsEscape = true;
} else {
prevCharIsEscape = false;
}
i++;
}
return false;
}
@SuppressWarnings("null") // tagInfo can't be null after initial test
@Override
public void visit(Node.CustomTag n) throws JasperException {
TagInfo tagInfo = n.getTagInfo();
if (tagInfo == null) {
err.jspError(n, "jsp.error.missing.tagInfo", n.getQName());
}
/*
* The bodycontent of a SimpleTag cannot be JSP.
*/
if (n.implementsSimpleTag()
&& tagInfo.getBodyContent().equalsIgnoreCase(
TagInfo.BODY_CONTENT_JSP)) {
err.jspError(n, "jsp.error.simpletag.badbodycontent", tagInfo
.getTagClassName());
}
/*
* If the tag handler declares in the TLD that it supports dynamic
* attributes, it also must implement the DynamicAttributes
* interface.
*/
if (tagInfo.hasDynamicAttributes()
&& !n.implementsDynamicAttributes()) {
err.jspError(n, "jsp.error.dynamic.attributes.not.implemented",
n.getQName());
}
/*
* Make sure all required attributes are present, either as
* attributes or named attributes (<jsp:attribute>). Also make sure
* that the same attribute is not specified in both attributes or
* named attributes.
*/
TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
String customActionUri = n.getURI();
Attributes attrs = n.getAttributes();
int attrsSize = (attrs == null) ? 0 : attrs.getLength();
for (int i = 0; i < tldAttrs.length; i++) {
String attr = null;
if (attrs != null) {
attr = attrs.getValue(tldAttrs[i].getName());
if (attr == null) {
attr = attrs.getValue(customActionUri, tldAttrs[i]
.getName());
}
}
Node.NamedAttribute na = n.getNamedAttributeNode(tldAttrs[i]
.getName());
if (tldAttrs[i].isRequired() && attr == null && na == null) {
err.jspError(n, "jsp.error.missing_attribute", tldAttrs[i]
.getName(), n.getLocalName());
}
if (attr != null && na != null) {
err.jspError(n, "jsp.error.duplicate.name.jspattribute",
tldAttrs[i].getName());
}
}
Node.Nodes naNodes = n.getNamedAttributeNodes();
int jspAttrsSize = naNodes.size() + attrsSize;
Node.JspAttribute[] jspAttrs = null;
if (jspAttrsSize > 0) {
jspAttrs = new Node.JspAttribute[jspAttrsSize];
}
Hashtable<String, Object> tagDataAttrs = new Hashtable<>(attrsSize);
checkXmlAttributes(n, jspAttrs, tagDataAttrs);
checkNamedAttributes(n, jspAttrs, attrsSize, tagDataAttrs);
TagData tagData = new TagData(tagDataAttrs);
// JSP.C1: It is a (translation time) error for an action that
// has one or more variable subelements to have a TagExtraInfo
// class that returns a non-null object.
TagExtraInfo tei = tagInfo.getTagExtraInfo();
if (tei != null && tei.getVariableInfo(tagData) != null
&& tei.getVariableInfo(tagData).length > 0
&& tagInfo.getTagVariableInfos().length > 0) {
err.jspError("jsp.error.non_null_tei_and_var_subelems", n
.getQName());
}
n.setTagData(tagData);
n.setJspAttributes(jspAttrs);
visitBody(n);
}
@Override
public void visit(Node.JspElement n) throws JasperException {
Attributes attrs = n.getAttributes();
if (attrs == null) {
err.jspError(n, "jsp.error.jspelement.missing.name");
}
@SuppressWarnings("null") // Exception will have been thrown above
int xmlAttrLen = attrs.getLength();
Node.Nodes namedAttrs = n.getNamedAttributeNodes();
// XML-style 'name' attribute, which is mandatory, must not be
// included in JspAttribute array
int jspAttrSize = xmlAttrLen - 1 + namedAttrs.size();
Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize];
int jspAttrIndex = 0;
// Process XML-style attributes
for (int i = 0; i < xmlAttrLen; i++) {
if ("name".equals(attrs.getLocalName(i))) {
n.setNameAttribute(getJspAttribute(null, attrs.getQName(i),
attrs.getURI(i), attrs.getLocalName(i), attrs
.getValue(i), n, false));
} else {
if (jspAttrIndex < jspAttrSize) {
jspAttrs[jspAttrIndex++] = getJspAttribute(null, attrs
.getQName(i), attrs.getURI(i), attrs
.getLocalName(i), attrs.getValue(i), n, false);
}
}
}
if (n.getNameAttribute() == null) {
err.jspError(n, "jsp.error.jspelement.missing.name");
}
// Process named attributes
for (int i = 0; i < namedAttrs.size(); i++) {
Node.NamedAttribute na = (Node.NamedAttribute) namedAttrs
.getNode(i);
jspAttrs[jspAttrIndex++] = new Node.JspAttribute(na, null,
false);
}
n.setJspAttributes(jspAttrs);
visitBody(n);
}
@Override
public void visit(Node.JspOutput n) throws JasperException {
JspUtil.checkAttributes("jsp:output", n, jspOutputAttrs, err);
if (n.getBody() != null) {
err.jspError(n, "jsp.error.jspoutput.nonemptybody");
}
String omitXmlDecl = n.getAttributeValue("omit-xml-declaration");
String doctypeName = n.getAttributeValue("doctype-root-element");
String doctypePublic = n.getAttributeValue("doctype-public");
String doctypeSystem = n.getAttributeValue("doctype-system");
String omitXmlDeclOld = pageInfo.getOmitXmlDecl();
String doctypeNameOld = pageInfo.getDoctypeName();
String doctypePublicOld = pageInfo.getDoctypePublic();
String doctypeSystemOld = pageInfo.getDoctypeSystem();
if (omitXmlDecl != null && omitXmlDeclOld != null
&& !omitXmlDecl.equals(omitXmlDeclOld)) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"omit-xml-declaration", omitXmlDeclOld, omitXmlDecl);
}
if (doctypeName != null && doctypeNameOld != null
&& !doctypeName.equals(doctypeNameOld)) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"doctype-root-element", doctypeNameOld, doctypeName);
}
if (doctypePublic != null && doctypePublicOld != null
&& !doctypePublic.equals(doctypePublicOld)) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"doctype-public", doctypePublicOld, doctypePublic);
}
if (doctypeSystem != null && doctypeSystemOld != null
&& !doctypeSystem.equals(doctypeSystemOld)) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"doctype-system", doctypeSystemOld, doctypeSystem);
}
if (doctypeName == null && doctypeSystem != null
|| doctypeName != null && doctypeSystem == null) {
err.jspError(n, "jsp.error.jspoutput.doctypenamesystem");
}
if (doctypePublic != null && doctypeSystem == null) {
err.jspError(n, "jsp.error.jspoutput.doctypepulicsystem");
}
if (omitXmlDecl != null) {
pageInfo.setOmitXmlDecl(omitXmlDecl);
}
if (doctypeName != null) {
pageInfo.setDoctypeName(doctypeName);
}
if (doctypeSystem != null) {
pageInfo.setDoctypeSystem(doctypeSystem);
}
if (doctypePublic != null) {
pageInfo.setDoctypePublic(doctypePublic);
}
}
@Override
public void visit(Node.InvokeAction n) throws JasperException {
JspUtil.checkAttributes("Invoke", n, invokeAttrs, err);
String scope = n.getTextAttribute("scope");
JspUtil.checkScope(scope, n, err);
String var = n.getTextAttribute("var");
String varReader = n.getTextAttribute("varReader");
if (scope != null && var == null && varReader == null) {
err.jspError(n, "jsp.error.missing_var_or_varReader");
}
if (var != null && varReader != null) {
err.jspError(n, "jsp.error.var_and_varReader");
}
}
@Override
public void visit(Node.DoBodyAction n) throws JasperException {
JspUtil.checkAttributes("DoBody", n, doBodyAttrs, err);
String scope = n.getTextAttribute("scope");
JspUtil.checkScope(scope, n, err);
String var = n.getTextAttribute("var");
String varReader = n.getTextAttribute("varReader");
if (scope != null && var == null && varReader == null) {
err.jspError(n, "jsp.error.missing_var_or_varReader");
}
if (var != null && varReader != null) {
err.jspError(n, "jsp.error.var_and_varReader");
}
}
/*
* Make sure the given custom action does not have any invalid
* attributes.
*
* A custom action and its declared attributes always belong to the same
* namespace, which is identified by the prefix name of the custom tag
* invocation. For example, in this invocation:
*
* <my:test a="1" b="2" c="3"/>, the action
*
* "test" and its attributes "a", "b", and "c" all belong to the
* namespace identified by the prefix "my". The above invocation would
* be equivalent to:
*
* <my:test my:a="1" my:b="2" my:c="3"/>
*
* An action attribute may have a prefix different from that of the
* action invocation only if the underlying tag handler supports dynamic
* attributes, in which case the attribute with the different prefix is
* considered a dynamic attribute.
*/
private void checkXmlAttributes(Node.CustomTag n,
Node.JspAttribute[] jspAttrs, Hashtable<String, Object> tagDataAttrs)
throws JasperException {
TagInfo tagInfo = n.getTagInfo();
TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
Attributes attrs = n.getAttributes();
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
boolean found = false;
boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("%="))
|| (!n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("<%=")));
boolean elExpression = false;
boolean deferred = false;
double libraryVersion = Double.parseDouble(
tagInfo.getTagLibrary().getRequiredVersion());
boolean deferredSyntaxAllowedAsLiteral =
pageInfo.isDeferredSyntaxAllowedAsLiteral() ||
libraryVersion < 2.1;
ELNode.Nodes el = null;
if (!runtimeExpression && !pageInfo.isELIgnored()) {
el = ELParser.parse(attrs.getValue(i),
deferredSyntaxAllowedAsLiteral);
Iterator<ELNode> nodes = el.iterator();
while (nodes.hasNext()) {
ELNode node = nodes.next();
if (node instanceof ELNode.Root) {
if (((ELNode.Root) node).getType() == '$') {
if (elExpression && deferred) {
err.jspError(n,
"jsp.error.attribute.deferredmix");
}
elExpression = true;
} else if (((ELNode.Root) node).getType() == '#') {
if (elExpression && !deferred) {
err.jspError(n,
"jsp.error.attribute.deferredmix");
}
elExpression = true;
deferred = true;
}
}
}
}
boolean expression = runtimeExpression || elExpression;
for (int j = 0; tldAttrs != null && j < tldAttrs.length; j++) {
if (attrs.getLocalName(i).equals(tldAttrs[j].getName())
&& (attrs.getURI(i) == null
|| attrs.getURI(i).length() == 0 || attrs
.getURI(i).equals(n.getURI()))) {
TagAttributeInfo tldAttr = tldAttrs[j];
if (tldAttr.canBeRequestTime()
|| tldAttr.isDeferredMethod() || tldAttr.isDeferredValue()) { // JSP 2.1
if (!expression) {
String expectedType = null;
if (tldAttr.isDeferredMethod()) {
// The String literal must be castable to what is declared as type
// for the attribute
String m = tldAttr.getMethodSignature();
if (m != null) {
m = m.trim();
int rti = m.indexOf(' ');
if (rti > 0) {
expectedType = m.substring(0, rti).trim();
}
} else {
expectedType = "java.lang.Object";
}
if ("void".equals(expectedType)) {
// Can't specify a literal for a
// deferred method with an expected type
// of void - JSP.2.3.4
err.jspError(n,
"jsp.error.literal_with_void",
tldAttr.getName());
}
}
if (tldAttr.isDeferredValue()) {
// The String literal must be castable to what is declared as type
// for the attribute
expectedType = tldAttr.getExpectedTypeName();
}
if (expectedType != null) {
Class<?> expectedClass = String.class;
try {
expectedClass = JspUtil.toClass(expectedType, loader);
} catch (ClassNotFoundException e) {
err.jspError
(n, "jsp.error.unknown_attribute_type",
tldAttr.getName(), expectedType);
}
// Check casting - not possible for all types
if (String.class.equals(expectedClass) ||
expectedClass == Long.TYPE ||
expectedClass == Double.TYPE ||
expectedClass == Byte.TYPE ||
expectedClass == Short.TYPE ||
expectedClass == Integer.TYPE ||
expectedClass == Float.TYPE ||
Number.class.isAssignableFrom(expectedClass) ||
Character.class.equals(expectedClass) ||
Character.TYPE == expectedClass ||
Boolean.class.equals(expectedClass) ||
Boolean.TYPE == expectedClass ||
expectedClass.isEnum()) {
try {
expressionFactory.coerceToType(attrs.getValue(i), expectedClass);
} catch (Exception e) {
err.jspError
(n, "jsp.error.coerce_to_type",
tldAttr.getName(), expectedType, attrs.getValue(i));
}
}
}
jspAttrs[i] = new Node.JspAttribute(tldAttr,
attrs.getQName(i), attrs.getURI(i), attrs
.getLocalName(i),
attrs.getValue(i), false, null, false);
} else {
if (deferred && !tldAttr.isDeferredMethod() && !tldAttr.isDeferredValue()) {
// No deferred expressions allowed for this attribute
err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr",
tldAttr.getName());
}
if (!deferred && !tldAttr.canBeRequestTime()) {
// Only deferred expressions are allowed for this attribute
err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr",
tldAttr.getName());
}
if (elExpression) {
// El expression
validateFunctions(el, n);
jspAttrs[i] = new Node.JspAttribute(tldAttr,
attrs.getQName(i), attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i), false, el, false);
ELContextImpl ctx = new ELContextImpl(
expressionFactory);
ctx.setFunctionMapper(getFunctionMapper(el));
try {
jspAttrs[i].validateEL(this.pageInfo.getExpressionFactory(), ctx);
} catch (ELException e) {
this.err.jspError(n.getStart(),
"jsp.error.invalid.expression",
attrs.getValue(i), e.toString());
}
} else {
// Runtime expression
jspAttrs[i] = getJspAttribute(tldAttr,
attrs.getQName(i), attrs.getURI(i),
attrs.getLocalName(i), attrs
.getValue(i), n, false);
}
}
} else {
// Attribute does not accept any expressions.
// Make sure its value does not contain any.
if (expression) {
err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr",
tldAttr.getName());
}
jspAttrs[i] = new Node.JspAttribute(tldAttr,
attrs.getQName(i), attrs.getURI(i), attrs
.getLocalName(i),
attrs.getValue(i), false, null, false);
}
if (expression) {
tagDataAttrs.put(attrs.getQName(i),
TagData.REQUEST_TIME_VALUE);
} else {
tagDataAttrs.put(attrs.getQName(i), attrs
.getValue(i));
}
found = true;
break;
}
}
if (!found) {
if (tagInfo.hasDynamicAttributes()) {
jspAttrs[i] = getJspAttribute(null, attrs.getQName(i),
attrs.getURI(i), attrs.getLocalName(i), attrs
.getValue(i), n, true);
} else {
err.jspError(n, "jsp.error.bad_attribute", attrs
.getQName(i), n.getLocalName());
}
}
}
}
/*
* Make sure the given custom action does not have any invalid named
* attributes
*/
private void checkNamedAttributes(Node.CustomTag n,
Node.JspAttribute[] jspAttrs, int start,
Hashtable<String, Object> tagDataAttrs)
throws JasperException {
TagInfo tagInfo = n.getTagInfo();
TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
Node.Nodes naNodes = n.getNamedAttributeNodes();
for (int i = 0; i < naNodes.size(); i++) {
Node.NamedAttribute na = (Node.NamedAttribute) naNodes
.getNode(i);
boolean found = false;
for (int j = 0; j < tldAttrs.length; j++) {
/*
* See above comment about namespace matches. For named
* attributes, we use the prefix instead of URI as the match
* criterion, because in the case of a JSP document, we'd
* have to keep track of which namespaces are in scope when
* parsing a named attribute, in order to determine the URI
* that the prefix of the named attribute's name matches to.
*/
String attrPrefix = na.getPrefix();
if (na.getLocalName().equals(tldAttrs[j].getName())
&& (attrPrefix == null || attrPrefix.length() == 0 || attrPrefix
.equals(n.getPrefix()))) {
jspAttrs[start + i] = new Node.JspAttribute(na,
tldAttrs[j], false);
NamedAttributeVisitor nav = null;
if (na.getBody() != null) {
nav = new NamedAttributeVisitor();
na.getBody().visit(nav);
}
if (nav != null && nav.hasDynamicContent()) {
tagDataAttrs.put(na.getName(),
TagData.REQUEST_TIME_VALUE);
} else {
tagDataAttrs.put(na.getName(), na.getText());
}
found = true;
break;
}
}
if (!found) {
if (tagInfo.hasDynamicAttributes()) {
jspAttrs[start + i] = new Node.JspAttribute(na, null,
true);
} else {
err.jspError(n, "jsp.error.bad_attribute",
na.getName(), n.getLocalName());
}
}
}
}
/**
* Preprocess attributes that can be expressions. Expression delimiters
* are stripped.
* <p>
* If value is null, checks if there are any NamedAttribute subelements
* in the tree node, and if so, constructs a JspAttribute out of a child
* NamedAttribute node.
*/
private Node.JspAttribute getJspAttribute(TagAttributeInfo tai,
String qName, String uri, String localName, String value,
Node n, boolean dynamic)
throws JasperException {
Node.JspAttribute result = null;
// XXX Is it an error to see "%=foo%" in non-Xml page?
// (We won't see "<%=foo%> in xml page because '<' is not a
// valid attribute value in xml).
if (value != null) {
if (n.getRoot().isXmlSyntax() && value.startsWith("%=")) {
result = new Node.JspAttribute(tai, qName, uri, localName,
value.substring(2, value.length() - 1), true, null,
dynamic);
} else if (!n.getRoot().isXmlSyntax()
&& value.startsWith("<%=")) {
result = new Node.JspAttribute(tai, qName, uri, localName,
value.substring(3, value.length() - 2), true, null,
dynamic);
} else if (pageInfo.isELIgnored()) {
result = new Node.JspAttribute(tai, qName, uri, localName,
value, false, null, dynamic);
} else {
// The attribute can contain expressions but is not a
// scriptlet expression; thus, we want to run it through
// the expression interpreter
// validate expression syntax if string contains
// expression(s)
ELNode.Nodes el = ELParser.parse(value, pageInfo
.isDeferredSyntaxAllowedAsLiteral());
if (el.containsEL()) {
validateFunctions(el, n);
result = new Node.JspAttribute(tai, qName, uri,
localName, value, false, el, dynamic);
ELContextImpl ctx =
new ELContextImpl(expressionFactory);
ctx.setFunctionMapper(getFunctionMapper(el));
try {
result.validateEL(this.pageInfo
.getExpressionFactory(), ctx);
} catch (ELException e) {
this.err.jspError(n.getStart(),
"jsp.error.invalid.expression", value, e
.toString());
}
} else {
result = new Node.JspAttribute(tai, qName, uri,
localName, value, false, null, dynamic);
}
}
} else {
// Value is null. Check for any NamedAttribute subnodes
// that might contain the value for this attribute.
// Otherwise, the attribute wasn't found so we return null.
Node.NamedAttribute namedAttributeNode = n
.getNamedAttributeNode(qName);
if (namedAttributeNode != null) {
result = new Node.JspAttribute(namedAttributeNode, tai,
dynamic);
}
}
return result;
}
/*
* Return an empty StringBuilder [not thread-safe]
*/
private StringBuilder getBuffer() {
this.buf.setLength(0);
return this.buf;
}
/*
* Checks to see if the given attribute value represents a runtime or EL
* expression.
*/
private boolean isExpression(Node n, String value, boolean checkDeferred) {
boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && value.startsWith("%="))
|| (!n.getRoot().isXmlSyntax() && value.startsWith("<%=")));
boolean elExpression = false;
if (!runtimeExpression && !pageInfo.isELIgnored()) {
Iterator<ELNode> nodes = ELParser.parse(value,
pageInfo.isDeferredSyntaxAllowedAsLiteral()).iterator();
while (nodes.hasNext()) {
ELNode node = nodes.next();
if (node instanceof ELNode.Root) {
if (((ELNode.Root) node).getType() == '$') {
elExpression = true;
break;
} else if (checkDeferred && !pageInfo.isDeferredSyntaxAllowedAsLiteral()
&& ((ELNode.Root) node).getType() == '#') {
elExpression = true;
break;
}
}
}
}
return runtimeExpression || elExpression;
}
/*
* Throws exception if the value of the attribute with the given name in
* the given node is given as an RT or EL expression, but the spec
* requires a static value.
*/
private void throwErrorIfExpression(Node n, String attrName,
String actionName) throws JasperException {
if (n.getAttributes() != null
&& n.getAttributes().getValue(attrName) != null
&& isExpression(n, n.getAttributes().getValue(attrName), true)) {
err.jspError(n,
"jsp.error.attribute.standard.non_rt_with_expr",
attrName, actionName);
}
}
private static class NamedAttributeVisitor extends Node.Visitor {
private boolean hasDynamicContent;
@Override
public void doVisit(Node n) throws JasperException {
if (!(n instanceof Node.JspText)
&& !(n instanceof Node.TemplateText)) {
hasDynamicContent = true;
}
visitBody(n);
}
public boolean hasDynamicContent() {
return hasDynamicContent;
}
}
private String findUri(String prefix, Node n) {
for (Node p = n; p != null; p = p.getParent()) {
Attributes attrs = p.getTaglibAttributes();
if (attrs == null) {
continue;
}
for (int i = 0; i < attrs.getLength(); i++) {
String name = attrs.getQName(i);
int k = name.indexOf(':');
if (prefix == null && k < 0) {
// prefix not specified and a default ns found
return attrs.getValue(i);
}
if (prefix != null && k >= 0
&& prefix.equals(name.substring(k + 1))) {
return attrs.getValue(i);
}
}
}
return null;
}
/**
* Validate functions in EL expressions
*/
private void validateFunctions(ELNode.Nodes el, Node n)
throws JasperException {
class FVVisitor extends ELNode.Visitor {
private Node n;
FVVisitor(Node n) {
this.n = n;
}
@Override
public void visit(ELNode.Function func) throws JasperException {
String prefix = func.getPrefix();
String function = func.getName();
String uri = null;
if (n.getRoot().isXmlSyntax()) {
uri = findUri(prefix, n);
} else if (prefix != null) {
uri = pageInfo.getURI(prefix);
}
if (uri == null) {
if (prefix == null) {
err.jspError(n, "jsp.error.noFunctionPrefix",
function);
} else {
err.jspError(n, "jsp.error.attribute.invalidPrefix",
prefix);
}
}
TagLibraryInfo taglib = pageInfo.getTaglib(uri);
FunctionInfo funcInfo = null;
if (taglib != null) {
funcInfo = taglib.getFunction(function);
}
if (funcInfo == null) {
err.jspError(n, "jsp.error.noFunction", function);
}
// Skip TLD function uniqueness check. Done by Schema ?
func.setUri(uri);
func.setFunctionInfo(funcInfo);
processSignature(func);
}
}
el.visit(new FVVisitor(n));
}
private void prepareExpression(ELNode.Nodes el, Node n, String expr)
throws JasperException {
validateFunctions(el, n);
// test it out
ELContextImpl ctx = new ELContextImpl(expressionFactory);
ctx.setFunctionMapper(this.getFunctionMapper(el));
ExpressionFactory ef = this.pageInfo.getExpressionFactory();
try {
ef.createValueExpression(ctx, expr, Object.class);
} catch (ELException e) {
}
}
private void processSignature(ELNode.Function func)
throws JasperException {
func.setMethodName(getMethod(func));
func.setParameters(getParameters(func));
}
/**
* Get the method name from the signature.
*/
private String getMethod(ELNode.Function func) throws JasperException {
FunctionInfo funcInfo = func.getFunctionInfo();
String signature = funcInfo.getFunctionSignature();
int start = signature.indexOf(' ');
if (start < 0) {
err.jspError("jsp.error.tld.fn.invalid.signature", func
.getPrefix(), func.getName());
}
int end = signature.indexOf('(');
if (end < 0) {
err.jspError(
"jsp.error.tld.fn.invalid.signature.parenexpected",
func.getPrefix(), func.getName());
}
return signature.substring(start + 1, end).trim();
}
/**
* Get the parameters types from the function signature.
*
* @return An array of parameter class names
*/
private String[] getParameters(ELNode.Function func)
throws JasperException {
FunctionInfo funcInfo = func.getFunctionInfo();
String signature = funcInfo.getFunctionSignature();
ArrayList<String> params = new ArrayList<>();
// Signature is of the form
// <return-type> S <method-name S? '('
// < <arg-type> ( ',' <arg-type> )* )? ')'
int start = signature.indexOf('(') + 1;
boolean lastArg = false;
while (true) {
int p = signature.indexOf(',', start);
if (p < 0) {
p = signature.indexOf(')', start);
if (p < 0) {
err.jspError("jsp.error.tld.fn.invalid.signature", func
.getPrefix(), func.getName());
}
lastArg = true;
}
String arg = signature.substring(start, p).trim();
if (!"".equals(arg)) {
params.add(arg);
}
if (lastArg) {
break;
}
start = p + 1;
}
return params.toArray(new String[params.size()]);
}
private FunctionMapper getFunctionMapper(ELNode.Nodes el)
throws JasperException {
class ValidateFunctionMapper extends FunctionMapper {
private HashMap<String, Method> fnmap = new HashMap<>();
@Override
public void mapFunction(String prefix, String localName,
Method method) {
fnmap.put(prefix + ":" + localName, method);
}
@Override
public Method resolveFunction(String prefix, String localName) {
return this.fnmap.get(prefix + ":" + localName);
}
}
class MapperELVisitor extends ELNode.Visitor {
private ValidateFunctionMapper fmapper;
MapperELVisitor(ValidateFunctionMapper fmapper) {
this.fmapper = fmapper;
}
@SuppressWarnings("null") // c can't be null after catch block
@Override
public void visit(ELNode.Function n) throws JasperException {
Class<?> c = null;
Method method = null;
try {
c = loader.loadClass(n.getFunctionInfo()
.getFunctionClass());
} catch (ClassNotFoundException e) {
err.jspError("jsp.error.function.classnotfound", n
.getFunctionInfo().getFunctionClass(), n
.getPrefix()
+ ':' + n.getName(), e.getMessage());
}
String paramTypes[] = n.getParameters();
int size = paramTypes.length;
Class<?> params[] = new Class[size];
int i = 0;
try {
for (i = 0; i < size; i++) {
params[i] = JspUtil.toClass(paramTypes[i], loader);
}
method = c.getDeclaredMethod(n.getMethodName(), params);
} catch (ClassNotFoundException e) {
err.jspError("jsp.error.signature.classnotfound",
paramTypes[i], n.getPrefix() + ':'
+ n.getName(), e.getMessage());
} catch (NoSuchMethodException e) {
err.jspError("jsp.error.noFunctionMethod", n
.getMethodName(), n.getName(), c.getName());
}
fmapper.mapFunction(n.getPrefix(), n.getName(),
method);
}
}
ValidateFunctionMapper fmapper = new ValidateFunctionMapper();
el.visit(new MapperELVisitor(fmapper));
return fmapper;
}
} // End of ValidateVisitor
/**
* A visitor for validating TagExtraInfo classes of all tags
*/
private static class TagExtraInfoVisitor extends Node.Visitor {
private final ErrorDispatcher err;
/*
* Constructor
*/
TagExtraInfoVisitor(Compiler compiler) {
this.err = compiler.getErrorDispatcher();
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
TagInfo tagInfo = n.getTagInfo();
if (tagInfo == null) {
err.jspError(n, "jsp.error.missing.tagInfo", n.getQName());
}
@SuppressWarnings("null") // tagInfo can't be null here
ValidationMessage[] errors = tagInfo.validate(n.getTagData());
if (errors != null && errors.length != 0) {
StringBuilder errMsg = new StringBuilder();
errMsg.append("<h3>");
errMsg.append(Localizer.getMessage(
"jsp.error.tei.invalid.attributes", n.getQName()));
errMsg.append("</h3>");
for (int i = 0; i < errors.length; i++) {
errMsg.append("<p>");
if (errors[i].getId() != null) {
errMsg.append(errors[i].getId());
errMsg.append(": ");
}
errMsg.append(errors[i].getMessage());
errMsg.append("</p>");
}
err.jspError(n, errMsg.toString());
}
visitBody(n);
}
}
public static void validateDirectives(Compiler compiler, Node.Nodes page)
throws JasperException {
page.visit(new DirectiveVisitor(compiler));
}
public static void validateExDirectives(Compiler compiler, Node.Nodes page)
throws JasperException {
// Determine the default output content type
PageInfo pageInfo = compiler.getPageInfo();
String contentType = pageInfo.getContentType();
if (contentType == null || contentType.indexOf("charset=") < 0) {
boolean isXml = page.getRoot().isXmlSyntax();
String defaultType;
if (contentType == null) {
defaultType = isXml ? "text/xml" : "text/html";
} else {
defaultType = contentType;
}
String charset = null;
if (isXml) {
charset = "UTF-8";
} else {
if (!page.getRoot().isDefaultPageEncoding()) {
charset = page.getRoot().getPageEncoding();
}
}
if (charset != null) {
pageInfo.setContentType(defaultType + ";charset=" + charset);
} else {
pageInfo.setContentType(defaultType);
}
}
/*
* Validate all other nodes. This validation step includes checking a
* custom tag's mandatory and optional attributes against information in
* the TLD (first validation step for custom tags according to
* JSP.10.5).
*/
page.visit(new ValidateVisitor(compiler));
/*
* Invoke TagLibraryValidator classes of all imported tags (second
* validation step for custom tags according to JSP.10.5).
*/
validateXmlView(new PageDataImpl(page, compiler), compiler);
/*
* Invoke TagExtraInfo method isValid() for all imported tags (third
* validation step for custom tags according to JSP.10.5).
*/
page.visit(new TagExtraInfoVisitor(compiler));
}
// *********************************************************************
// Private (utility) methods
/**
* Validate XML view against the TagLibraryValidator classes of all imported
* tag libraries.
*/
private static void validateXmlView(PageData xmlView, Compiler compiler)
throws JasperException {
StringBuilder errMsg = null;
ErrorDispatcher errDisp = compiler.getErrorDispatcher();
for (Iterator<TagLibraryInfo> iter =
compiler.getPageInfo().getTaglibs().iterator(); iter.hasNext();) {
Object o = iter.next();
if (!(o instanceof TagLibraryInfoImpl))
continue;
TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o;
ValidationMessage[] errors = tli.validate(xmlView);
if ((errors != null) && (errors.length != 0)) {
if (errMsg == null) {
errMsg = new StringBuilder();
}
errMsg.append("<h3>");
errMsg.append(Localizer.getMessage(
"jsp.error.tlv.invalid.page", tli.getShortName(),
compiler.getPageInfo().getJspFile()));
errMsg.append("</h3>");
for (int i = 0; i < errors.length; i++) {
if (errors[i] != null) {
errMsg.append("<p>");
errMsg.append(errors[i].getId());
errMsg.append(": ");
errMsg.append(errors[i].getMessage());
errMsg.append("</p>");
}
}
}
}
if (errMsg != null) {
errDisp.jspError(errMsg.toString());
}
}
}
|
55,735
|
Bug 55735 Additional quote entity in html element attribute evaluated in tagx if attribute contains EL expression
| null |
resolved fixed
|
7ee1275
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-11-05T22:46:35Z
| 2013-11-02T11:00:00Z
|
java/org/apache/jasper/runtime/PageContextImpl.java
|
/*
* 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.jasper.runtime;
import java.io.IOException;
import java.io.Writer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import javax.el.ELContext;
import javax.el.ELException;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.el.ELContextImpl;
import org.apache.jasper.security.SecurityUtil;
/**
* Implementation of the PageContext class from the JSP spec. Also doubles as a
* VariableResolver for the EL.
*
* @author Anil K. Vijendran
* @author Larry Cable
* @author Hans Bergsten
* @author Pierre Delisle
* @author Mark Roth
* @author Jan Luehe
* @author Jacob Hookom
*/
public class PageContextImpl extends PageContext {
private static final JspFactory jspf = JspFactory.getDefaultFactory();
private BodyContentImpl[] outs;
private int depth;
// per-servlet state
private Servlet servlet;
private ServletConfig config;
private ServletContext context;
private JspApplicationContextImpl applicationContext;
private String errorPageURL;
// page-scope attributes
private final transient HashMap<String, Object> attributes;
// per-request state
private transient ServletRequest request;
private transient ServletResponse response;
private transient HttpSession session;
private transient ELContextImpl elContext;
private boolean isIncluded;
// initial output stream
private transient JspWriter out;
private transient JspWriterImpl baseOut;
/*
* Constructor.
*/
PageContextImpl() {
this.outs = new BodyContentImpl[0];
this.attributes = new HashMap<>(16);
this.depth = -1;
}
@Override
public void initialize(Servlet servlet, ServletRequest request,
ServletResponse response, String errorPageURL,
boolean needsSession, int bufferSize, boolean autoFlush)
throws IOException {
// initialize state
this.servlet = servlet;
this.config = servlet.getServletConfig();
this.context = config.getServletContext();
this.errorPageURL = errorPageURL;
this.request = request;
this.response = response;
// initialize application context
this.applicationContext = JspApplicationContextImpl.getInstance(context);
// Setup session (if required)
if (request instanceof HttpServletRequest && needsSession)
this.session = ((HttpServletRequest) request).getSession();
if (needsSession && session == null)
throw new IllegalStateException(
"Page needs a session and none is available");
// initialize the initial out ...
depth = -1;
if (this.baseOut == null) {
this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
} else {
this.baseOut.init(response, bufferSize, autoFlush);
}
this.out = baseOut;
// register names/values as per spec
setAttribute(OUT, this.out);
setAttribute(REQUEST, request);
setAttribute(RESPONSE, response);
if (session != null)
setAttribute(SESSION, session);
setAttribute(PAGE, servlet);
setAttribute(CONFIG, config);
setAttribute(PAGECONTEXT, this);
setAttribute(APPLICATION, context);
isIncluded = request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH) != null;
}
@Override
public void release() {
out = baseOut;
try {
if (isIncluded) {
((JspWriterImpl) out).flushBuffer();
// push it into the including jspWriter
} else {
// Old code:
// out.flush();
// Do not flush the buffer even if we're not included (i.e.
// we are the main page. The servlet will flush it and close
// the stream.
((JspWriterImpl) out).flushBuffer();
}
} catch (IOException ex) {
IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex);
throw ise;
} finally {
servlet = null;
config = null;
context = null;
applicationContext = null;
elContext = null;
errorPageURL = null;
request = null;
response = null;
depth = -1;
baseOut.recycle();
session = null;
attributes.clear();
for (BodyContentImpl body: outs) {
body.recycle();
}
}
}
@Override
public Object getAttribute(final String name) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(
new PrivilegedAction<Object>() {
@Override
public Object run() {
return doGetAttribute(name);
}
});
} else {
return doGetAttribute(name);
}
}
private Object doGetAttribute(String name) {
return attributes.get(name);
}
@Override
public Object getAttribute(final String name, final int scope) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(
new PrivilegedAction<Object>() {
@Override
public Object run() {
return doGetAttribute(name, scope);
}
});
} else {
return doGetAttribute(name, scope);
}
}
private Object doGetAttribute(String name, int scope) {
switch (scope) {
case PAGE_SCOPE:
return attributes.get(name);
case REQUEST_SCOPE:
return request.getAttribute(name);
case SESSION_SCOPE:
if (session == null) {
throw new IllegalStateException(Localizer
.getMessage("jsp.error.page.noSession"));
}
return session.getAttribute(name);
case APPLICATION_SCOPE:
return context.getAttribute(name);
default:
throw new IllegalArgumentException("Invalid scope");
}
}
@Override
public void setAttribute(final String name, final Object attribute) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
doSetAttribute(name, attribute);
return null;
}
});
} else {
doSetAttribute(name, attribute);
}
}
private void doSetAttribute(String name, Object attribute) {
if (attribute != null) {
attributes.put(name, attribute);
} else {
removeAttribute(name, PAGE_SCOPE);
}
}
@Override
public void setAttribute(final String name, final Object o, final int scope) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
doSetAttribute(name, o, scope);
return null;
}
});
} else {
doSetAttribute(name, o, scope);
}
}
private void doSetAttribute(String name, Object o, int scope) {
if (o != null) {
switch (scope) {
case PAGE_SCOPE:
attributes.put(name, o);
break;
case REQUEST_SCOPE:
request.setAttribute(name, o);
break;
case SESSION_SCOPE:
if (session == null) {
throw new IllegalStateException(Localizer
.getMessage("jsp.error.page.noSession"));
}
session.setAttribute(name, o);
break;
case APPLICATION_SCOPE:
context.setAttribute(name, o);
break;
default:
throw new IllegalArgumentException("Invalid scope");
}
} else {
removeAttribute(name, scope);
}
}
@Override
public void removeAttribute(final String name, final int scope) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
doRemoveAttribute(name, scope);
return null;
}
});
} else {
doRemoveAttribute(name, scope);
}
}
private void doRemoveAttribute(String name, int scope) {
switch (scope) {
case PAGE_SCOPE:
attributes.remove(name);
break;
case REQUEST_SCOPE:
request.removeAttribute(name);
break;
case SESSION_SCOPE:
if (session == null) {
throw new IllegalStateException(Localizer
.getMessage("jsp.error.page.noSession"));
}
session.removeAttribute(name);
break;
case APPLICATION_SCOPE:
context.removeAttribute(name);
break;
default:
throw new IllegalArgumentException("Invalid scope");
}
}
@Override
public int getAttributesScope(final String name) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
return (AccessController
.doPrivileged(new PrivilegedAction<Integer>() {
@Override
public Integer run() {
return Integer.valueOf(doGetAttributeScope(name));
}
})).intValue();
} else {
return doGetAttributeScope(name);
}
}
private int doGetAttributeScope(String name) {
if (attributes.get(name) != null)
return PAGE_SCOPE;
if (request.getAttribute(name) != null)
return REQUEST_SCOPE;
if (session != null) {
try {
if (session.getAttribute(name) != null)
return SESSION_SCOPE;
} catch(IllegalStateException ise) {
// Session has been invalidated.
// Ignore and fall through to application scope.
}
}
if (context.getAttribute(name) != null)
return APPLICATION_SCOPE;
return 0;
}
@Override
public Object findAttribute(final String name) {
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(
new PrivilegedAction<Object>() {
@Override
public Object run() {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
return doFindAttribute(name);
}
});
} else {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
return doFindAttribute(name);
}
}
private Object doFindAttribute(String name) {
Object o = attributes.get(name);
if (o != null)
return o;
o = request.getAttribute(name);
if (o != null)
return o;
if (session != null) {
try {
o = session.getAttribute(name);
} catch(IllegalStateException ise) {
// Session has been invalidated.
// Ignore and fall through to application scope.
}
if (o != null)
return o;
}
return context.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNamesInScope(final int scope) {
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(
new PrivilegedAction<Enumeration<String>>() {
@Override
public Enumeration<String> run() {
return doGetAttributeNamesInScope(scope);
}
});
} else {
return doGetAttributeNamesInScope(scope);
}
}
private Enumeration<String> doGetAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return Collections.enumeration(attributes.keySet());
case REQUEST_SCOPE:
return request.getAttributeNames();
case SESSION_SCOPE:
if (session == null) {
throw new IllegalStateException(Localizer
.getMessage("jsp.error.page.noSession"));
}
return session.getAttributeNames();
case APPLICATION_SCOPE:
return context.getAttributeNames();
default:
throw new IllegalArgumentException("Invalid scope");
}
}
@Override
public void removeAttribute(final String name) {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
doRemoveAttribute(name);
return null;
}
});
} else {
doRemoveAttribute(name);
}
}
private void doRemoveAttribute(String name) {
removeAttribute(name, PAGE_SCOPE);
removeAttribute(name, REQUEST_SCOPE);
if( session != null ) {
try {
removeAttribute(name, SESSION_SCOPE);
} catch(IllegalStateException ise) {
// Session has been invalidated.
// Ignore and fall throw to application scope.
}
}
removeAttribute(name, APPLICATION_SCOPE);
}
@Override
public JspWriter getOut() {
return out;
}
@Override
public HttpSession getSession() {
return session;
}
@Override
public ServletConfig getServletConfig() {
return config;
}
@Override
public ServletContext getServletContext() {
return config.getServletContext();
}
@Override
public ServletRequest getRequest() {
return request;
}
@Override
public ServletResponse getResponse() {
return response;
}
/**
* Returns the exception associated with this page context, if any. <p/>
* Added wrapping for Throwables to avoid ClassCastException: see Bugzilla
* 31171 for details.
*
* @return The Exception associated with this page context, if any.
*/
@Override
public Exception getException() {
Throwable t = JspRuntimeLibrary.getThrowable(request);
// Only wrap if needed
if ((t != null) && (!(t instanceof Exception))) {
t = new JspException(t);
}
return (Exception) t;
}
@Override
public Object getPage() {
return servlet;
}
private final String getAbsolutePathRelativeToContext(String relativeUrlPath) {
String path = relativeUrlPath;
if (!path.startsWith("/")) {
String uri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
if (uri == null)
uri = ((HttpServletRequest) request).getServletPath();
String baseURI = uri.substring(0, uri.lastIndexOf('/'));
path = baseURI + '/' + path;
}
return path;
}
@Override
public void include(String relativeUrlPath) throws ServletException,
IOException {
JspRuntimeLibrary
.include(request, response, relativeUrlPath, out, true);
}
@Override
public void include(final String relativeUrlPath, final boolean flush)
throws ServletException, IOException {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
doInclude(relativeUrlPath, flush);
return null;
}
});
} catch (PrivilegedActionException e) {
Exception ex = e.getException();
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
throw (ServletException) ex;
}
}
} else {
doInclude(relativeUrlPath, flush);
}
}
private void doInclude(String relativeUrlPath, boolean flush)
throws ServletException, IOException {
JspRuntimeLibrary.include(request, response, relativeUrlPath, out,
flush);
}
@Override
@Deprecated
public javax.servlet.jsp.el.VariableResolver getVariableResolver() {
return new org.apache.jasper.el.VariableResolverImpl(
this.getELContext());
}
@Override
public void forward(final String relativeUrlPath) throws ServletException,
IOException {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
doForward(relativeUrlPath);
return null;
}
});
} catch (PrivilegedActionException e) {
Exception ex = e.getException();
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
throw (ServletException) ex;
}
}
} else {
doForward(relativeUrlPath);
}
}
private void doForward(String relativeUrlPath) throws ServletException,
IOException {
// JSP.4.5 If the buffer was flushed, throw IllegalStateException
try {
out.clear();
baseOut.clear();
} catch (IOException ex) {
IllegalStateException ise = new IllegalStateException(Localizer
.getMessage("jsp.error.attempt_to_clear_flushed_buffer"));
ise.initCause(ex);
throw ise;
}
// Make sure that the response object is not the wrapper for include
while (response instanceof ServletResponseWrapperInclude) {
response = ((ServletResponseWrapperInclude) response).getResponse();
}
final String path = getAbsolutePathRelativeToContext(relativeUrlPath);
String includeUri = (String) request.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
if (includeUri != null)
request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
try {
context.getRequestDispatcher(path).forward(request, response);
} finally {
if (includeUri != null)
request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH,
includeUri);
}
}
@Override
public BodyContent pushBody() {
return (BodyContent) pushBody(null);
}
@Override
public JspWriter pushBody(Writer writer) {
depth++;
if (depth >= outs.length) {
BodyContentImpl[] newOuts = new BodyContentImpl[depth + 1];
for (int i = 0; i < outs.length; i++) {
newOuts[i] = outs[i];
}
newOuts[depth] = new BodyContentImpl(out);
outs = newOuts;
}
outs[depth].setWriter(writer);
out = outs[depth];
// Update the value of the "out" attribute in the page scope
// attribute namespace of this PageContext
setAttribute(OUT, out);
return outs[depth];
}
@Override
public JspWriter popBody() {
depth--;
if (depth >= 0) {
out = outs[depth];
} else {
out = baseOut;
}
// Update the value of the "out" attribute in the page scope
// attribute namespace of this PageContext
setAttribute(OUT, out);
return out;
}
/**
* Provides programmatic access to the ExpressionEvaluator. The JSP
* Container must return a valid instance of an ExpressionEvaluator that can
* parse EL expressions.
*/
@Override
@Deprecated
public javax.servlet.jsp.el.ExpressionEvaluator getExpressionEvaluator() {
return new org.apache.jasper.el.ExpressionEvaluatorImpl(
this.applicationContext.getExpressionFactory());
}
@Override
public void handlePageException(Exception ex) throws IOException,
ServletException {
// Should never be called since handleException() called with a
// Throwable in the generated servlet.
handlePageException((Throwable) ex);
}
@Override
public void handlePageException(final Throwable t) throws IOException,
ServletException {
if (t == null)
throw new NullPointerException("null Throwable");
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
doHandlePageException(t);
return null;
}
});
} catch (PrivilegedActionException e) {
Exception ex = e.getException();
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
throw (ServletException) ex;
}
}
} else {
doHandlePageException(t);
}
}
@SuppressWarnings("deprecation") // Still jave to support old JSP EL
private void doHandlePageException(Throwable t) throws IOException,
ServletException {
if (errorPageURL != null && !errorPageURL.equals("")) {
/*
* Set request attributes. Do not set the
* javax.servlet.error.exception attribute here (instead, set in the
* generated servlet code for the error page) in order to prevent
* the ErrorReportValve, which is invoked as part of forwarding the
* request to the error page, from throwing it if the response has
* not been committed (the response will have been committed if the
* error page is a JSP page).
*/
request.setAttribute(PageContext.EXCEPTION, t);
request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE,
new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
((HttpServletRequest) request).getRequestURI());
request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME,
config.getServletName());
try {
forward(errorPageURL);
} catch (IllegalStateException ise) {
include(errorPageURL);
}
// The error page could be inside an include.
Object newException =
request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
// t==null means the attribute was not set.
if ((newException != null) && (newException == t)) {
request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION);
}
// now clear the error code - to prevent double handling.
request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE);
request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI);
request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME);
request.removeAttribute(PageContext.EXCEPTION);
} else {
// Otherwise throw the exception wrapped inside a ServletException.
// Set the exception as the root cause in the ServletException
// to get a stack trace for the real problem
if (t instanceof IOException)
throw (IOException) t;
if (t instanceof ServletException)
throw (ServletException) t;
if (t instanceof RuntimeException)
throw (RuntimeException) t;
Throwable rootCause = null;
if (t instanceof JspException || t instanceof ELException ||
t instanceof javax.servlet.jsp.el.ELException) {
rootCause =t.getCause();
}
if (rootCause != null) {
throw new ServletException(t.getClass().getName() + ": "
+ t.getMessage(), rootCause);
}
throw new ServletException(t);
}
}
protected static String XmlEscape(String s) {
if (s == null) {
return null;
}
int len = s.length();
/*
* Look for any "bad" characters, Escape "bad" character was found
*/
// ASCII " 34 & 38 ' 39 < 60 > 62
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= '\"' && c <= '>' &&
(c == '<' || c == '>' || c == '\'' || c == '&' || c == '"')) {
// need to escape them and then quote the whole string
StringBuilder sb = new StringBuilder((int) (len * 1.2));
sb.append(s, 0, i);
int pos = i + 1;
for (int j = i; j < len; j++) {
c = s.charAt(j);
if (c >= '\"' && c <= '>') {
if (c == '<') {
if (j > pos) {
sb.append(s, pos, j);
}
sb.append("<");
pos = j + 1;
} else if (c == '>') {
if (j > pos) {
sb.append(s, pos, j);
}
sb.append(">");
pos = j + 1;
} else if (c == '\'') {
if (j > pos) {
sb.append(s, pos, j);
}
sb.append("'"); // '
pos = j + 1;
} else if (c == '&') {
if (j > pos) {
sb.append(s, pos, j);
}
sb.append("&");
pos = j + 1;
} else if (c == '"') {
if (j > pos) {
sb.append(s, pos, j);
}
sb.append("""); // "
pos = j + 1;
}
}
}
if (pos < len) {
sb.append(s, pos, len);
}
return sb.toString();
}
}
return s;
}
/**
* Proprietary method to evaluate EL expressions. XXX - This method should
* go away once the EL interpreter moves out of JSTL and into its own
* project. For now, this is necessary because the standard machinery is too
* slow.
*
* @param expression
* The expression to be evaluated
* @param expectedType
* The expected resulting type
* @param pageContext
* The page context
* @param functionMap
* Maps prefix and name to Method
* @return The result of the evaluation
*/
public static Object proprietaryEvaluate(final String expression,
final Class<?> expectedType, final PageContext pageContext,
final ProtectedFunctionMapper functionMap, final boolean escape)
throws ELException {
Object retValue;
final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory();
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
retValue = AccessController
.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
ELContextImpl ctx = (ELContextImpl) pageContext.getELContext();
ctx.setFunctionMapper(functionMap);
ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType);
return ve.getValue(ctx);
}
});
} catch (PrivilegedActionException ex) {
Exception realEx = ex.getException();
if (realEx instanceof ELException) {
throw (ELException) realEx;
} else {
throw new ELException(realEx);
}
}
} else {
ELContextImpl ctx = (ELContextImpl) pageContext.getELContext();
ctx.setFunctionMapper(functionMap);
ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType);
retValue = ve.getValue(ctx);
}
if (escape && retValue != null) {
retValue = XmlEscape(retValue.toString());
}
return retValue;
}
@Override
public ELContext getELContext() {
if (this.elContext == null) {
this.elContext = this.applicationContext.createELContext(this);
}
return this.elContext;
}
}
|
55,735
|
Bug 55735 Additional quote entity in html element attribute evaluated in tagx if attribute contains EL expression
| null |
resolved fixed
|
7ee1275
|
Tomcat
|
https://github.com/apache/tomcat
|
apache/tomcat
|
java
| null | null | null | 2013-11-05T22:46:35Z
| 2013-11-02T11:00:00Z
|
test/org/apache/jasper/compiler/TestParser.java
|
/*
* 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.jasper.compiler;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
/**
* Tests are duplicated in {@link TestParserNoStrictWhitespace} with the strict
* whitespace parsing disabled.
*/
public class TestParser extends TomcatBaseTest {
@Test
public void testBug48627() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir =
new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug48nnn/bug48627.jsp");
String result = res.toString();
// Beware of the differences between escaping in JSP attributes and
// in Java Strings
assertEcho(result, "00-\\");
assertEcho(result, "01-\\");
}
@Test
public void testBug48668a() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir =
new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug48nnn/bug48668a.jsp");
String result = res.toString();
assertEcho(result, "00-Hello world</p>#{foo.bar}");
assertEcho(result, "01-Hello world</p>${foo.bar}");
assertEcho(result, "10-Hello ${'foo.bar}");
assertEcho(result, "11-Hello ${'foo.bar}");
assertEcho(result, "12-Hello #{'foo.bar}");
assertEcho(result, "13-Hello #{'foo.bar}");
assertEcho(result, "14-Hello ${'foo}");
assertEcho(result, "15-Hello ${'foo}");
assertEcho(result, "16-Hello #{'foo}");
assertEcho(result, "17-Hello #{'foo}");
assertEcho(result, "18-Hello ${'foo.bar}");
assertEcho(result, "19-Hello ${'foo.bar}");
assertEcho(result, "20-Hello #{'foo.bar}");
assertEcho(result, "21-Hello #{'foo.bar}");
assertEcho(result, "30-Hello ${'foo}");
assertEcho(result, "31-Hello ${'foo}");
assertEcho(result, "32-Hello #{'foo}");
assertEcho(result, "33-Hello #{'foo}");
assertEcho(result, "34-Hello ${'foo}");
assertEcho(result, "35-Hello ${'foo}");
assertEcho(result, "36-Hello #{'foo}");
assertEcho(result, "37-Hello #{'foo}");
assertEcho(result, "40-Hello ${'foo}");
assertEcho(result, "41-Hello ${'foo}");
assertEcho(result, "42-Hello #{'foo}");
assertEcho(result, "43-Hello #{'foo}");
assertEcho(result, "50-Hello ${'foo}");
assertEcho(result, "51-Hello ${'foo}");
assertEcho(result, "52-Hello #{'foo}");
assertEcho(result, "53-Hello #{'foo}");
}
@Test
public void testBug48668b() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug48nnn/bug48668b.jsp");
String result = res.toString();
assertEcho(result, "00-Hello world</p>#{foo.bar}");
assertEcho(result, "01-Hello world</p>#{foo2");
}
@Test
public void testBug49297NoSpaceStrict() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297NoSpace.jsp", new ByteChunk(),
new HashMap<String,List<String>>());
assertEquals(500, sc);
}
@Test
public void testBug49297DuplicateAttr() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297DuplicateAttr.jsp", new ByteChunk(),
new HashMap<String,List<String>>());
assertEquals(500, sc);
}
@Test
public void testBug49297MultipleImport1() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297MultipleImport1.jsp", res,
new HashMap<String,List<String>>());
assertEquals(200, sc);
assertEcho(res.toString(), "OK");
}
@Test
public void testBug49297MultipleImport2() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297MultipleImport2.jsp", res,
new HashMap<String,List<String>>());
assertEquals(200, sc);
assertEcho(res.toString(), "OK");
}
@Test
public void testBug49297MultiplePageEncoding1() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297MultiplePageEncoding1.jsp", res,
new HashMap<String,List<String>>());
assertEquals(500, sc);
}
@Test
public void testBug49297MultiplePageEncoding2() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297MultiplePageEncoding2.jsp", res,
new HashMap<String,List<String>>());
assertEquals(500, sc);
}
@Test
public void testBug49297MultiplePageEncoding3() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297MultiplePageEncoding3.jsp", res,
new HashMap<String,List<String>>());
assertEquals(500, sc);
}
@Test
public void testBug49297MultiplePageEncoding4() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297MultiplePageEncoding4.jsp", res,
new HashMap<String,List<String>>());
assertEquals(500, sc);
}
@Test
public void testBug49297Tag() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int sc = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49297Tag.jsp", res,
new HashMap<String,List<String>>());
assertEquals(200, sc);
assertEcho(res.toString(), "OK");
}
@Test
public void testBug52335() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir =
new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug5nnnn/bug52335.jsp");
String result = res.toString();
// Beware of the differences between escaping in JSP attributes and
// in Java Strings
assertEcho(result, "00 - \\% \\\\% <%");
assertEcho(result, "01 - <b><%</b>");
assertEcho(result, "02 - <p>Foo</p><%");
}
@Test
public void testBug55198() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug5nnnn/bug55198.jsp");
String result = res.toString();
Assert.assertTrue(result.contains(""bar"") ||
result.contains(""bar""));
Assert.assertTrue(result.contains(""foo"") ||
result.contains(""foo""));
}
/** Assertion for text printed by tags:echo */
private static void assertEcho(String result, String expected) {
assertTrue(result.indexOf("<p>" + expected + "</p>") > 0);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.