Fix for #304803 (Remove TypeUtil Integer and Long caches).

git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk@1744 7e9141cc-0065-0410-87d8-b60c137991c4
This commit is contained in:
Simone Bordet 2010-05-10 15:12:34 +00:00
parent bcebcb329f
commit c3d31d68b0
11 changed files with 399 additions and 526 deletions

View File

@ -1,9 +1,12 @@
jetty-7.1.1-SNAPSHOT
+ 304803 Remove TypeUtil Integer and Long caches
jetty-7.1.0 5 May 2010
+ 306353 fixed cross context dispatch to root context.
+ 311154 Added deprecated StringBuffer API for backwards compatibility
+ 311554 Protect shutdown thread from Server#doStop
jetty-7.1.0.RC1-SNAPSHOT
jetty-7.1.0.RC1 5 May 2010
+ 286889 Allow System and Server classes to be set on Server instance and when applied to all webapps
+ 291448 SessionManager has isCheckingRemoteSessionIdEncoding
+ 296650 JETTY-1198 reset idle timeout on request body chunks

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.ajp;
@ -28,13 +28,12 @@ import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
/**
*
*
*/
*
*
*/
public class Ajp13Generator extends AbstractGenerator
{
private static HashMap __headerHash = new HashMap();
@ -121,7 +120,7 @@ public class Ajp13Generator extends AbstractGenerator
{
return false;
}
/* ------------------------------------------------------------ */
@Override
public boolean isResponse()
@ -157,7 +156,7 @@ public class Ajp13Generator extends AbstractGenerator
_noContent = false;
_persistent = true;
_header = null; // Buffer for HTTP header (and maybe small _content)
_buffer = null; // Buffer for copy of passed _content
@ -169,7 +168,7 @@ public class Ajp13Generator extends AbstractGenerator
/* ------------------------------------------------------------ */
/**
* Add content.
*
*
* @param content
* @param last
* @throws IllegalArgumentException
@ -251,7 +250,7 @@ public class Ajp13Generator extends AbstractGenerator
/* ------------------------------------------------------------ */
/**
* Add content.
*
*
* @param b
* byte
* @return true if the buffers are full
@ -301,7 +300,7 @@ public class Ajp13Generator extends AbstractGenerator
/**
* Prepare buffer for unchecked writes. Prepare the generator buffer to
* receive unchecked writes
*
*
* @return the available space in the buffer.
* @throws IOException
*/
@ -375,7 +374,7 @@ public class Ajp13Generator extends AbstractGenerator
if (_reason == null)
_reason=HttpGenerator.getReasonBuffer(_status);
if (_reason == null)
_reason = new ByteArrayBuffer(TypeUtil.toString(_status));
_reason = new ByteArrayBuffer(Integer.toString(_status));
addBuffer(_reason);
if (_status == 100 || _status == 204 || _status == 304)
@ -392,7 +391,7 @@ public class Ajp13Generator extends AbstractGenerator
int num_fields = 0;
if (fields != null)
{
{
// Add headers
int s=fields.size();
for (int f=0;f<s;f++)
@ -401,7 +400,7 @@ public class Ajp13Generator extends AbstractGenerator
if (field==null)
continue;
num_fields++;
byte[] codes = (byte[]) __headerHash.get(field.getName());
if (codes != null)
{
@ -452,7 +451,7 @@ public class Ajp13Generator extends AbstractGenerator
/* ------------------------------------------------------------ */
/**
* Complete the message.
*
*
* @throws IOException
*/
@Override
@ -506,7 +505,7 @@ public class Ajp13Generator extends AbstractGenerator
{
int len = -1;
int to_flush = ((_header != null && _header.length() > 0) ? 4 : 0) | ((_buffer != null && _buffer.length() > 0) ? 2 : 0);
switch (to_flush)
{

View File

@ -4,23 +4,21 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.http;
import org.eclipse.jetty.util.TypeUtil;
/**
* <p>
* HttpStatusCode enum class, for status codes based on various HTTP RFCs. (see
* table below)
* </p>
*
*
* <table border="1" cellpadding="5">
* <tr>
* <th>Enum</th>
@ -33,12 +31,12 @@ import org.eclipse.jetty.util.TypeUtil;
* <th>
* <a href="http://tools.ietf.org/html/rfc2518">RFC 2518 - WEBDAV</a></th>
* </tr>
*
*
* <tr>
* <td><strong><code>Informational - 1xx</code></strong></td>
* <td colspan="5">{@link #isInformational(int)}</td>
* </tr>
*
*
* <tr>
* <td>{@link #CONTINUE_100}</td>
* <td>100</td>
@ -66,12 +64,12 @@ import org.eclipse.jetty.util.TypeUtil;
* <td>
* <a href="http://tools.ietf.org/html/rfc2518#section-10.1">Sec. 10.1</a></td>
* </tr>
*
*
* <tr>
* <td><strong><code>Success - 2xx</code></strong></td>
* <td colspan="5">{@link #isSuccess(int)}</td>
* </tr>
*
*
* <tr>
* <td>{@link #OK_200}</td>
* <td>200</td>
@ -159,12 +157,12 @@ import org.eclipse.jetty.util.TypeUtil;
* >draft/01</a></td>
* <td>&nbsp;</td>
* </tr>
*
*
* <tr>
* <td><strong><code>Redirection - 3xx</code></strong></td>
* <td colspan="5">{@link #isRedirection(int)}</td>
* </tr>
*
*
* <tr>
* <td>{@link #MULTIPLE_CHOICES_300}</td>
* <td>300</td>
@ -249,12 +247,12 @@ import org.eclipse.jetty.util.TypeUtil;
* <a href="http://tools.ietf.org/html/rfc2616#section-10.3.8">Sec. 10.3.8</a></td>
* <td>&nbsp;</td>
* </tr>
*
*
* <tr>
* <td><strong><code>Client Error - 4xx</code></strong></td>
* <td colspan="5">{@link #isClientError(int)}</td>
* </tr>
*
*
* <tr>
* <td>{@link #BAD_REQUEST_400}</td>
* <td>400</td>
@ -521,12 +519,12 @@ import org.eclipse.jetty.util.TypeUtil;
* <td>
* <a href="http://tools.ietf.org/html/rfc2518#section-10.5">Sec. 10.5</a></td>
* </tr>
*
*
* <tr>
* <td><strong><code>Server Error - 5xx</code></strong></td>
* <td colspan="5">{@link #isServerError(int)}</td>
* </tr>
*
*
* <tr>
* <td>{@link #INTERNAL_SERVER_ERROR_500}</td>
* <td>500</td>
@ -602,9 +600,9 @@ import org.eclipse.jetty.util.TypeUtil;
* <td>
* <a href="http://tools.ietf.org/html/rfc2518#section-10.6">Sec. 10.6</a></td>
* </tr>
*
*
* </table>
*
*
* @version $Id$
*/
public class HttpStatus
@ -612,7 +610,7 @@ public class HttpStatus
public final static int CONTINUE_100 = 100;
public final static int SWITCHING_PROTOCOLS_101 = 101;
public final static int PROCESSING_102 = 102;
public final static int OK_200 = 200;
public final static int CREATED_201 = 201;
public final static int ACCEPTED_202 = 202;
@ -621,7 +619,7 @@ public class HttpStatus
public final static int RESET_CONTENT_205 = 205;
public final static int PARTIAL_CONTENT_206 = 206;
public final static int MULTI_STATUS_207 = 207;
public final static int MULTIPLE_CHOICES_300 = 300;
public final static int MOVED_PERMANENTLY_301 = 301;
public final static int MOVED_TEMPORARILY_302 = 302;
@ -630,7 +628,7 @@ public class HttpStatus
public final static int NOT_MODIFIED_304 = 304;
public final static int USE_PROXY_305 = 305;
public final static int TEMPORARY_REDIRECT_307 = 307;
public final static int BAD_REQUEST_400 = 400;
public final static int UNAUTHORIZED_401 = 401;
public final static int PAYMENT_REQUIRED_402 = 402;
@ -652,7 +650,7 @@ public class HttpStatus
public final static int UNPROCESSABLE_ENTITY_422 = 422;
public final static int LOCKED_423 = 423;
public final static int FAILED_DEPENDENCY_424 = 424;
public final static int INTERNAL_SERVER_ERROR_500 = 500;
public final static int NOT_IMPLEMENTED_501 = 501;
public final static int BAD_GATEWAY_502 = 502;
@ -660,9 +658,9 @@ public class HttpStatus
public final static int GATEWAY_TIMEOUT_504 = 504;
public final static int HTTP_VERSION_NOT_SUPPORTED_505 = 505;
public final static int INSUFFICIENT_STORAGE_507 = 507;
public static final int MAX_CODE = 507;
private static final Code[] codeMap = new Code[MAX_CODE+1];
@ -673,7 +671,7 @@ public class HttpStatus
codeMap[code._code] = code;
}
}
public enum Code
{
@ -843,7 +841,7 @@ public class HttpStatus
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>,
* and <a href="http://tools.ietf.org/html/rfc2616">RFC 2616 -
* HTTP/1.1</a>.
*
*
* @return true if within range of codes that belongs to
* <code>Informational</code> messages.
*/
@ -858,7 +856,7 @@ public class HttpStatus
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>,
* and <a href="http://tools.ietf.org/html/rfc2616">RFC 2616 -
* HTTP/1.1</a>.
*
*
* @return true if within range of codes that belongs to
* <code>Success</code> messages.
*/
@ -873,7 +871,7 @@ public class HttpStatus
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>,
* and <a href="http://tools.ietf.org/html/rfc2616">RFC 2616 -
* HTTP/1.1</a>.
*
*
* @return true if within range of codes that belongs to
* <code>Redirection</code> messages.
*/
@ -888,7 +886,7 @@ public class HttpStatus
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>,
* and <a href="http://tools.ietf.org/html/rfc2616">RFC 2616 -
* HTTP/1.1</a>.
*
*
* @return true if within range of codes that belongs to
* <code>Client Error</code> messages.
*/
@ -903,7 +901,7 @@ public class HttpStatus
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>,
* and <a href="http://tools.ietf.org/html/rfc2616">RFC 2616 -
* HTTP/1.1</a>.
*
*
* @return true if within range of codes that belongs to
* <code>Server Error</code> messages.
*/
@ -916,7 +914,7 @@ public class HttpStatus
/**
* Get the HttpStatusCode for a specific code
*
*
* @param code
* the code to lookup.
* @return the {@link HttpStatus} if found, or null if not found.
@ -929,10 +927,10 @@ public class HttpStatus
}
return null;
}
/**
* Get the status message for a specific code.
*
*
* @param code
* the code to look up
* @return the specific message, or the code number itself if code
@ -947,7 +945,7 @@ public class HttpStatus
}
else
{
return TypeUtil.toString(code);
return Integer.toString(code);
}
}
@ -956,7 +954,7 @@ public class HttpStatus
* <code>Informational</code> message category as defined in the <a
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>, and <a
* href="http://tools.ietf.org/html/rfc2616">RFC 2616 - HTTP/1.1</a>.
*
*
* @param code
* the code to test.
* @return true if within range of codes that belongs to
@ -972,7 +970,7 @@ public class HttpStatus
* <code>Success</code> message category as defined in the <a
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>, and <a
* href="http://tools.ietf.org/html/rfc2616">RFC 2616 - HTTP/1.1</a>.
*
*
* @param code
* the code to test.
* @return true if within range of codes that belongs to
@ -988,7 +986,7 @@ public class HttpStatus
* <code>Redirection</code> message category as defined in the <a
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>, and <a
* href="http://tools.ietf.org/html/rfc2616">RFC 2616 - HTTP/1.1</a>.
*
*
* @param code
* the code to test.
* @return true if within range of codes that belongs to
@ -1004,7 +1002,7 @@ public class HttpStatus
* <code>Client Error</code> message category as defined in the <a
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>, and <a
* href="http://tools.ietf.org/html/rfc2616">RFC 2616 - HTTP/1.1</a>.
*
*
* @param code
* the code to test.
* @return true if within range of codes that belongs to
@ -1020,7 +1018,7 @@ public class HttpStatus
* <code>Server Error</code> message category as defined in the <a
* href="http://tools.ietf.org/html/rfc1945">RFC 1945 - HTTP/1.0</a>, and <a
* href="http://tools.ietf.org/html/rfc2616">RFC 2616 - HTTP/1.1</a>.
*
*
* @param code
* the code to test.
* @return true if within range of codes that belongs to

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.jmx;
@ -20,13 +20,11 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.component.Container.Relationship;
@ -36,7 +34,7 @@ import org.eclipse.jetty.util.thread.ShutdownThread;
/* ------------------------------------------------------------ */
/**
* Container class for the MBean instances
* Container class for the MBean instances
*/
public class MBeanContainer extends AbstractLifeCycle implements Container.Listener
{
@ -49,21 +47,21 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
/* ------------------------------------------------------------ */
/**
* Lookup an object name by instance
*
*
* @param object instance for which object name is looked up
* @return object name associated with specified instance, or null if not found
*/
public synchronized ObjectName findMBean(Object object)
{
ObjectName bean = (ObjectName)_beans.get(object);
return bean==null?null:bean;
return bean==null?null:bean;
}
/* ------------------------------------------------------------ */
/**
* Lookup an instance by object name
*
* @param oname object name of instance
*
* @param oname object name of instance
* @return instance associated with specified object name, or null if not found
*/
public synchronized Object findBean(ObjectName oname)
@ -80,7 +78,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
/* ------------------------------------------------------------ */
/**
* Constructs MBeanContainer
*
*
* @param server instance of MBeanServer for use by container
*/
public MBeanContainer(MBeanServer server)
@ -96,62 +94,62 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
Log.ignore(e);
}
}
/* ------------------------------------------------------------ */
/**
* Retrieve instance of MBeanServer used by container
*
*
* @return instance of MBeanServer
*/
public MBeanServer getMBeanServer()
{
return _server;
}
/* ------------------------------------------------------------ */
/**
* Set domain to be used to add MBeans
*
*
* @param domain domain name
*/
public void setDomain (String domain)
{
_domain = domain;
}
/* ------------------------------------------------------------ */
/**
* Retrieve domain name used to add MBeans
*
*
* @return domain name
*/
public String getDomain()
{
return _domain;
}
/* ------------------------------------------------------------ */
/**
* Implementation of Container.Listener interface
*
*
* @see org.eclipse.jetty.util.component.Container.Listener#add(org.eclipse.jetty.util.component.Container.Relationship)
*/
public synchronized void add(Relationship relationship)
{
{
ObjectName parent=(ObjectName)_beans.get(relationship.getParent());
if (parent==null)
{
addBean(relationship.getParent());
parent=(ObjectName)_beans.get(relationship.getParent());
}
ObjectName child=(ObjectName)_beans.get(relationship.getChild());
if (child==null)
{
addBean(relationship.getChild());
child=(ObjectName)_beans.get(relationship.getChild());
}
if (parent!=null && child!=null)
_relations.add(parent,relationship);
}
@ -159,7 +157,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
/* ------------------------------------------------------------ */
/**
* Implementation of Container.Listener interface
*
*
* @see org.eclipse.jetty.util.component.Container.Listener#remove(org.eclipse.jetty.util.component.Container.Relationship)
*/
public synchronized void remove(Relationship relationship)
@ -173,7 +171,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
/* ------------------------------------------------------------ */
/**
* Implementation of Container.Listener interface
*
*
* @see org.eclipse.jetty.util.component.Container.Listener#removeBean(java.lang.Object)
*/
public synchronized void removeBean(Object obj)
@ -192,7 +190,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
relation.getContainer().update(relation.getParent(),relation.getChild(),null,relation.getRelationship(),true);
}
}
try
{
_server.unregisterMBean(bean);
@ -208,11 +206,11 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
}
}
}
/* ------------------------------------------------------------ */
/**
* Implementation of Container.Listener interface
*
*
* @see org.eclipse.jetty.util.component.Container.Listener#addBean(java.lang.Object)
*/
public synchronized void addBean(Object obj)
@ -221,7 +219,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
{
if (obj == null || _beans.containsKey(obj))
return;
Object mbean = ObjectMBean.mbeanFor(obj);
if (mbean == null)
return;
@ -232,7 +230,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
((ObjectMBean) mbean).setMBeanContainer(this);
oname = ((ObjectMBean)mbean).getObjectName();
}
//no override mbean object name, so make a generic one
if (oname == null)
{
@ -240,7 +238,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
int dot = type.lastIndexOf('.');
if (dot >= 0)
type = type.substring(dot + 1);
String name=null;
if (mbean instanceof ObjectMBean)
{
@ -261,11 +259,11 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
name=name.replace(':','_').replace('*','_').replace('?','_').replace('=','_').replace(',','_').replace(' ','_');
}
}
String basis=(name!=null&&name.length()>1)?("type="+type+",name="+name):("type="+type);
Integer count = (Integer) _unique.get(basis);
count = TypeUtil.newInteger(count == null ? 0 : (1 + count.intValue()));
count = count == null ? 0 : 1 + count;
_unique.put(basis, count);
//if no explicit domain, create one
@ -275,7 +273,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
oname = ObjectName.getInstance(domain+":"+basis+",id="+count);
}
ObjectInstance oinstance = _server.registerMBean(mbean, oname);
Log.debug("Registered {}" , oinstance.getObjectName());
_beans.put(obj, oinstance.getObjectName());
@ -286,7 +284,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
Log.warn("bean: "+obj,e);
}
}
/* ------------------------------------------------------------ */
/**
* Perform actions needed to start lifecycle

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
@ -20,7 +20,6 @@ import java.io.Writer;
import java.util.ArrayList;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.http.Cookie;
import org.eclipse.jetty.http.HttpHeaders;
@ -28,7 +27,6 @@ import org.eclipse.jetty.http.PathMap;
import org.eclipse.jetty.util.DateCache;
import org.eclipse.jetty.util.RolloverFileOutputStream;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.Utf8StringBuilder;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.Log;
@ -40,7 +38,7 @@ import org.eclipse.jetty.util.log.Log;
* Format (single log format). This log format can be output by most web
* servers, and almost all web log analysis software can understand these
* formats.
*
*
* @org.apache.xbean.XBean element="ncsaLog"
*/
public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
@ -133,12 +131,12 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
{
return _logDateFormat;
}
public void setLogLocale(Locale logLocale)
{
_logLocale = logLocale;
}
public Locale getLogLocale()
{
return _logLocale;
@ -251,7 +249,7 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
u8buf = size==0?new Utf8StringBuilder(160):(Utf8StringBuilder)_buffers.remove(size-1);
buf = u8buf.getStringBuilder();
}
if (_logServer)
{
buf.append(request.getServerName());
@ -274,7 +272,7 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
buf.append(((Authentication.User)authentication).getUserIdentity().getUserPrincipal().getName());
else
buf.append(" - ");
buf.append(" [");
if (_logDateCache != null)
buf.append(_logDateCache.format(request.getTimeStamp()));
@ -332,12 +330,12 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
buf.append(StringUtil.__LINE_SEPARATOR);
int l=buf.length();
if (l>_copy.length)
l=_copy.length;
buf.getChars(0,l,_copy,0);
l=_copy.length;
buf.getChars(0,l,_copy,0);
_writer.write(_copy,0,l);
_writer.flush();
u8buf.reset();
_buffers.add(u8buf);
_buffers.add(u8buf);
}
}
else
@ -346,11 +344,11 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
{
int l=buf.length();
if (l>_copy.length)
l=_copy.length;
buf.getChars(0,l,_copy,0);
l=_copy.length;
buf.getChars(0,l,_copy,0);
_writer.write(_copy,0,l);
u8buf.reset();
_buffers.add(u8buf);
_buffers.add(u8buf);
// TODO do outside synchronized scope
if (_extended)
@ -359,13 +357,13 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
// TODO do outside synchronized scope
if (_logCookies)
{
Cookie[] cookies = request.getCookies();
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0)
_writer.write(" -");
else
{
_writer.write(" \"");
for (int i = 0; i < cookies.length; i++)
for (int i = 0; i < cookies.length; i++)
{
if (i != 0)
_writer.write(';');
@ -380,7 +378,7 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
if (_logLatency)
{
_writer.write(' ');
_writer.write(TypeUtil.toString(System.currentTimeMillis() - request.getTimeStamp()));
_writer.write(Long.toString(System.currentTimeMillis() - request.getTimeStamp()));
}
_writer.write(StringUtil.__LINE_SEPARATOR);
@ -396,9 +394,9 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
}
/* ------------------------------------------------------------ */
protected void logExtended(Request request,
Response response,
Writer writer) throws IOException
protected void logExtended(Request request,
Response response,
Writer writer) throws IOException
{
String referer = request.getHeader(HttpHeaders.REFERER);
if (referer == null)
@ -502,7 +500,7 @@ public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
/* ------------------------------------------------------------ */
/**
* Set the log file date format.
*
*
* @see RolloverFileOutputStream#RolloverFileOutputStream(String, boolean, int, TimeZone, String, String)
* @param logFileDateFormat
* the logFileDateFormat to pass to

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.handler;
@ -16,7 +16,6 @@ package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -33,7 +32,6 @@ import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.resource.FileResource;
@ -42,12 +40,12 @@ import org.eclipse.jetty.util.resource.Resource;
/* ------------------------------------------------------------ */
/** Resource Handler.
*
*
* This handle will serve static content and handle If-Modified-Since headers.
* No caching is done.
* Requests that cannot be handled are let pass (Eg no 404's)
*
*
*
*
* @org.apache.xbean.XBean
*/
public class ResourceHandler extends AbstractHandler
@ -90,7 +88,7 @@ public class ResourceHandler extends AbstractHandler
/**
* Set if resource aliases (eg symlink, 8.3 names, case insensitivity) are allowed.
* Allowing aliases can significantly increase security vulnerabilities.
* If this handler is deployed inside a ContextHandler, then the
* If this handler is deployed inside a ContextHandler, then the
* {@link ContextHandler#isAliases()} takes precedent.
* @param aliases True if aliases are supported.
*/
@ -124,13 +122,13 @@ public class ResourceHandler extends AbstractHandler
{
Context scontext = ContextHandler.getCurrentContext();
_context = (scontext==null?null:scontext.getContextHandler());
if (_context!=null)
_aliases=_context.isAliases();
if (!_aliases && !FileResource.getCheckAliases())
throw new IllegalStateException("Alias checking disabled");
super.doStart();
}
@ -156,12 +154,12 @@ public class ResourceHandler extends AbstractHandler
return _baseResource.toString();
}
/* ------------------------------------------------------------ */
/**
* @param base The resourceBase to set.
*/
public void setBaseResource(Resource base)
public void setBaseResource(Resource base)
{
_baseResource=base;
}
@ -170,7 +168,7 @@ public class ResourceHandler extends AbstractHandler
/**
* @param resourceBase The base resource as a string.
*/
public void setResourceBase(String resourceBase)
public void setResourceBase(String resourceBase)
{
try
{
@ -203,18 +201,18 @@ public class ResourceHandler extends AbstractHandler
}
/* ------------------------------------------------------------ */
/*
/*
*/
public Resource getResource(String path) throws MalformedURLException
{
if (path==null || !path.startsWith("/"))
throw new MalformedURLException(path);
Resource base = _baseResource;
if (base==null)
{
if (_context==null)
return null;
return null;
base=_context.getBaseResource();
if (base==null)
return null;
@ -229,7 +227,7 @@ public class ResourceHandler extends AbstractHandler
{
Log.ignore(e);
}
return null;
}
@ -254,7 +252,7 @@ public class ResourceHandler extends AbstractHandler
{
_welcomeFiles=welcomeFiles;
}
/* ------------------------------------------------------------ */
protected Resource getWelcome(Resource directory) throws MalformedURLException, IOException
{
@ -269,14 +267,14 @@ public class ResourceHandler extends AbstractHandler
}
/* ------------------------------------------------------------ */
/*
/*
* @see org.eclipse.jetty.server.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
*/
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (baseRequest.isHandled())
return;
boolean skipContentBody = false;
if(!HttpMethods.GET.equals(request.getMethod()))
{
@ -284,9 +282,9 @@ public class ResourceHandler extends AbstractHandler
return;
skipContentBody = true;
}
Resource resource=getResource(request);
if (resource==null || !resource.exists())
return;
if (!_aliases && resource.getAlias()!=null)
@ -297,7 +295,7 @@ public class ResourceHandler extends AbstractHandler
// We are going to server something
baseRequest.setHandled(true);
if (resource.isDirectory())
{
if (!request.getPathInfo().endsWith(URIUtil.SLASH))
@ -305,7 +303,7 @@ public class ResourceHandler extends AbstractHandler
response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH)));
return;
}
Resource welcome=getWelcome(resource);
if (welcome!=null && welcome.exists())
resource=welcome;
@ -316,7 +314,7 @@ public class ResourceHandler extends AbstractHandler
return;
}
}
// set some headers
long last_modified=resource.lastModified();
if (last_modified>0)
@ -328,11 +326,11 @@ public class ResourceHandler extends AbstractHandler
return;
}
}
Buffer mime=_mimeTypes.getMimeByExtension(resource.toString());
if (mime==null)
mime=_mimeTypes.getMimeByExtension(request.getPathInfo());
// set the headers
doResponseHeaders(response,resource,mime!=null?mime.toString():null);
response.setDateHeader(HttpHeaders.LAST_MODIFIED,last_modified);
@ -342,7 +340,7 @@ public class ResourceHandler extends AbstractHandler
OutputStream out =null;
try {out = response.getOutputStream();}
catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());}
// See if a short direct method can be used?
if (out instanceof HttpConnection.Output)
{
@ -369,7 +367,7 @@ public class ResourceHandler extends AbstractHandler
else
response.sendError(HttpStatus.FORBIDDEN_403);
}
/* ------------------------------------------------------------ */
/** Set the response headers.
* This method is called to set the response headers such as content type and content length.
@ -384,25 +382,25 @@ public class ResourceHandler extends AbstractHandler
response.setContentType(mimeType);
long length=resource.length();
if (response instanceof Response)
{
HttpFields fields = ((Response)response).getHttpFields();
if (length>0)
fields.putLongField(HttpHeaders.CONTENT_LENGTH_BUFFER,length);
if (_cacheControl!=null)
fields.put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl);
}
else
{
if (length>0)
response.setHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(length));
response.setHeader(HttpHeaders.CONTENT_LENGTH,Long.toString(length));
if (_cacheControl!=null)
response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString());
}
}
}

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlet;
@ -21,7 +21,6 @@ import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@ -50,7 +49,6 @@ import org.eclipse.jetty.server.nio.NIOConnector;
import org.eclipse.jetty.server.ssl.SslConnector;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.MultiPartOutputStream;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.resource.FileResource;
@ -61,85 +59,85 @@ import org.eclipse.jetty.util.resource.ResourceFactory;
/* ------------------------------------------------------------ */
/** The default servlet.
* This servlet, normally mapped to /, provides the handling for static
* content, OPTION and TRACE methods for the context.
/** The default servlet.
* This servlet, normally mapped to /, provides the handling for static
* content, OPTION and TRACE methods for the context.
* The following initParameters are supported, these can be set either
* on the servlet itself or as ServletContext initParameters with a prefix
* of org.eclipse.jetty.servlet.Default. :
* <PRE>
* acceptRanges If true, range requests and responses are
* supported
*
* dirAllowed If true, directory listings are returned if no
* welcome file is found. Else 403 Forbidden.
* of org.eclipse.jetty.servlet.Default. :
* <PRE>
* acceptRanges If true, range requests and responses are
* supported
*
* dirAllowed If true, directory listings are returned if no
* welcome file is found. Else 403 Forbidden.
*
* welcomeServlets If true, attempt to dispatch to welcome files
* that are servlets, but only after no matching static
* resources could be found. If false, then a welcome
* file must exist on disk. If "exact", then exact
* resources could be found. If false, then a welcome
* file must exist on disk. If "exact", then exact
* servlet matches are supported without an existing file.
* Default is true.
*
*
* This must be false if you want directory listings,
* but have index.jsp in your welcome file list.
*
* redirectWelcome If true, welcome files are redirected rather than
* forwarded to.
*
* gzip If set to true, then static content will be served as
* gzip content encoded if a matching resource is
* gzip If set to true, then static content will be served as
* gzip content encoded if a matching resource is
* found ending with ".gz"
*
* resourceBase Set to replace the context resource base
*
* relativeResourceBase
* relativeResourceBase
* Set with a pathname relative to the base of the
* servlet context root. Useful for only serving static content out
* of only specific subdirectories.
*
*
* aliases If True, aliases of resources are allowed (eg. symbolic
* links and caps variations). May bypass security constraints.
*
*
* maxCacheSize The maximum total size of the cache or 0 for no cache.
* maxCachedFileSize The maximum size of a file to cache
* maxCachedFiles The maximum number of files to cache
* cacheType Set to "bio", "nio" or "both" to determine the type resource cache.
* cacheType Set to "bio", "nio" or "both" to determine the type resource cache.
* A bio cached buffer may be used by nio but is not as efficient as an
* nio buffer. An nio cached buffer may not be used by bio.
*
* useFileMappedBuffer
* nio buffer. An nio cached buffer may not be used by bio.
*
* useFileMappedBuffer
* If set to true, it will use mapped file buffer to serve static content
* when using NIO connector. Setting this value to false means that
* a direct buffer will be used instead of a mapped file buffer.
* a direct buffer will be used instead of a mapped file buffer.
* By default, this is set to true.
*
*
* cacheControl If set, all static content will have this value set as the cache-control
* header.
*
*
* </PRE>
*
*
*
*
*
* </PRE>
*
*
*
*
*/
public class DefaultServlet extends HttpServlet implements ResourceFactory
{
{
private ServletContext _servletContext;
private ContextHandler _contextHandler;
private boolean _acceptRanges=true;
private boolean _dirAllowed=true;
private boolean _welcomeServlets=true;
private boolean _welcomeExactServlets=false;
private boolean _redirectWelcome=false;
private boolean _gzip=true;
private Resource _resourceBase;
private NIOResourceCache _nioCache;
private ResourceCache _bioCache;
private MimeTypes _mimeTypes;
private String[] _welcomes;
private boolean _useFileMappedBuffer=false;
@ -147,8 +145,8 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
private String _relativeResourceBase;
private ServletHandler _servletHandler;
private ServletHolder _defaultHolder;
/* ------------------------------------------------------------ */
@Override
public void init()
@ -160,18 +158,18 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
_contextHandler=((ContextHandler.Context)_servletContext).getContextHandler();
else
_contextHandler = ContextHandler.getCurrentContext().getContextHandler();
_mimeTypes = _contextHandler.getMimeTypes();
_welcomes = _contextHandler.getWelcomeFiles();
if (_welcomes==null)
_welcomes=new String[] {"index.html","index.jsp"};
_acceptRanges=getInitBoolean("acceptRanges",_acceptRanges);
_dirAllowed=getInitBoolean("dirAllowed",_dirAllowed);
_redirectWelcome=getInitBoolean("redirectWelcome",_redirectWelcome);
_gzip=getInitBoolean("gzip",_gzip);
if ("exact".equals(getInitParameter("welcomeServlets")))
{
_welcomeExactServlets=true;
@ -179,37 +177,37 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
else
_welcomeServlets=getInitBoolean("welcomeServlets", _welcomeServlets);
if (getInitParameter("aliases")!=null)
_contextHandler.setAliases(getInitBoolean("aliases",false));
boolean aliases=_contextHandler.isAliases();
if (!aliases && !FileResource.getCheckAliases())
throw new IllegalStateException("Alias checking disabled");
if (aliases)
_servletContext.log("Aliases are enabled");
_useFileMappedBuffer=getInitBoolean("useFileMappedBuffer",_useFileMappedBuffer);
_relativeResourceBase = getInitParameter("relativeResourceBase");
String rb=getInitParameter("resourceBase");
if (rb!=null)
{
if (_relativeResourceBase!=null)
throw new UnavailableException("resourceBase & relativeResourceBase");
throw new UnavailableException("resourceBase & relativeResourceBase");
try{_resourceBase=_contextHandler.newResource(rb);}
catch (Exception e)
catch (Exception e)
{
Log.warn(Log.EXCEPTION,e);
throw new UnavailableException(e.toString());
throw new UnavailableException(e.toString());
}
}
String t=getInitParameter("cacheControl");
if (t!=null)
_cacheControl=new ByteArrayBuffer(t);
try
{
String cache_type =getInitParameter("cacheType");
@ -224,9 +222,9 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
_nioCache=new NIOResourceCache(_mimeTypes);
_nioCache.setUseFileMappedBuffer(_useFileMappedBuffer);
if (max_cache_size>0)
_nioCache.setMaxCacheSize(max_cache_size);
_nioCache.setMaxCacheSize(max_cache_size);
if (max_cached_file_size>=-1)
_nioCache.setMaxCachedFileSize(max_cached_file_size);
_nioCache.setMaxCachedFileSize(max_cached_file_size);
if (max_cached_files>=-1)
_nioCache.setMaxCachedFiles(max_cached_files);
_nioCache.start();
@ -238,9 +236,9 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
{
_bioCache=new ResourceCache(_mimeTypes);
if (max_cache_size>0)
_bioCache.setMaxCacheSize(max_cache_size);
_bioCache.setMaxCacheSize(max_cache_size);
if (max_cached_file_size>=-1)
_bioCache.setMaxCachedFileSize(max_cached_file_size);
_bioCache.setMaxCachedFileSize(max_cached_file_size);
if (max_cached_files>=-1)
_bioCache.setMaxCachedFiles(max_cached_files);
_bioCache.start();
@ -248,19 +246,19 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
if (_nioCache==null)
_bioCache=null;
}
catch (Exception e)
catch (Exception e)
{
Log.warn(Log.EXCEPTION,e);
throw new UnavailableException(e.toString());
throw new UnavailableException(e.toString());
}
_servletHandler= (ServletHandler) _contextHandler.getChildHandlerByClass(ServletHandler.class);
for (ServletHolder h :_servletHandler.getServlets())
if (h.getServletInstance()==this)
_defaultHolder=h;
if (Log.isDebugEnabled()) Log.debug("resource base = "+_resourceBase);
}
@ -273,7 +271,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
value=super.getInitParameter(name);
return value;
}
/* ------------------------------------------------------------ */
private boolean getInitBoolean(String name, boolean dft)
{
@ -286,7 +284,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
value.startsWith("Y")||
value.startsWith("1"));
}
/* ------------------------------------------------------------ */
private int getInitInt(String name, int dft)
{
@ -297,7 +295,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
return Integer.parseInt(value);
return dft;
}
/* ------------------------------------------------------------ */
/** get Resource to serve.
* Map a path to a resource. The default implementation calls
@ -311,7 +309,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
Resource r=null;
if (_relativeResourceBase!=null)
pathInContext=URIUtil.addPaths(_relativeResourceBase,pathInContext);
try
{
if (_resourceBase!=null)
@ -321,8 +319,8 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
URL u = _servletContext.getResource(pathInContext);
r = _contextHandler.newResource(u);
}
if (Log.isDebugEnabled())
if (Log.isDebugEnabled())
Log.debug("RESOURCE "+pathInContext+"="+r);
}
catch (IOException e)
@ -331,7 +329,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
return r;
}
/* ------------------------------------------------------------ */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
@ -362,10 +360,10 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (!hasDefinedRange(reqRanges))
reqRanges = null;
}
String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH);
// Can we gzip this request?
String pathInContextGz=null;
boolean gzip=false;
@ -375,19 +373,19 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (accept!=null && accept.indexOf("gzip")>=0)
gzip=true;
}
// Find the resource and content
Resource resource=null;
HttpContent content=null;
Connector connector = HttpConnection.getCurrentConnection().getConnector();
ResourceCache cache=(connector instanceof NIOConnector && !(connector instanceof SslConnector)) ?_nioCache:_bioCache;
try
{
{
// Try gzipped content first
if (gzip)
{
pathInContextGz=pathInContext+".gz";
pathInContextGz=pathInContext+".gz";
if (cache==null)
{
@ -415,7 +413,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
pathInContextGz=null;
}
}
// find resource
if (!gzip)
{
@ -431,15 +429,15 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
resource=getResource(pathInContext);
}
}
if (Log.isDebugEnabled())
Log.debug("resource="+resource+(content!=null?" content":""));
// Handle resource
if (resource==null || !resource.exists())
response.sendError(HttpServletResponse.SC_NOT_FOUND);
else if (!resource.isDirectory())
{
{
if (endsWithSlash && _contextHandler.isAliases() && pathInContext.length()>1)
{
String q=request.getQueryString();
@ -453,8 +451,8 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
// ensure we have content
if (content==null)
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
{
if (gzip)
{
@ -463,14 +461,14 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (mt!=null)
response.setContentType(mt);
}
sendData(request,response,included.booleanValue(),resource,content,reqRanges);
sendData(request,response,included.booleanValue(),resource,content,reqRanges);
}
}
}
else
{
String welcome=null;
if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.eclipse.jetty.server.nullPathInfo")!=null))
{
StringBuffer buf=request.getRequestURL();
@ -520,7 +518,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
}
}
else
else
{
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
@ -541,9 +539,9 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
else if (resource!=null)
resource.release();
}
}
/* ------------------------------------------------------------ */
private boolean hasDefinedRange(Enumeration reqRanges)
{
@ -557,7 +555,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
{
doGet(request,response);
}
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
@ -570,7 +568,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
/* ------------------------------------------------------------ */
/**
* Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of
* Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of
* configured {@link #_welcomes welcome files} that existing within the directory referenced by the <code>Resource</code>.
* If the resource is not a directory, or no matching file is found, then it may look for a valid servlet mapping.
* If there is none, then <code>null</code> is returned.
@ -585,7 +583,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
{
if (_welcomes==null)
return null;
String welcome_servlet=null;
for (int i=0;i<_welcomes.length;i++)
{
@ -600,7 +598,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (entry!=null && entry.getValue()!=_defaultHolder &&
(_welcomeServlets || (_welcomeExactServlets && entry.getKey().equals(welcome_in_context))))
welcome_servlet=welcome_in_context;
}
}
return welcome_servlet;
@ -633,7 +631,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
}
}
long ifmsl=request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifmsl!=-1)
{
@ -649,7 +647,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
// Parse the if[un]modified dates and compare to resource
long date=request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE);
if (date!=-1)
{
if (resource.lastModified()/1000 > date/1000)
@ -658,7 +656,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
return false;
}
}
}
}
catch(IllegalArgumentException iae)
@ -669,8 +667,8 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
return true;
}
/* ------------------------------------------------------------------- */
protected void sendDirectory(HttpServletRequest request,
HttpServletResponse response,
@ -683,16 +681,16 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
byte[] data=null;
String base = URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH);
// handle ResourceCollection
if (_resourceBase instanceof ResourceCollection)
resource=_resourceBase.addPath(pathInContext);
else if (_contextHandler.getBaseResource() instanceof ResourceCollection)
resource=_contextHandler.getBaseResource().addPath(pathInContext);
String dir = resource.getListHTML(base,pathInContext.length()>1);
if (dir==null)
{
@ -700,13 +698,13 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
"No directory");
return;
}
data=dir.getBytes("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setContentLength(data.length);
response.getOutputStream().write(data);
}
/* ------------------------------------------------------------ */
protected void sendData(HttpServletRequest request,
HttpServletResponse response,
@ -717,12 +715,12 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
throws IOException
{
long content_length=content==null?resource.length():content.getContentLength();
// Get the output stream (or writer)
OutputStream out =null;
try{out = response.getOutputStream();}
catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());}
if ( reqRanges == null || !reqRanges.hasMoreElements() || content_length<0)
{
// if there were no ranges, send entire entity
@ -763,19 +761,19 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
{
// Parse the satisfiable ranges
List ranges =InclusiveByteRange.satisfiableRanges(reqRanges,content_length);
// if there are no satisfiable ranges, send 416 response
if (ranges==null || ranges.size()==0)
{
writeHeaders(response, content, content_length);
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
response.setHeader(HttpHeaders.CONTENT_RANGE,
response.setHeader(HttpHeaders.CONTENT_RANGE,
InclusiveByteRange.to416HeaderRangeString(content_length));
resource.writeTo(out,0,content_length);
return;
}
// if there is only a single valid range (must be satisfiable
// if there is only a single valid range (must be satisfiable
// since were here now), send that range with a 216 response
if ( ranges.size()== 1)
{
@ -784,21 +782,21 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
long singleLength = singleSatisfiableRange.getSize(content_length);
writeHeaders(response,content,singleLength );
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader(HttpHeaders.CONTENT_RANGE,
response.setHeader(HttpHeaders.CONTENT_RANGE,
singleSatisfiableRange.toHeaderRangeString(content_length));
resource.writeTo(out,singleSatisfiableRange.getFirst(content_length),singleLength);
return;
}
// multiple non-overlapping valid ranges cause a multipart
// 216 response which does not require an overall
// 216 response which does not require an overall
// content-length header
//
writeHeaders(response,content,-1);
String mimetype=content.getContentType().toString();
MultiPartOutputStream multi = new MultiPartOutputStream(out);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
// If the request has a "Request-Range" header then we need to
// send an old style multipart/x-byteranges Content-Type. This
// keeps Netscape and acrobat happy. This is what Apache does.
@ -808,10 +806,10 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
else
ctp = "multipart/byteranges; boundary=";
response.setContentType(ctp+multi.getBoundary());
InputStream in=resource.getInputStream();
long pos=0;
// calculate the content-length
int length=0;
String[] header = new String[ranges.size()];
@ -821,20 +819,20 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
header[i]=ibr.toHeaderRangeString(content_length);
length+=
((i>0)?2:0)+
2+multi.getBoundary().length()+2+
HttpHeaders.CONTENT_TYPE.length()+2+mimetype.length()+2+
HttpHeaders.CONTENT_RANGE.length()+2+header[i].length()+2+
2+multi.getBoundary().length()+2+
HttpHeaders.CONTENT_TYPE.length()+2+mimetype.length()+2+
HttpHeaders.CONTENT_RANGE.length()+2+header[i].length()+2+
2+
(ibr.getLast(content_length)-ibr.getFirst(content_length))+1;
}
length+=2+2+multi.getBoundary().length()+2+2;
response.setContentLength(length);
for (int i=0;i<ranges.size();i++)
{
InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
multi.startPart(mimetype,new String[]{HttpHeaders.CONTENT_RANGE+": "+header[i]});
long start=ibr.getFirst(content_length);
long size=ibr.getSize(content_length);
if (in!=null)
@ -857,7 +855,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
else
// Handle cached resource
(resource).writeTo(multi,start,size);
}
if (in!=null)
in.close();
@ -865,20 +863,20 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
return;
}
/* ------------------------------------------------------------ */
protected void writeHeaders(HttpServletResponse response,HttpContent content,long count)
throws IOException
{
{
if (content.getContentType()!=null && response.getContentType()==null)
response.setContentType(content.getContentType().toString());
if (response instanceof Response)
{
Response r=(Response)response;
HttpFields fields = r.getHttpFields();
if (content.getLastModified()!=null)
if (content.getLastModified()!=null)
fields.put(HttpHeaders.LAST_MODIFIED_BUFFER,content.getLastModified(),content.getResource().lastModified());
else if (content.getResource()!=null)
{
@ -886,7 +884,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (lml!=-1)
fields.putDateField(HttpHeaders.LAST_MODIFIED_BUFFER,lml);
}
if (count != -1)
r.setLongContentLength(count);
@ -902,27 +900,27 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
{
if (count<Integer.MAX_VALUE)
response.setContentLength((int)count);
else
response.setHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(count));
else
response.setHeader(HttpHeaders.CONTENT_LENGTH,Long.toString(count));
}
writeOptionHeaders(response);
}
}
/* ------------------------------------------------------------ */
protected void writeOptionHeaders(HttpFields fields) throws IOException
{
{
if (_acceptRanges)
fields.put(HttpHeaders.ACCEPT_RANGES_BUFFER,HttpHeaderValues.BYTES_BUFFER);
if (_cacheControl!=null)
fields.put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl);
}
/* ------------------------------------------------------------ */
protected void writeOptionHeaders(HttpServletResponse response) throws IOException
{
{
if (_acceptRanges)
response.setHeader(HttpHeaders.ACCEPT_RANGES,"bytes");
@ -931,7 +929,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
/* ------------------------------------------------------------ */
/*
/*
* @see javax.servlet.Servlet#destroy()
*/
@Override
@ -970,12 +968,12 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
private class UnCachedContent implements HttpContent
{
Resource _resource;
UnCachedContent(Resource resource)
{
_resource=resource;
}
/* ------------------------------------------------------------ */
public Buffer getContentType()
{
@ -1018,6 +1016,6 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
_resource.release();
_resource=null;
}
}
}

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlet;
@ -18,7 +18,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -30,30 +29,29 @@ import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
/** Error Page Error Handler
*
*
* An ErrorHandler that maps exceptions and status codes to URIs for dispatch using
* the internal ERROR style of dispatch.
*
*
*
*/
public class ErrorPageErrorHandler extends ErrorHandler
{
public final static String ERROR_PAGE="org.eclipse.jetty.server.error_page";
protected ServletContext _servletContext;
protected Map _errorPages; // code or exception to URL
protected List _errorPageList; // list of ErrorCode by range
protected List _errorPageList; // list of ErrorCode by range
/* ------------------------------------------------------------ */
public ErrorPageErrorHandler()
{}
/* ------------------------------------------------------------ */
/**
/**
* @see org.eclipse.jetty.server.handler.ErrorHandler#handle(String, Request, HttpServletRequest, HttpServletResponse)
*/
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
@ -68,7 +66,7 @@ public class ErrorPageErrorHandler extends ErrorHandler
{
String error_page= null;
Class exClass= (Class)request.getAttribute(Dispatcher.ERROR_EXCEPTION_TYPE);
if (ServletException.class.equals(exClass))
{
error_page= (String)_errorPages.get(exClass.getName());
@ -81,20 +79,20 @@ public class ErrorPageErrorHandler extends ErrorHandler
exClass= th.getClass();
}
}
while (error_page == null && exClass != null )
{
error_page= (String)_errorPages.get(exClass.getName());
exClass= exClass.getSuperclass();
}
if (error_page == null)
{
// look for an exact code match
Integer code=(Integer)request.getAttribute(Dispatcher.ERROR_STATUS_CODE);
if (code!=null)
{
error_page= (String)_errorPages.get(TypeUtil.toString(code.intValue()));
error_page= (String)_errorPages.get(Integer.toString(code));
// if still not found
if ((error_page == null) && (_errorPageList != null))
@ -103,7 +101,7 @@ public class ErrorPageErrorHandler extends ErrorHandler
for (int i = 0; i < _errorPageList.size(); i++)
{
ErrorCodeRange errCode = (ErrorCodeRange) _errorPageList.get(i);
if (errCode.isInRange(code.intValue()))
if (errCode.isInRange(code))
{
error_page = errCode.getUri();
break;
@ -112,19 +110,19 @@ public class ErrorPageErrorHandler extends ErrorHandler
}
}
}
if (error_page!=null)
{
String old_error_page=(String)request.getAttribute(ERROR_PAGE);
if (old_error_page==null || !old_error_page.equals(error_page))
{
request.setAttribute(ERROR_PAGE, error_page);
Dispatcher dispatcher = (Dispatcher) _servletContext.getRequestDispatcher(error_page);
try
{
if(dispatcher!=null)
{
{
dispatcher.error(request, response);
return;
}
@ -141,7 +139,7 @@ public class ErrorPageErrorHandler extends ErrorHandler
}
}
}
super.handle(target, baseRequest, request, response);
}
@ -153,7 +151,7 @@ public class ErrorPageErrorHandler extends ErrorHandler
{
return _errorPages;
}
/* ------------------------------------------------------------ */
/**
* @param errorPages The errorPages to set. A map of Exception class name or error code as a string to URI string
@ -176,7 +174,7 @@ public class ErrorPageErrorHandler extends ErrorHandler
_errorPages=new HashMap();
_errorPages.put(exception.getName(),uri);
}
/* ------------------------------------------------------------ */
/** Add Error Page mapping for a status code.
* This method is called as a result of an error-code element in a web.xml file
@ -188,9 +186,9 @@ public class ErrorPageErrorHandler extends ErrorHandler
{
if (_errorPages==null)
_errorPages=new HashMap();
_errorPages.put(TypeUtil.toString(code),uri);
_errorPages.put(Integer.toString(code),uri);
}
/* ------------------------------------------------------------ */
/** Add Error Page mapping for a status code range.
* This method is not available from web.xml and must be called
@ -229,36 +227,36 @@ public class ErrorPageErrorHandler extends ErrorHandler
private int _from;
private int _to;
private String _uri;
ErrorCodeRange(int from, int to, String uri)
throws IllegalArgumentException
{
if (from > to)
throw new IllegalArgumentException("from>to");
_from = from;
_to = to;
_uri = uri;
}
boolean isInRange(int value)
{
if ((value >= _from) && (value <= _to))
{
return true;
}
return false;
}
String getUri()
{
return _uri;
}
public String toString()
{
return "from: " + _from + ",to: " + _to + ",uri: " + _uri;
}
}
}
}

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlets;
@ -24,7 +24,6 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.HashSet;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@ -46,7 +45,6 @@ import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
@ -54,7 +52,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool;
/**
* Asynchronous Proxy Servlet.
*
*
* Forward requests to another server either as a standard web proxy (as defined by
* RFC2616) or as a transparent proxy.
* <p>
@ -71,11 +69,11 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool;
* <li>maxThreads - maximum threads
* <li>maxConnections - maximum connections per destination
* <li>HostHeader - Force the host header to a particular value
* </ul>
* </ul>
*/
public class ProxyServlet implements Servlet
{
protected Logger _log;
protected Logger _log;
HttpClient _client;
String _hostHeader;
@ -107,10 +105,10 @@ public class ProxyServlet implements Servlet
_client=new HttpClient();
_client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
_hostHeader=config.getInitParameter("HostHeader");
try
{
String t = config.getInitParameter("attrPrefix");
@ -124,13 +122,13 @@ public class ProxyServlet implements Servlet
else
_client.setThreadPool(new QueuedThreadPool());
((QueuedThreadPool)_client.getThreadPool()).setName(_name.substring(_name.lastIndexOf('.')+1));
t = config.getInitParameter("maxConnections");
if (t!=null)
_client.setMaxConnectionsPerAddress(Integer.parseInt(t));
_client.start();
if (_context!=null)
{
_context.setAttribute("org.eclipse.jetty.servlets."+_name+".Logger",_log);
@ -153,7 +151,7 @@ public class ProxyServlet implements Servlet
return _config;
}
/* ------------------------------------------------------------ */
/** Get the hostHeader.
* @return the hostHeader
@ -180,7 +178,7 @@ public class ProxyServlet implements Servlet
IOException
{
final int debug=_log.isDebugEnabled()?req.hashCode():0;
final HttpServletRequest request = (HttpServletRequest)req;
final HttpServletResponse response = (HttpServletResponse)res;
if ("CONNECT".equalsIgnoreCase(request.getMethod()))
@ -193,7 +191,7 @@ public class ProxyServlet implements Servlet
final OutputStream out=response.getOutputStream();
final Continuation continuation = ContinuationSupport.getContinuation(request);
if (!continuation.isInitial())
response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT); // Need better test that isInitial
else
@ -206,10 +204,10 @@ public class ProxyServlet implements Servlet
request.getServerName(),
request.getServerPort(),
uri);
if (debug!=0)
_log.debug(debug+" proxy "+uri+"-->"+url);
if (url==null)
{
response.sendError(HttpServletResponse.SC_FORBIDDEN);
@ -248,7 +246,7 @@ public class ProxyServlet implements Servlet
{
if (debug!=0)
_log.debug(debug+" "+version+" "+status+" "+reason);
if (reason!=null && reason.length()>0)
response.setStatus(status,reason.toString());
else
@ -264,7 +262,7 @@ public class ProxyServlet implements Servlet
{
if (debug!=0)
_log.debug(debug+" "+name+": "+value);
response.addHeader(name.toString(),value.toString());
}
else if (debug!=0)
@ -303,7 +301,7 @@ public class ProxyServlet implements Servlet
exchange.setMethod(request.getMethod());
exchange.setURL(url.toString());
exchange.setVersion(request.getProtocol());
if (debug!=0)
_log.debug(debug+" "+request.getMethod()+" "+url+" "+request.getProtocol());
@ -320,7 +318,7 @@ public class ProxyServlet implements Servlet
// force host
if (_hostHeader!=null)
exchange.setRequestHeader("Host",_hostHeader);
// copy headers
boolean xForwardedFor=false;
boolean hasContent=false;
@ -344,7 +342,7 @@ public class ProxyServlet implements Servlet
else if ("content-length".equals(lhdr))
{
contentLength=request.getContentLength();
exchange.setRequestHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(contentLength));
exchange.setRequestHeader(HttpHeaders.CONTENT_LENGTH,Long.toString(contentLength));
if (contentLength>0)
hasContent=true;
}
@ -373,8 +371,8 @@ public class ProxyServlet implements Servlet
if (hasContent)
exchange.setRequestContentSource(in);
continuation.suspend(response);
continuation.suspend(response);
_client.send(exchange);
}
@ -450,19 +448,19 @@ public class ProxyServlet implements Servlet
{
}
/**
* Transparent Proxy.
*
* This convenience extension to ProxyServlet configures the servlet as a transparent proxy.
*
* This convenience extension to ProxyServlet configures the servlet as a transparent proxy.
* The servlet is configured with init parameters:
* <ul>
* <li>ProxyTo - a URI like http://host:80/context to which the request is proxied.
* <li>Prefix - a URI prefix that is striped from the start of the forwarded URI.
* </ul>
* For example, if a request was received at /foo/bar and the ProxyTo was http://host:80/context
* For example, if a request was received at /foo/bar and the ProxyTo was http://host:80/context
* and the Prefix was /foo, then the request would be proxied to http://host:80/context/bar
*
*
*/
public static class Transparent extends ProxyServlet
{

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.util;
@ -25,20 +25,20 @@ import org.eclipse.jetty.util.log.Log;
/* ------------------------------------------------------------ */
/** TYPE Utilities.
/**
* TYPE Utilities.
* Provides various static utiltiy methods for manipulating types and their
* string representations.
*
* @since Jetty 4.1
*
*/
public class TypeUtil
{
public static int CR = '\015';
public static int LF = '\012';
/* ------------------------------------------------------------ */
private static final HashMap name2Class=new HashMap();
private static final HashMap<String, Class> name2Class=new HashMap<String, Class>();
static
{
name2Class.put("boolean",java.lang.Boolean.TYPE);
@ -50,7 +50,7 @@ public class TypeUtil
name2Class.put("long",java.lang.Long.TYPE);
name2Class.put("short",java.lang.Short.TYPE);
name2Class.put("void",java.lang.Void.TYPE);
name2Class.put("java.lang.Boolean.TYPE",java.lang.Boolean.TYPE);
name2Class.put("java.lang.Byte.TYPE",java.lang.Byte.TYPE);
name2Class.put("java.lang.Character.TYPE",java.lang.Character.TYPE);
@ -84,9 +84,9 @@ public class TypeUtil
name2Class.put("String",java.lang.String.class);
name2Class.put("java.lang.String",java.lang.String.class);
}
/* ------------------------------------------------------------ */
private static final HashMap class2Name=new HashMap();
private static final HashMap<Class, String> class2Name=new HashMap<Class, String>();
static
{
class2Name.put(java.lang.Boolean.TYPE,"boolean");
@ -107,19 +107,19 @@ public class TypeUtil
class2Name.put(java.lang.Integer.class,"java.lang.Integer");
class2Name.put(java.lang.Long.class,"java.lang.Long");
class2Name.put(java.lang.Short.class,"java.lang.Short");
class2Name.put(null,"void");
class2Name.put(java.lang.String.class,"java.lang.String");
}
/* ------------------------------------------------------------ */
private static final HashMap class2Value=new HashMap();
private static final HashMap<Class, Method> class2Value=new HashMap<Class, Method>();
static
{
try
{
Class[] s ={java.lang.String.class};
class2Value.put(java.lang.Boolean.TYPE,
java.lang.Boolean.class.getMethod("valueOf",s));
class2Value.put(java.lang.Byte.TYPE,
@ -156,44 +156,6 @@ public class TypeUtil
}
}
/* ------------------------------------------------------------ */
private static Class[] stringArg = { java.lang.String.class };
/* ------------------------------------------------------------ */
private static int intCacheSize = 600;
private static Integer[] integerCache = new Integer[intCacheSize];
private static String[] integerStrCache = new String[intCacheSize];
private static Integer minusOne = new Integer(-1);
private static int longCacheSize = 64;
private static Long[] longCache = new Long[longCacheSize];
private static Long minusOneL = new Long(-1);
public static void setIntCacheSize(int size)
{
if (size > intCacheSize) {
Integer[] intCache = new Integer[size];
System.arraycopy(integerCache,0,intCache,0,intCacheSize);
String [] strCache = new String[size];
System.arraycopy(integerStrCache,0,strCache,0,intCacheSize);
intCacheSize = size;
integerCache = intCache;
integerStrCache = strCache;
}
}
public static void setLongCacheSize(int size)
{
if (size > longCacheSize) {
Long[] lnCache = new Long[size];
System.arraycopy(longCache,0,lnCache,0,longCacheSize);
longCacheSize = size;
longCache = lnCache;
}
}
/* ------------------------------------------------------------ */
/** Class from a canonical name for a type.
* @param name A class or type name.
@ -201,9 +163,9 @@ public class TypeUtil
*/
public static Class fromName(String name)
{
return (Class)name2Class.get(name);
return name2Class.get(name);
}
/* ------------------------------------------------------------ */
/** Canonical name for a type.
* @param type A class , which may be a primitive TYPE field.
@ -211,9 +173,9 @@ public class TypeUtil
*/
public static String toName(Class type)
{
return (String)class2Name.get(type);
return class2Name.get(type);
}
/* ------------------------------------------------------------ */
/** Convert String value to instance.
* @param type The class of the instance, which may be a primitive TYPE field.
@ -226,17 +188,17 @@ public class TypeUtil
{
if (type.equals(java.lang.String.class))
return value;
Method m = (Method)class2Value.get(type);
Method m = class2Value.get(type);
if (m!=null)
return m.invoke(null,new Object[] {value});
return m.invoke(null, value);
if (type.equals(java.lang.Character.TYPE) ||
type.equals(java.lang.Character.class))
return new Character(value.charAt(0));
Constructor c = type.getConstructor(stringArg);
return c.newInstance(new Object[] {value});
Constructor c = type.getConstructor(java.lang.String.class);
return c.newInstance(value);
}
catch(NoSuchMethodException e)
{
@ -258,7 +220,7 @@ public class TypeUtil
}
return null;
}
/* ------------------------------------------------------------ */
/** Convert String value to instance.
* @param type classname or type (eg int)
@ -269,72 +231,6 @@ public class TypeUtil
{
return valueOf(fromName(type),value);
}
/* ------------------------------------------------------------ */
/** Convert int to Integer using cache.
*/
public static Integer newInteger(int i)
{
if (i>=0 && i<intCacheSize)
{
if (integerCache[i]==null)
integerCache[i]=new Integer(i);
return integerCache[i];
}
else if (i==-1)
return minusOne;
return new Integer(i);
}
/* ------------------------------------------------------------ */
/** Convert int to Integer using cache.
*/
public static Long newLong(long i)
{
if (i>=0 && i<longCacheSize)
{
if (longCache[(int)i]==null)
longCache[(int)i]=new Long(i);
return longCache[(int)i];
}
else if (i==-1)
return minusOneL;
return new Long(i);
}
/* ------------------------------------------------------------ */
/** Convert int to String using cache.
*/
public static String toString(int i)
{
if (i>=0 && i<intCacheSize)
{
if (integerStrCache[i]==null)
integerStrCache[i]=Integer.toString(i);
return integerStrCache[i];
}
else if (i==-1)
return "-1";
return Integer.toString(i);
}
/* ------------------------------------------------------------ */
/** Convert long to String using cache.
*/
public static String toString(long i)
{
if (i>=0 && i<intCacheSize)
{
if (integerStrCache[(int)i]==null)
integerStrCache[(int)i]=Long.toString(i);
return integerStrCache[(int)i];
}
else if (i==-1)
return "-1";
return Long.toString(i);
}
/* ------------------------------------------------------------ */
/** Parse an int from a substring.
@ -343,7 +239,8 @@ public class TypeUtil
* @param offset Offset within string
* @param length Length of integer or -1 for remainder of string
* @param base base of the integer
* @exception NumberFormatException
* @return the parsed integer
* @throws NumberFormatException if the string cannot be parsed
*/
public static int parseInt(String s, int offset, int length, int base)
throws NumberFormatException
@ -356,7 +253,7 @@ public class TypeUtil
for (int i=0;i<length;i++)
{
char c=s.charAt(offset+i);
int digit=c-'0';
if (digit<0 || digit>=base || digit>=10)
{
@ -378,7 +275,8 @@ public class TypeUtil
* @param offset Offset within string
* @param length Length of integer or -1 for remainder of string
* @param base base of the integer
* @exception NumberFormatException
* @return the parsed integer
* @throws NumberFormatException if the array cannot be parsed into an integer
*/
public static int parseInt(byte[] b, int offset, int length, int base)
throws NumberFormatException
@ -391,7 +289,7 @@ public class TypeUtil
for (int i=0;i<length;i++)
{
char c=(char)(0xff&b[offset+i]);
int digit=c-'0';
if (digit<0 || digit>=base || digit>=10)
{
@ -419,9 +317,9 @@ public class TypeUtil
public static String toString(byte[] bytes, int base)
{
StringBuilder buf = new StringBuilder();
for (int i=0;i<bytes.length;i++)
for (byte b : bytes)
{
int bi=0xff&bytes[i];
int bi=0xff&b;
int c='0'+(bi/base)%base;
if (c>'9')
c= 'a'+(c-'0'-10);
@ -435,7 +333,7 @@ public class TypeUtil
}
/* ------------------------------------------------------------ */
/**
/**
* @param b An ASCII encoded character 0-9 a-f A-F
* @return The byte value of the character 0-16.
*/
@ -449,7 +347,7 @@ public class TypeUtil
/* ------------------------------------------------------------ */
public static void toHex(byte b,Appendable buf)
{
{
try
{
int bi=0xff&b;
@ -467,29 +365,16 @@ public class TypeUtil
throw new RuntimeException(e);
}
}
/* ------------------------------------------------------------ */
public static String toHexString(byte[] b)
{
StringBuilder buf = new StringBuilder();
for (int i=0;i<b.length;i++)
{
int bi=0xff&b[i];
int c='0'+(bi/16)%16;
if (c>'9')
c= 'A'+(c-'0'-10);
buf.append((char)c);
c='0'+bi%16;
if (c>'9')
c= 'a'+(c-'0'-10);
buf.append((char)c);
}
return buf.toString();
{
return toHexString(b, 0, b.length);
}
/* ------------------------------------------------------------ */
public static String toHexString(byte[] b,int offset,int length)
{
{
StringBuilder buf = new StringBuilder();
for (int i=offset;i<offset+length;i++)
{
@ -505,10 +390,10 @@ public class TypeUtil
}
return buf.toString();
}
/* ------------------------------------------------------------ */
public static byte[] fromHexString(String s)
{
{
if (s.length()%2!=0)
throw new IllegalArgumentException(s);
byte[] array = new byte[s.length()/2];
@ -516,10 +401,10 @@ public class TypeUtil
{
int b = Integer.parseInt(s.substring(i*2,i*2+2),16);
array[i]=(byte)(0xff&b);
}
}
return array;
}
public static void dump(Class c)
{
@ -536,31 +421,31 @@ public class TypeUtil
cl = cl.getParent();
}
}
/* ------------------------------------------------------------ */
public static byte[] readLine(InputStream in) throws IOException
{
byte[] buf = new byte[256];
int i=0;
int loops=0;
int ch=0;
while (true)
{
ch=in.read();
if (ch<0)
break;
loops++;
// skip a leading LF's
if (loops==1 && ch==LF)
continue;
if (ch==CR || ch==LF)
break;
if (i>=buf.length)
{
byte[] old_buf=buf;
@ -569,10 +454,10 @@ public class TypeUtil
}
buf[i++]=(byte)ch;
}
if (ch==-1 && i==0)
return null;
// skip a trailing LF if it exists
if (ch==CR && in.available()>=1 && in.markSupported())
{
@ -585,10 +470,10 @@ public class TypeUtil
byte[] old_buf=buf;
buf=new byte[i];
System.arraycopy(old_buf, 0, buf, 0, i);
return buf;
}
public static URL jarFor(String className)
{
try

View File

@ -4,11 +4,11 @@
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.util.ajax;
@ -33,11 +33,11 @@ import org.eclipse.jetty.util.log.Log;
/**
* JSON Parser and Generator.
*
*
* <p>
* This class provides some static methods to convert POJOs to and from JSON
* notation. The mapping from JSON to java is:
*
*
* <pre>
* object ==> Map
* array ==> Object[]
@ -46,11 +46,11 @@ import org.eclipse.jetty.util.log.Log;
* null ==> null
* bool ==> Boolean
* </pre>
*
*
* </p>
* <p>
* The java to JSON mapping is:
*
*
* <pre>
* String --> string
* Number --> number
@ -61,7 +61,7 @@ import org.eclipse.jetty.util.log.Log;
* Boolean--> boolean
* Object --> string (dubious!)
* </pre>
*
*
* </p>
* <p>
* The interface {@link JSON.Convertible} may be implemented by classes that
@ -80,8 +80,8 @@ import org.eclipse.jetty.util.log.Log;
* . These convertors are looked up by class, interface and super class by
* {@link #getConvertor(Class)}.
* </p>
*
*
*
*
*/
public class JSON
{
@ -118,7 +118,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Register a {@link Convertor} for a class or interface.
*
*
* @param forClass
* The class or interface that the convertor applies to
* @param convertor
@ -244,7 +244,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Convert Object to JSON
*
*
* @param object
* The object to convert
* @return The JSON String
@ -259,7 +259,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Convert JSON to Object
*
*
* @param json
* The json to convert
* @return The object
@ -279,7 +279,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Append object as JSON to string buffer.
*
*
* @param buffer
* the buffer to append to
* @param object
@ -636,7 +636,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Register a {@link Convertor} for a class or interface.
*
*
* @param forClass
* The class or interface that the convertor applies to
* @param convertor
@ -654,7 +654,7 @@ public class JSON
* If no match is found for the class, then the interfaces for the class are
* tried. If still no match is found, then the super class and it's
* interfaces are tried recursively.
*
*
* @param forClass
* The class
* @return a {@link JSON.Convertor} or null if none were found.
@ -684,7 +684,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Register a {@link JSON.Convertor} for a named class or interface.
*
*
* @param name
* name of a class or an interface that the convertor applies to
* @param convertor
@ -698,7 +698,7 @@ public class JSON
/* ------------------------------------------------------------ */
/**
* Lookup a convertor for a named class.
*
*
* @param name
* name of the class
* @return a {@link JSON.Convertor} or null if none were found.
@ -1215,7 +1215,7 @@ public class JSON
}
if (buffer == null)
return TypeUtil.newLong(minus?-1 * number:number);
return minus ? -1 * number : number;
doubleLoop: while (source.hasNext())
{
@ -1395,7 +1395,7 @@ public class JSON
_buffer.append(c);
QuotedStringTokenizer.quote(_buffer,name);
_buffer.append(':');
appendNumber(_buffer,TypeUtil.newLong(value));
appendNumber(_buffer, value);
c = ',';
}
catch (IOException e)
@ -1577,7 +1577,7 @@ public class JSON
* <p>
* If the JSON is to be convertible back to an Object, then the method
* {@link Output#addClass(Class)} must be called from within toJSON()
*
*
*/
public interface Convertible
{
@ -1630,7 +1630,7 @@ public class JSON
* Construct a literal JSON instance for use by
* {@link JSON#toString(Object)}. If {@link Log#isDebugEnabled()} is
* true, the JSON will be parsed to check validity
*
*
* @param json
* A literal JSON string.
*/