下面列出了javax.servlet.http.HttpSessionAttributeListener#org.apache.tomcat.util.ExceptionUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String getClasspath( ClassLoader loader ) {
try {
Method m=loader.getClass().getMethod("getClasspath", new Class[] {});
if( log.isTraceEnabled())
log.trace("getClasspath " + m );
if( m==null ) return null;
Object o=m.invoke( loader, new Object[] {} );
if( log.isDebugEnabled() )
log.debug("gotClasspath " + o);
if( o instanceof String )
return (String)o;
return null;
} catch( Exception ex ) {
Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex);
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled())
log.debug("getClasspath ", ex);
}
return null;
}
@Override
@SuppressWarnings("unchecked") // doPrivileged() returns the correct type
public <T extends EventListener> T createListener(Class<T> c)
throws ServletException {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
return (T) invokeMethod(context, "createListener",
new Object[]{c});
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (t instanceof ServletException) {
throw (ServletException) t;
}
return null;
}
} else {
return context.createListener(c);
}
}
@Override
public void init() throws ServletException {
// Ensure that our ContainerServlet properties have been set
if ((wrapper == null) || (context == null))
throw new UnavailableException
(sm.getString("hostManagerServlet.noWrapper"));
// Set our properties from the initialization parameters
String value = null;
try {
value = getServletConfig().getInitParameter("debug");
debug = Integer.parseInt(value);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
public static void main(String[] args) throws Exception {
WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();
int testCaseCount = getTestCaseCount(wsc);
System.out.println("There are " + testCaseCount + " test cases");
for (int testCase = 1; testCase <= testCaseCount; testCase++) {
if (testCase % 50 == 0) {
System.out.println(testCase);
} else {
System.out.print('.');
}
try {
executeTestCase(wsc, testCase);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
t.printStackTrace();
}
}
System.out.println("Testing complete");
updateReports(wsc);
}
@Override
public void addHeader(String name, String value) {
super.addHeader(name, value);
String lname = name.toLowerCase(Locale.ENGLISH);
if (lname.equals(LAST_MODIFIED)) {
try {
synchronized(RFC1123_FORMAT) {
lastModified = RFC1123_FORMAT.parse(value).getTime();
}
} catch (Throwable ignore) {
ExceptionUtils.handleThrowable(ignore);
}
} else if (lname.equals(CONTENT_TYPE)) {
contentType = value;
}
}
private void fireEndpointOnClose(CloseReason closeReason) {
// Fire the onClose event
InstanceManager instanceManager = webSocketContainer.getInstanceManager();
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
localEndpoint.onClose(this, closeReason);
if (instanceManager != null) {
instanceManager.destroyInstance(localEndpoint);
}
} catch (Throwable throwable) {
ExceptionUtils.handleThrowable(throwable);
localEndpoint.onError(this, throwable);
} finally {
t.setContextClassLoader(cl);
}
}
/**
* 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 {
super.startInternal();
// Load unloaded sessions, if any
try {
load();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("standardManager.managerLoad"), t);
}
setState(LifecycleState.STARTING);
}
/**
* Use reflection to invoke the requested method. Cache the method object
* to speed up the process
* @param methodName The method to invoke.
* @param clazz The class where the method is.
* @param params The arguments passed to the called method.
*/
private Object doPrivileged(final String methodName,
final Class<?>[] clazz,
Object[] params) {
try{
Method method = context.getClass().getMethod(methodName, clazz);
return executeMethod(method,context,params);
} catch (Exception ex){
try {
handleException(ex);
} catch (Throwable t){
ExceptionUtils.handleThrowable(t);
throw new RuntimeException(t.getMessage());
}
return null;
} finally {
params = null;
}
}
/**
* Construct a new CharsetMapper using the specified properties resource.
*
* @param name Name of a properties resource to be loaded
*
* @exception IllegalArgumentException if the specified properties
* resource could not be loaded for any reason.
*/
public CharsetMapper(String name) {
InputStream stream = null;
try {
stream = this.getClass().getResourceAsStream(name);
map.load(stream);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
throw new IllegalArgumentException(t.toString());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
/**
* Move a current but rotated log file back to the unrotated
* one. Needed if date stamp inclusion is deferred to rotation
* time.
*/
private void restore() {
File newLogFile = getLogFile(false);
File rotatedLogFile = getLogFile(true);
if (rotatedLogFile.exists() && !newLogFile.exists() &&
!rotatedLogFile.equals(newLogFile)) {
try {
if (!rotatedLogFile.renameTo(newLogFile)) {
log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile));
}
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile), e);
}
}
}
/**
* Initialize this servlet.
*/
@Override
public void init() throws ServletException {
// Ensure that our ContainerServlet properties have been set
if ((wrapper == null) || (context == null))
throw new UnavailableException
(sm.getString("hostManagerServlet.noWrapper"));
// Set our properties from the initialization parameters
String value = null;
try {
value = getServletConfig().getInitParameter("debug");
debug = Integer.parseInt(value);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
}
/**
* Process a new connection from a new client. Wraps the socket so
* keep-alive and other attributes can be tracked and then passes the socket
* to the executor for processing.
*
* @param socket The socket associated with the client.
*
* @return <code>true</code> if the socket is passed to the
* executor, <code>false</code> if something went wrong or
* if the endpoint is shutting down. Returning
* <code>false</code> is an indication to close the socket
* immediately.
*/
protected boolean processSocket(Socket socket) {
// Process the request from this socket
try {
SocketWrapper<Socket> wrapper = new SocketWrapper<Socket>(socket);
wrapper.setKeepAliveLeft(getMaxKeepAliveRequests());
wrapper.setSecure(isSSLEnabled());
// During shutdown, executor may be null - avoid NPE
if (!running) {
return false;
}
getExecutor().execute(new SocketProcessor(wrapper));
} catch (RejectedExecutionException x) {
log.warn("Socket processing request was rejected for:"+socket,x);
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;
}
/**
* @deprecated As of Java Servlet API 2.1, with no direct replacement.
*/
@Override
@Deprecated
public Servlet getServlet(String name)
throws ServletException {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
return (Servlet) invokeMethod(context, "getServlet",
new Object[]{name});
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (t instanceof ServletException) {
throw (ServletException) t;
}
return null;
}
} else {
return context.getServlet(name);
}
}
public static void main(String[] args) throws Exception {
WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();
int testCaseCount = getTestCaseCount(wsc);
System.out.println("There are " + testCaseCount + " test cases");
for (int testCase = 1; testCase <= testCaseCount; testCase++) {
if (testCase % 50 == 0) {
System.out.println(testCase);
} else {
System.out.print('.');
}
try {
executeTestCase(wsc, testCase);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
t.printStackTrace();
}
}
System.out.println("Testing complete");
updateReports(wsc);
}
@Override
@SuppressWarnings("unchecked") // doPrivileged() returns the correct type
public <T extends Filter> T createFilter(Class<T> c)
throws ServletException {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
return (T) invokeMethod(context, "createFilter",
new Object[]{c});
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (t instanceof ServletException) {
throw (ServletException) t;
}
return null;
}
} else {
return context.createFilter(c);
}
}
@Override
@SuppressWarnings("unchecked") // doPrivileged() returns the correct type
public <T extends Filter> T createFilter(Class<T> c)
throws ServletException {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
return (T) invokeMethod(context, "createFilter",
new Object[]{c});
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (t instanceof ServletException) {
throw (ServletException) t;
}
return null;
}
} else {
return context.createFilter(c);
}
}
/**
* @return <code>true</code> if the specified class name represents a
* container provided servlet class that should be loaded by the
* server class loader.
*
* @param classname Name of the class to be checked
*
* @deprecated Unused. Will be removed in Tomcat 9
*/
@Deprecated
protected boolean isContainerProvidedServlet(String classname) {
if (classname.startsWith("org.apache.catalina.")) {
return true;
}
try {
Class<?> clazz =
this.getClass().getClassLoader().loadClass(classname);
return (ContainerServlet.class.isAssignableFrom(clazz));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
return false;
}
}
@Override
public void fireOnComplete() {
if (log.isDebugEnabled()) {
log.debug(sm.getString("asyncContextImpl.fireOnComplete"));
}
List<AsyncListenerWrapper> listenersCopy = new ArrayList<>();
listenersCopy.addAll(listeners);
ClassLoader oldCL = context.bind(Globals.IS_SECURITY_ENABLED, null);
try {
for (AsyncListenerWrapper listener : listenersCopy) {
try {
listener.fireOnComplete(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.warn(sm.getString("asyncContextImpl.onCompleteError",
listener.getClass().getName()), t);
}
}
} finally {
context.fireRequestDestroyEvent(request.getRequest());
clearServletRequestResponse();
this.context.decrementInProgressAsyncCount();
context.unbind(Globals.IS_SECURITY_ENABLED, oldCL);
}
}
/**
* 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 {
super.startInternal();
// Load unloaded sessions, if any
try {
load();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("standardManager.managerLoad"), t);
}
setState(LifecycleState.STARTING);
}
/**
* Return <code>true</code> if the specified class name represents a
* container provided servlet class that should be loaded by the
* server class loader.
*
* @param classname Name of the class to be checked
*/
protected boolean isContainerProvidedServlet(String classname) {
if (classname.startsWith("org.apache.catalina.")) {
return (true);
}
try {
Class<?> clazz =
this.getClass().getClassLoader().loadClass(classname);
return (ContainerServlet.class.isAssignableFrom(clazz));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
return (false);
}
}
private void flushInternal(boolean block, boolean updateFlushing) throws IOException {
try {
synchronized (writeLock) {
if (updateFlushing) {
flushing = socketWrapper.flush(block);
if (flushing) {
socketWrapper.registerWriteInterest();
}
} else {
socketWrapper.flush(block);
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
onError(t);
if (t instanceof IOException) {
throw (IOException) t;
} else {
throw new IOException(t);
}
}
}
private final void onError(Throwable t) {
if (listener == null) {
return;
}
ClassLoader oldCL = processor.getUpgradeToken().getContextBind().bind(false, null);
try {
listener.onError(t);
} catch (Throwable t2) {
ExceptionUtils.handleThrowable(t2);
log.warn(sm.getString("upgrade.sos.onErrorFail"), t2);
} finally {
processor.getUpgradeToken().getContextBind().unbind(false, oldCL);
}
try {
close();
} catch (IOException ioe) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("upgrade.sos.errorCloseFail"), ioe);
}
}
}
@Override
public final void onError(Session session, Throwable throwable) {
if (methodMapping.getOnError() == null) {
log.error(sm.getString("pojoEndpointBase.onError",
pojo.getClass().getName()), throwable);
} else {
try {
methodMapping.getOnError().invoke(
pojo,
methodMapping.getOnErrorArgs(pathParameters, session,
throwable));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("pojoEndpointBase.onErrorFail",
pojo.getClass().getName()), t);
}
}
}
/**
* Configure the socket.
*/
protected boolean setSocketOptions(Socket socket) {
try {
// 1: Set socket options: timeout, linger, etc
socketProperties.setProperties(socket);
} catch (SocketException s) {
//error here is common if the client has reset the connection
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.err.unexpected"), s);
}
// Close the socket
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("endpoint.err.unexpected"), t);
// Close the socket
return false;
}
return true;
}
/**
* Rename the existing log file to something else. Then open the
* old log file name up once again. Intended to be called by a JMX
* agent.
*
*
* @param newFileName The file name to move the log file entry to
* @return true if a file was rotated with no error
*/
public synchronized boolean rotate(String newFileName) {
if (currentLogFile != null) {
File holder = currentLogFile;
close(false);
try {
holder.renameTo(new File(newFileName));
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("accessLogValve.rotateFail"), e);
}
/* Make sure date is correct */
dateStamp = fileDateFormatter.format(
new Date(System.currentTimeMillis()));
open();
return true;
} else {
return false;
}
}
/**
* 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 {
super.startInternal();
// Load unloaded sessions, if any
try {
if (cluster == null) {
log.error(sm.getString("deltaManager.noCluster", getName()));
return;
} else {
if (log.isInfoEnabled()) {
String type = "unknown" ;
if( cluster.getContainer() instanceof Host){
type = "Host" ;
} else if( cluster.getContainer() instanceof Engine){
type = "Engine" ;
}
log.info(sm.getString("deltaManager.registerCluster",
getName(), type, cluster.getClusterName()));
}
}
if (log.isInfoEnabled()) {
log.info(sm.getString("deltaManager.startClustering", getName()));
}
getAllClusterSessions();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("deltaManager.managerLoad"), t);
}
setState(LifecycleState.STARTING);
}
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();
}
}
/**
* Close the specified database connection.
*/
protected void close() {
// Do nothing if the database connection is already closed
if (conn == null) {
return;
}
// Close our prepared statements (if any)
try {
ps.close();
} catch (Throwable f) {
ExceptionUtils.handleThrowable(f);
}
this.ps = null;
// Close this database connection, and log any errors
try {
conn.close();
} catch (SQLException e) {
container.getLogger().error(sm.getString("jdbcAccessLogValve.close"), e); // Just log it here
} finally {
this.conn = null;
}
}
/**
* 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() {
// 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 (InputStream is = getResourceAsStream(
"org/apache/catalina/loader/JdbcLeakPrevention.class")) {
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.getConstructor().newInstance();
@SuppressWarnings("unchecked")
List<String> driverNames = (List<String>) obj.getClass().getMethod(
"clearJdbcDriverRegistrations").invoke(obj);
for (String name : driverNames) {
log.warn(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);
}
}
public void setStarted(Context context, ServletRequest request,
ServletResponse response, boolean originalRequestResponse) {
synchronized (asyncContextLock) {
this.request.getCoyoteRequest().action(
ActionCode.ASYNC_START, this);
this.context = context;
this.servletRequest = request;
this.servletResponse = response;
this.hasOriginalRequestAndResponse = originalRequestResponse;
this.event = new AsyncEvent(this, request, response);
List<AsyncListenerWrapper> listenersCopy =
new ArrayList<AsyncListenerWrapper>();
listenersCopy.addAll(listeners);
listeners.clear();
for (AsyncListenerWrapper listener : listenersCopy) {
try {
listener.fireOnStartAsync(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.warn("onStartAsync() failed for listener of type [" +
listener.getClass().getName() + "]", t);
}
}
}
}