Merge pull request #3398 from eclipse/jetty-10.0.x-remove-deprecated

Issue #1676 - Removing deprecated methods and classes
This commit is contained in:
Joakim Erdfelt 2019-03-01 07:55:19 -05:00 committed by GitHub
commit ce3f6634b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
201 changed files with 710 additions and 9004 deletions

View File

@ -212,7 +212,6 @@ public class LikeJettyXml
lowResourcesMonitor.setPeriod(1000);
lowResourcesMonitor.setLowResourcesIdleTimeout(200);
lowResourcesMonitor.setMonitorThreads(true);
lowResourcesMonitor.setMaxConnections(0);
lowResourcesMonitor.setMaxMemory(0);
lowResourcesMonitor.setMaxLowResourcesTime(5000);
server.addBean(lowResourcesMonitor);

View File

@ -61,7 +61,7 @@ public class ServerWithAnnotations
new Transaction(new com.acme.MockUserTransaction());
// Define an env entry with webapp scope.
new EnvEntry(webapp, "maxAmount", new Double(100), true);
new EnvEntry(webapp, "maxAmount", 100D, true);
// Register a mock DataSource scoped to the webapp
new Resource(webapp, "jdbc/mydatasource", new com.acme.MockDataSource());

View File

@ -61,7 +61,7 @@ public class ServerWithJNDI
// <env-entry-type>java.lang.Integer</env-entry-type>
// <env-entry-value>4000</env-entry-value>
// </env-entry>
new org.eclipse.jetty.plus.jndi.EnvEntry(server, "woggle", new Integer(4000), false);
new org.eclipse.jetty.plus.jndi.EnvEntry(server, "woggle", 4000, false);
// Define an env entry with webapp scope.
// At runtime, the webapp accesses this as java:comp/env/wiggle
@ -74,7 +74,7 @@ public class ServerWithJNDI
// Note that the last arg of "true" means that this definition for
// "wiggle" would override an entry of the
// same name in web.xml
new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "wiggle", new Double(100), true);
new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "wiggle", 100D, true);
// Register a reference to a mail service scoped to the webapp.
// This must be linked to the webapp by an entry in web.xml:

View File

@ -39,7 +39,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.annotation.HandlesTypes;
@ -217,12 +216,12 @@ public class AnnotationConfiguration extends AbstractConfiguration
for (int i=0; i<tmp.length; i++)
{
String s = tmp[i].trim();
_indexMap.put(s, Integer.valueOf(i));
_indexMap.put(s, i);
if ("*".equals(s))
{
if (_star != null)
throw new IllegalArgumentException("Duplicate wildcards in ServletContainerInitializer ordering "+ordering);
_star = Integer.valueOf(i);
_star = i;
}
}

View File

@ -26,7 +26,6 @@ import java.net.URL;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@ -570,22 +569,6 @@ public class AnnotationParser
if (existing != null)
LOG.warn("{} scanned from multiple locations: {}, {}", classname, existing, location);
}
/**
* Get the locations of the given classname. There may be more than one
* location if there are duplicates of the same class.
*
* @param classname the name of the class
* @return an immutable list of locations
*
* @deprecated List of duplicate locations no longer stored
*/
@Deprecated
public List<String> getParsedLocations (String classname)
{
return Collections.emptyList();
}
/**
* Parse a given class
@ -755,22 +738,6 @@ public class AnnotationParser
me.ifExceptionThrow();
}
/**
* Parse classes in the supplied classloader.
* Only class files in jar files will be scanned.
*
* @param handlers the handlers to look for classes in
* @param loader the classloader for the classes
* @param visitParents if true, visit parent classloaders too
* @param nullInclusive if true, an empty pattern means all names match, if false, none match
* @throws Exception if unable to parse
*/
@Deprecated
public void parse (final Set<? extends Handler> handlers, ClassLoader loader, boolean visitParents, boolean nullInclusive) throws Exception
{
throw new UnsupportedOperationException();
}
/**
* Parse classes in the supplied uris.
*

View File

@ -18,18 +18,12 @@
package org.eclipse.jetty.annotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContainerInitializer;
import org.eclipse.jetty.toolchain.test.FS;
@ -42,6 +36,11 @@ import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestAnnotationConfiguration
{
public class TestableAnnotationConfiguration extends AnnotationConfiguration
@ -121,7 +120,7 @@ public class TestAnnotationConfiguration
WebAppContext context25 = new WebAppContext();
context25.setClassLoader(Thread.currentThread().getContextClassLoader());
context25.setAttribute(AnnotationConfiguration.MULTI_THREADED, Boolean.FALSE);
context25.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, new Integer(0));
context25.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, 0);
context25.getMetaData().setWebXml(Resource.newResource(web25));
context25.getServletContext().setEffectiveMajorVersion(2);
context25.getServletContext().setEffectiveMinorVersion(5);
@ -133,7 +132,7 @@ public class TestAnnotationConfiguration
WebAppContext context25b = new WebAppContext();
context25b.setClassLoader(Thread.currentThread().getContextClassLoader());
context25b.setAttribute(AnnotationConfiguration.MULTI_THREADED, Boolean.FALSE);
context25b.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, new Integer(0));
context25b.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, 0);
context25b.setConfigurationDiscovered(true);
context25b.getMetaData().setWebXml(Resource.newResource(web25));
context25b.getServletContext().setEffectiveMajorVersion(2);
@ -146,7 +145,7 @@ public class TestAnnotationConfiguration
WebAppContext context31 = new WebAppContext();
context31.setClassLoader(Thread.currentThread().getContextClassLoader());
context31.setAttribute(AnnotationConfiguration.MULTI_THREADED, Boolean.FALSE);
context31.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, new Integer(0));
context31.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, 0);
context31.getMetaData().setWebXml(Resource.newResource(web31true));
context31.getServletContext().setEffectiveMajorVersion(3);
context31.getServletContext().setEffectiveMinorVersion(1);
@ -158,7 +157,7 @@ public class TestAnnotationConfiguration
WebAppContext context31b = new WebAppContext();
context31b.setClassLoader(Thread.currentThread().getContextClassLoader());
context31b.setAttribute(AnnotationConfiguration.MULTI_THREADED, Boolean.FALSE);
context31b.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, new Integer(0));
context31b.setAttribute(AnnotationConfiguration.MAX_SCAN_WAIT, 0);
context31b.getMetaData().setWebXml(Resource.newResource(web31false));
context31b.getServletContext().setEffectiveMajorVersion(3);
context31b.getServletContext().setEffectiveMinorVersion(1);

View File

@ -35,7 +35,7 @@ public class ResourceB extends ResourceA
private Integer f;//test no inheritance of private fields
@Resource
private Integer p = new Integer(8); //test no injection because no value
private Integer p = 8; //test no injection because no value
//test no annotation
public void z()

View File

@ -33,7 +33,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.Manifest;
import javax.servlet.Servlet;
import org.apache.tools.ant.AntClassLoader;
@ -250,12 +249,6 @@ public class AntWebAppContext extends WebAppContext
return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase);
}
@Override
protected Package getPackage(String name)
{
return super.getPackage(name);
}
@Override
protected Package[] getPackages()
{

View File

@ -119,7 +119,7 @@ public class DeploymentManager extends ContainerLifeCycle
void setLifeCycleNode(Node node)
{
this.lifecyleNode = node;
this.stateTimestamps.put(node,Long.valueOf(System.currentTimeMillis()));
this.stateTimestamps.put(node, System.currentTimeMillis());
}
}

View File

@ -216,7 +216,6 @@ Below is the relevant section taken from link:{GITBROWSEURL}/jetty-server/src/ma
<Set name="headerCacheSize"><Property name="jetty.httpConfig.headerCacheSize" default="4096" /></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" deprecated="jetty.delayDispatchUntilContent" default="true"/></Set>
<Set name="maxErrorDispatches"><Property name="jetty.httpConfig.maxErrorDispatches" default="10"/></Set>
<Set name="blockingTimeout"><Property name="jetty.httpConfig.blockingTimeout" default="-1"/></Set>
<Set name="persistentConnectionsEnabled"><Property name="jetty.httpConfig.persistentConnectionsEnabled" default="true"/></Set>
<Set name="cookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.cookieCompliance" default="RFC6265"/></Arg></Call></Set>

View File

@ -69,21 +69,8 @@ public enum HttpCompliance // TODO in Jetty-10 convert this enum to a class so t
RFC7230_LEGACY(sectionsBySpec("RFC7230,-METHOD_CASE_SENSITIVE")),
/** The RFC7230 support mode */
RFC7230(sectionsBySpec("RFC7230")),
/** Custom compliance mode that can be defined with System property <code>org.eclipse.jetty.http.HttpCompliance.CUSTOM0</code> */
@Deprecated
CUSTOM0(sectionsByProperty("CUSTOM0")),
/** Custom compliance mode that can be defined with System property <code>org.eclipse.jetty.http.HttpCompliance.CUSTOM1</code> */
@Deprecated
CUSTOM1(sectionsByProperty("CUSTOM1")),
/** Custom compliance mode that can be defined with System property <code>org.eclipse.jetty.http.HttpCompliance.CUSTOM2</code> */
@Deprecated
CUSTOM2(sectionsByProperty("CUSTOM2")),
/** Custom compliance mode that can be defined with System property <code>org.eclipse.jetty.http.HttpCompliance.CUSTOM3</code> */
@Deprecated
CUSTOM3(sectionsByProperty("CUSTOM3"));
RFC7230(sectionsBySpec("RFC7230"));
public static final String VIOLATIONS_ATTR = "org.eclipse.jetty.http.compliance.violations";
private static final Logger LOG = Log.getLogger(HttpParser.class);

View File

@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@ -34,9 +33,7 @@ import java.util.StringTokenizer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.eclipse.jetty.util.ArrayTernaryTrie;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.Trie;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -52,9 +49,6 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class HttpFields implements Iterable<HttpField>
{
@Deprecated
public static final String __separators = ", \t";
private static final Logger LOG = Log.getLogger(HttpFields.class);
private HttpField[] _fields;
@ -225,12 +219,6 @@ public class HttpFields implements Iterable<HttpField>
return false;
}
@Deprecated
public String getStringField(HttpHeader header)
{
return get(header);
}
public String get(HttpHeader header)
{
for (int i=0;i<_size;i++)
@ -242,12 +230,6 @@ public class HttpFields implements Iterable<HttpField>
return null;
}
@Deprecated
public String getStringField(String name)
{
return get(name);
}
public String get(String header)
{
for (int i=0;i<_size;i++)

View File

@ -133,20 +133,6 @@ public class HttpGenerator
_trailers = null;
}
/* ------------------------------------------------------------ */
@Deprecated
public boolean getSendServerVersion ()
{
return (_send&SEND_SERVER)!=0;
}
/* ------------------------------------------------------------ */
@Deprecated
public void setSendServerVersion (boolean sendServerVersion)
{
throw new UnsupportedOperationException();
}
/* ------------------------------------------------------------ */
public State getState()
{
@ -385,14 +371,6 @@ public class HttpGenerator
}
/* ------------------------------------------------------------ */
@Deprecated
public Result generateResponse(MetaData.Response info, ByteBuffer header, ByteBuffer chunk, ByteBuffer content, boolean last) throws IOException
{
return generateResponse(info,false,header,chunk,content,last);
}
/* ------------------------------------------------------------ */
public Result generateResponse(MetaData.Response info, boolean head, ByteBuffer header, ByteBuffer chunk, ByteBuffer content, boolean last) throws IOException
{

View File

@ -1908,17 +1908,6 @@ public class HttpParser
* @param failure the failure with the bad message information
*/
public default void badMessage(BadMessageException failure)
{
badMessage(failure.getCode(), failure.getReason());
}
/**
* @param status The status to send
* @param reason The reason for the bad message
* @deprecated use {@link #badMessage(BadMessageException)} instead
*/
@Deprecated
public default void badMessage(int status, String reason)
{
}
@ -1964,12 +1953,9 @@ public class HttpParser
/* ------------------------------------------------------------------------------- */
public interface ComplianceHandler extends HttpHandler
{
@Deprecated
public default void onComplianceViolation(HttpCompliance compliance, HttpCompliance required, String reason) {}
public default void onComplianceViolation(HttpCompliance compliance, HttpComplianceSection violation, String details)
{
onComplianceViolation(compliance,HttpCompliance.requiredCompliance(violation), details);
}
}

View File

@ -62,15 +62,9 @@ public class HttpStatus
public final static int GONE_410 = 410;
public final static int LENGTH_REQUIRED_411 = 411;
public final static int PRECONDITION_FAILED_412 = 412;
@Deprecated
public final static int REQUEST_ENTITY_TOO_LARGE_413 = 413;
public final static int PAYLOAD_TOO_LARGE_413 = 413;
@Deprecated
public final static int REQUEST_URI_TOO_LONG_414 = 414;
public final static int URI_TOO_LONG_414 = 414;
public final static int UNSUPPORTED_MEDIA_TYPE_415 = 415;
@Deprecated
public final static int REQUESTED_RANGE_NOT_SATISFIABLE_416 = 416;
public final static int RANGE_NOT_SATISFIABLE_416 = 416;
public final static int EXPECTATION_FAILED_417 = 417;
public final static int IM_A_TEAPOT_418 = 418;

View File

@ -193,15 +193,6 @@ public class HttpURI
parse(uri.startsWith("/")?State.PATH:State.START,uri);
}
/* ------------------------------------------------------------ */
@Deprecated
public void parseConnect(String uri)
{
clear();
_uri=uri;
_path=uri;
}
/* ------------------------------------------------------------ */
public void parse(String uri, int offset, int length)
{

View File

@ -59,16 +59,6 @@ public class MetaData implements Iterable<HttpField>
return false;
}
/**
* @deprecated use {@link #getHttpVersion()} instead
* @return the HTTP version of this MetaData object
*/
@Deprecated
public HttpVersion getVersion()
{
return getHttpVersion();
}
/**
* @return the HTTP version of this MetaData object
*/

View File

@ -519,12 +519,6 @@ public class MimeTypes
return __assumedEncodings;
}
@Deprecated
public static String inferCharsetFromContentType(String contentType)
{
return getCharsetAssumedFromContentType(contentType);
}
public static String getCharsetInferredFromContentType(String contentType)
{
return __inferredEncodings.get(contentType);

View File

@ -1,38 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.http;
/**
* The compliance level for parsing <code>multiPart/form-data</code>
*
*/
public enum MultiPartFormDataCompliance
{
/**
* Legacy <code>multiPart/form-data</code> parsing which is slow but forgiving.
* It will accept non compliant preambles and inconsistent line termination.
* @see MultiPartInputStreamParser
*/
LEGACY,
/**
* RFC7578 compliant parsing that is a fast but strict parser.
* @see org.eclipse.jetty.http.MultiPartFormInputStream
*/
RFC7578
}

View File

@ -35,7 +35,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Part;
@ -372,27 +371,6 @@ public class MultiPartFormInputStream
return true;
}
/**
* Get the already parsed parts.
*
* @return the parts that were parsed
*/
@Deprecated
public Collection<Part> getParsedParts()
{
if (_parts == null)
return Collections.emptyList();
Collection<List<Part>> values = _parts.values();
List<Part> parts = new ArrayList<>();
for (List<Part> o : values)
{
List<Part> asList = LazyList.getList(o, false);
parts.addAll(asList);
}
return parts;
}
/**
* Delete any tmp storage for parts, and clear out the parts list.
*/

View File

@ -1,991 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.http;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Part;
import org.eclipse.jetty.http.ReadLineInputStream.Termination;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* MultiPartInputStream
*
* Handle a MultiPart Mime input stream, breaking it up on the boundary into files and strings.
*
* Non Compliance warnings are documented by the method {@link #getNonComplianceWarnings()}
*
* @deprecated Replaced by org.eclipse.jetty.http.MultiPartFormInputStream
* The code for MultiPartInputStream is slower than its replacement MultiPartFormInputStream. However
* this class accepts formats non compliant the RFC that the new MultiPartFormInputStream does not accept.
*/
@Deprecated
public class MultiPartInputStreamParser
{
private static final Logger LOG = Log.getLogger(MultiPartInputStreamParser.class);
public static final MultipartConfigElement __DEFAULT_MULTIPART_CONFIG = new MultipartConfigElement(System.getProperty("java.io.tmpdir"));
public static final MultiMap<Part> EMPTY_MAP = new MultiMap(Collections.emptyMap());
protected InputStream _in;
protected MultipartConfigElement _config;
protected String _contentType;
protected MultiMap<Part> _parts;
protected Exception _err;
protected File _tmpDir;
protected File _contextTmpDir;
protected boolean _deleteOnExit;
protected boolean _writeFilesWithFilenames;
protected boolean _parsed;
private EnumSet<NonCompliance> nonComplianceWarnings = EnumSet.noneOf(NonCompliance.class);
public enum NonCompliance
{
CR_LINE_TERMINATION("https://tools.ietf.org/html/rfc2046#section-4.1.1"),
LF_LINE_TERMINATION("https://tools.ietf.org/html/rfc2046#section-4.1.1"),
NO_CRLF_AFTER_PREAMBLE("https://tools.ietf.org/html/rfc2046#section-5.1.1"),
BASE64_TRANSFER_ENCODING("https://tools.ietf.org/html/rfc7578#section-4.7"),
QUOTED_PRINTABLE_TRANSFER_ENCODING("https://tools.ietf.org/html/rfc7578#section-4.7");
final String _rfcRef;
NonCompliance(String rfcRef)
{
_rfcRef = rfcRef;
}
public String getURL()
{
return _rfcRef;
}
}
/**
* @return an EnumSet of non compliances with the RFC that were accepted by this parser
*/
public EnumSet<NonCompliance> getNonComplianceWarnings()
{
return nonComplianceWarnings;
}
public class MultiPart implements Part
{
protected String _name;
protected String _filename;
protected File _file;
protected OutputStream _out;
protected ByteArrayOutputStream2 _bout;
protected String _contentType;
protected MultiMap<String> _headers;
protected long _size = 0;
protected boolean _temporary = true;
public MultiPart (String name, String filename)
throws IOException
{
_name = name;
_filename = filename;
}
@Override
public String toString()
{
return String.format("Part{n=%s,fn=%s,ct=%s,s=%d,t=%b,f=%s}",_name,_filename,_contentType,_size,_temporary,_file);
}
protected void setContentType (String contentType)
{
_contentType = contentType;
}
protected void open()
throws IOException
{
//We will either be writing to a file, if it has a filename on the content-disposition
//and otherwise a byte-array-input-stream, OR if we exceed the getFileSizeThreshold, we
//will need to change to write to a file.
if (isWriteFilesWithFilenames() && _filename != null && _filename.trim().length() > 0)
{
createFile();
}
else
{
//Write to a buffer in memory until we discover we've exceed the
//MultipartConfig fileSizeThreshold
_out = _bout= new ByteArrayOutputStream2();
}
}
protected void close()
throws IOException
{
_out.close();
}
protected void write (int b)
throws IOException
{
if (MultiPartInputStreamParser.this._config.getMaxFileSize() > 0 && _size + 1 > MultiPartInputStreamParser.this._config.getMaxFileSize())
throw new IllegalStateException ("Multipart Mime part "+_name+" exceeds max filesize");
if (MultiPartInputStreamParser.this._config.getFileSizeThreshold() > 0 && _size + 1 > MultiPartInputStreamParser.this._config.getFileSizeThreshold() && _file==null)
createFile();
_out.write(b);
_size ++;
}
protected void write (byte[] bytes, int offset, int length)
throws IOException
{
if (MultiPartInputStreamParser.this._config.getMaxFileSize() > 0 && _size + length > MultiPartInputStreamParser.this._config.getMaxFileSize())
throw new IllegalStateException ("Multipart Mime part "+_name+" exceeds max filesize");
if (MultiPartInputStreamParser.this._config.getFileSizeThreshold() > 0 && _size + length > MultiPartInputStreamParser.this._config.getFileSizeThreshold() && _file==null)
createFile();
_out.write(bytes, offset, length);
_size += length;
}
protected void createFile ()
throws IOException
{
/* Some statics just to make the code below easier to understand
* This get optimized away during the compile anyway */
final boolean USER = true;
final boolean WORLD = false;
_file = File.createTempFile("MultiPart", "", MultiPartInputStreamParser.this._tmpDir);
_file.setReadable(false,WORLD); // (reset) disable it for everyone first
_file.setReadable(true,USER); // enable for user only
if (_deleteOnExit)
_file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(_file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
if (_size > 0 && _out != null)
{
//already written some bytes, so need to copy them into the file
_out.flush();
_bout.writeTo(bos);
_out.close();
}
_bout = null;
_out = bos;
}
protected void setHeaders(MultiMap<String> headers)
{
_headers = headers;
}
/**
* @see javax.servlet.http.Part#getContentType()
*/
@Override
public String getContentType()
{
return _contentType;
}
/**
* @see javax.servlet.http.Part#getHeader(java.lang.String)
*/
@Override
public String getHeader(String name)
{
if (name == null)
return null;
return _headers.getValue(name.toLowerCase(Locale.ENGLISH), 0);
}
/**
* @see javax.servlet.http.Part#getHeaderNames()
*/
@Override
public Collection<String> getHeaderNames()
{
return _headers.keySet();
}
/**
* @see javax.servlet.http.Part#getHeaders(java.lang.String)
*/
@Override
public Collection<String> getHeaders(String name)
{
return _headers.getValues(name);
}
/**
* @see javax.servlet.http.Part#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException
{
if (_file != null)
{
//written to a file, whether temporary or not
return new BufferedInputStream (new FileInputStream(_file));
}
else
{
//part content is in memory
return new ByteArrayInputStream(_bout.getBuf(),0,_bout.size());
}
}
/**
* @see javax.servlet.http.Part#getSubmittedFileName()
*/
@Override
public String getSubmittedFileName()
{
return getContentDispositionFilename();
}
public byte[] getBytes()
{
if (_bout!=null)
return _bout.toByteArray();
return null;
}
/**
* @see javax.servlet.http.Part#getName()
*/
@Override
public String getName()
{
return _name;
}
/**
* @see javax.servlet.http.Part#getSize()
*/
@Override
public long getSize()
{
return _size;
}
/**
* @see javax.servlet.http.Part#write(java.lang.String)
*/
@Override
public void write(String fileName) throws IOException
{
if (_file == null)
{
_temporary = false;
//part data is only in the ByteArrayOutputStream and never been written to disk
_file = new File (_tmpDir, fileName);
BufferedOutputStream bos = null;
try
{
bos = new BufferedOutputStream(new FileOutputStream(_file));
_bout.writeTo(bos);
bos.flush();
}
finally
{
if (bos != null)
bos.close();
_bout = null;
}
}
else
{
//the part data is already written to a temporary file, just rename it
_temporary = false;
Path src = _file.toPath();
Path target = src.resolveSibling(fileName);
Files.move(src, target, StandardCopyOption.REPLACE_EXISTING);
_file = target.toFile();
}
}
/**
* Remove the file, whether or not Part.write() was called on it
* (ie no longer temporary)
* @see javax.servlet.http.Part#delete()
*/
@Override
public void delete() throws IOException
{
if (_file != null && _file.exists())
_file.delete();
}
/**
* Only remove tmp files.
*
* @throws IOException if unable to delete the file
*/
public void cleanUp() throws IOException
{
if (_temporary && _file != null && _file.exists())
_file.delete();
}
/**
* Get the file
* @return the file, if any, the data has been written to.
*/
public File getFile ()
{
return _file;
}
/**
* Get the filename from the content-disposition.
* @return null or the filename
*/
public String getContentDispositionFilename ()
{
return _filename;
}
}
/**
* @param in Request input stream
* @param contentType Content-Type header
* @param config MultipartConfigElement
* @param contextTmpDir javax.servlet.context.tempdir
*/
public MultiPartInputStreamParser (InputStream in, String contentType, MultipartConfigElement config, File contextTmpDir)
{
_contentType = contentType;
_config = config;
_contextTmpDir = contextTmpDir;
if (_contextTmpDir == null)
_contextTmpDir = new File (System.getProperty("java.io.tmpdir"));
if (_config == null)
_config = new MultipartConfigElement(_contextTmpDir.getAbsolutePath());
if (in instanceof ServletInputStream)
{
if (((ServletInputStream)in).isFinished())
{
_parts = EMPTY_MAP;
_parsed = true;
return;
}
}
_in = new ReadLineInputStream(in);
}
/**
* Get the already parsed parts.
* @return the parts that were parsed
*/
public Collection<Part> getParsedParts()
{
if (_parts == null)
return Collections.emptyList();
Collection<List<Part>> values = _parts.values();
List<Part> parts = new ArrayList<>();
for (List<Part> o: values)
{
List<Part> asList = LazyList.getList(o, false);
parts.addAll(asList);
}
return parts;
}
/**
* Delete any tmp storage for parts, and clear out the parts list.
*/
public void deleteParts ()
{
if(!_parsed)
return;
Collection<Part> parts = getParsedParts();
MultiException err = new MultiException();
for (Part p:parts)
{
try
{
((MultiPartInputStreamParser.MultiPart)p).cleanUp();
}
catch(Exception e)
{
err.add(e);
}
}
_parts.clear();
err.ifExceptionThrowRuntime();
}
/**
* Parse, if necessary, the multipart data and return the list of Parts.
*
* @return the parts
* @throws IOException if unable to get the parts
*/
public Collection<Part> getParts()
throws IOException
{
if(!_parsed)
parse();
throwIfError();
Collection<List<Part>> values = _parts.values();
List<Part> parts = new ArrayList<>();
for (List<Part> o: values)
{
List<Part> asList = LazyList.getList(o, false);
parts.addAll(asList);
}
return parts;
}
/**
* Get the named Part.
*
* @param name the part name
* @return the parts
* @throws IOException if unable to get the part
*/
public Part getPart(String name)
throws IOException
{
if(!_parsed)
parse();
throwIfError();
return _parts.getValue(name, 0);
}
/**
* Throws an exception if one has been latched.
*
* @throws IOException the exception (if present)
*/
protected void throwIfError ()
throws IOException
{
if (_err != null)
{
if (_err instanceof IOException)
throw (IOException)_err;
if (_err instanceof IllegalStateException)
throw (IllegalStateException)_err;
throw new IllegalStateException(_err);
}
}
/**
* Parse, if necessary, the multipart stream.
*
*/
protected void parse ()
{
//have we already parsed the input?
if (_parsed)
return;
_parsed = true;
//initialize
long total = 0; //keep running total of size of bytes read from input and throw an exception if exceeds MultipartConfigElement._maxRequestSize
_parts = new MultiMap<>();
//if its not a multipart request, don't parse it
if (_contentType == null || !_contentType.startsWith("multipart/form-data"))
return;
try
{
//sort out the location to which to write the files
if (_config.getLocation() == null)
_tmpDir = _contextTmpDir;
else if ("".equals(_config.getLocation()))
_tmpDir = _contextTmpDir;
else
{
File f = new File (_config.getLocation());
if (f.isAbsolute())
_tmpDir = f;
else
_tmpDir = new File (_contextTmpDir, _config.getLocation());
}
if (!_tmpDir.exists())
_tmpDir.mkdirs();
String contentTypeBoundary = "";
int bstart = _contentType.indexOf("boundary=");
if (bstart >= 0)
{
int bend = _contentType.indexOf(";", bstart);
bend = (bend < 0? _contentType.length(): bend);
contentTypeBoundary = QuotedStringTokenizer.unquote(value(_contentType.substring(bstart,bend)).trim());
}
String boundary="--"+contentTypeBoundary;
String lastBoundary=boundary+"--";
byte[] byteBoundary=lastBoundary.getBytes(StandardCharsets.ISO_8859_1);
// Get first boundary
String line = null;
try
{
line=((ReadLineInputStream)_in).readLine();
}
catch (IOException e)
{
LOG.warn("Badly formatted multipart request");
throw e;
}
if (line == null)
throw new IOException("Missing content for multipart request");
boolean badFormatLogged = false;
String untrimmed = line;
line=line.trim();
while (line != null && !line.equals(boundary) && !line.equals(lastBoundary))
{
if (!badFormatLogged)
{
LOG.warn("Badly formatted multipart request");
badFormatLogged = true;
}
line=((ReadLineInputStream)_in).readLine();
untrimmed = line;
if(line!=null)
line = line.trim();
}
if (line == null || line.length() == 0)
throw new IOException("Missing initial multi part boundary");
// Empty multipart.
if (line.equals(lastBoundary))
return;
// check compliance of preamble
if (Character.isWhitespace(untrimmed.charAt(0)))
nonComplianceWarnings.add(NonCompliance.NO_CRLF_AFTER_PREAMBLE);
// Read each part
boolean lastPart=false;
outer:while(!lastPart)
{
String contentDisposition=null;
String contentType=null;
String contentTransferEncoding=null;
MultiMap<String> headers = new MultiMap<>();
while(true)
{
line=((ReadLineInputStream)_in).readLine();
//No more input
if(line==null)
break outer;
//end of headers:
if("".equals(line))
break;
total += line.length();
if (_config.getMaxRequestSize() > 0 && total > _config.getMaxRequestSize())
throw new IllegalStateException ("Request exceeds maxRequestSize ("+_config.getMaxRequestSize()+")");
//get content-disposition and content-type
int c=line.indexOf(':',0);
if(c>0)
{
String key=line.substring(0,c).trim().toLowerCase(Locale.ENGLISH);
String value=line.substring(c+1,line.length()).trim();
headers.put(key, value);
if (key.equalsIgnoreCase("content-disposition"))
contentDisposition=value;
if (key.equalsIgnoreCase("content-type"))
contentType = value;
if(key.equals("content-transfer-encoding"))
contentTransferEncoding=value;
}
}
// Extract content-disposition
boolean form_data=false;
if(contentDisposition==null)
{
throw new IOException("Missing content-disposition");
}
QuotedStringTokenizer tok=new QuotedStringTokenizer(contentDisposition,";", false, true);
String name=null;
String filename=null;
while(tok.hasMoreTokens())
{
String t=tok.nextToken().trim();
String tl=t.toLowerCase(Locale.ENGLISH);
if(tl.startsWith("form-data"))
form_data=true;
else if(tl.startsWith("name="))
name=value(t);
else if(tl.startsWith("filename="))
filename=filenameValue(t);
}
// Check disposition
if(!form_data)
{
continue;
}
//It is valid for reset and submit buttons to have an empty name.
//If no name is supplied, the browser skips sending the info for that field.
//However, if you supply the empty string as the name, the browser sends the
//field, with name as the empty string. So, only continue this loop if we
//have not yet seen a name field.
if(name==null)
{
continue;
}
//Have a new Part
MultiPart part = new MultiPart(name, filename);
part.setHeaders(headers);
part.setContentType(contentType);
_parts.add(name, part);
part.open();
InputStream partInput = null;
if ("base64".equalsIgnoreCase(contentTransferEncoding))
{
nonComplianceWarnings.add(NonCompliance.BASE64_TRANSFER_ENCODING);
partInput = new Base64InputStream((ReadLineInputStream)_in);
}
else if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding))
{
nonComplianceWarnings.add(NonCompliance.QUOTED_PRINTABLE_TRANSFER_ENCODING);
partInput = new FilterInputStream(_in)
{
@Override
public int read() throws IOException
{
int c = in.read();
if (c >= 0 && c == '=')
{
int hi = in.read();
int lo = in.read();
if (hi < 0 || lo < 0)
{
throw new IOException("Unexpected end to quoted-printable byte");
}
char[] chars = new char[] { (char)hi, (char)lo };
c = Integer.parseInt(new String(chars),16);
}
return c;
}
};
}
else
partInput = _in;
try
{
int state=-2;
int c;
boolean cr=false;
boolean lf=false;
// loop for all lines
while(true)
{
int b=0;
while((c=(state!=-2)?state:partInput.read())!=-1)
{
total ++;
if (_config.getMaxRequestSize() > 0 && total > _config.getMaxRequestSize())
throw new IllegalStateException("Request exceeds maxRequestSize ("+_config.getMaxRequestSize()+")");
state=-2;
// look for CR and/or LF
if(c==13||c==10)
{
if(c==13)
{
partInput.mark(1);
int tmp=partInput.read();
if (tmp!=10)
partInput.reset();
else
state=tmp;
}
break;
}
// Look for boundary
if(b>=0&&b<byteBoundary.length&&c==byteBoundary[b])
{
b++;
}
else
{
// Got a character not part of the boundary, so we don't have the boundary marker.
// Write out as many chars as we matched, then the char we're looking at.
if(cr)
part.write(13);
if(lf)
part.write(10);
cr=lf=false;
if(b>0)
part.write(byteBoundary,0,b);
b=-1;
part.write(c);
}
}
// Check for incomplete boundary match, writing out the chars we matched along the way
if((b>0&&b<byteBoundary.length-2)||(b==byteBoundary.length-1))
{
if(cr)
part.write(13);
if(lf)
part.write(10);
cr=lf=false;
part.write(byteBoundary,0,b);
b=-1;
}
// Boundary match. If we've run out of input or we matched the entire final boundary marker, then this is the last part.
if(b>0||c==-1)
{
if(b==byteBoundary.length)
lastPart=true;
if(state==10)
state=-2;
break;
}
// handle CR LF
if(cr)
part.write(13);
if(lf)
part.write(10);
cr=(c==13);
lf=(c==10||state==10);
if(state==10)
state=-2;
}
}
finally
{
part.close();
}
}
if (lastPart)
{
while(line!=null)
line=((ReadLineInputStream)_in).readLine();
EnumSet<Termination> term = ((ReadLineInputStream)_in).getLineTerminations();
if(term.contains(Termination.CR))
nonComplianceWarnings.add(NonCompliance.CR_LINE_TERMINATION);
if(term.contains(Termination.LF))
nonComplianceWarnings.add(NonCompliance.LF_LINE_TERMINATION);
}
else
throw new IOException("Incomplete parts");
}
catch (Exception e)
{
_err = e;
}
}
public void setDeleteOnExit(boolean deleteOnExit)
{
_deleteOnExit = deleteOnExit;
}
public void setWriteFilesWithFilenames (boolean writeFilesWithFilenames)
{
_writeFilesWithFilenames = writeFilesWithFilenames;
}
public boolean isWriteFilesWithFilenames ()
{
return _writeFilesWithFilenames;
}
public boolean isDeleteOnExit()
{
return _deleteOnExit;
}
/* ------------------------------------------------------------ */
private String value(String nameEqualsValue)
{
int idx = nameEqualsValue.indexOf('=');
String value = nameEqualsValue.substring(idx+1).trim();
return QuotedStringTokenizer.unquoteOnly(value);
}
/* ------------------------------------------------------------ */
private String filenameValue(String nameEqualsValue)
{
int idx = nameEqualsValue.indexOf('=');
String value = nameEqualsValue.substring(idx+1).trim();
if (value.matches(".??[a-z,A-Z]\\:\\\\[^\\\\].*"))
{
//incorrectly escaped IE filenames that have the whole path
//we just strip any leading & trailing quotes and leave it as is
char first=value.charAt(0);
if (first=='"' || first=='\'')
value=value.substring(1);
char last=value.charAt(value.length()-1);
if (last=='"' || last=='\'')
value = value.substring(0,value.length()-1);
return value;
}
else
//unquote the string, but allow any backslashes that don't
//form a valid escape sequence to remain as many browsers
//even on *nix systems will not escape a filename containing
//backslashes
return QuotedStringTokenizer.unquoteOnly(value, true);
}
private static class Base64InputStream extends InputStream
{
ReadLineInputStream _in;
String _line;
byte[] _buffer;
int _pos;
public Base64InputStream(ReadLineInputStream rlis)
{
_in = rlis;
}
@Override
public int read() throws IOException
{
if (_buffer==null || _pos>= _buffer.length)
{
//Any CR and LF will be consumed by the readLine() call.
//We need to put them back into the bytes returned from this
//method because the parsing of the multipart content uses them
//as markers to determine when we've reached the end of a part.
_line = _in.readLine();
if (_line==null)
return -1; //nothing left
if (_line.startsWith("--"))
_buffer=(_line+"\r\n").getBytes(); //boundary marking end of part
else if (_line.length()==0)
_buffer="\r\n".getBytes(); //blank line
else
{
ByteArrayOutputStream baos = new ByteArrayOutputStream((4*_line.length()/3)+2);
B64Code.decode(_line, baos);
baos.write(13);
baos.write(10);
_buffer = baos.toByteArray();
}
_pos=0;
}
return _buffer[_pos++];
}
}
}

View File

@ -18,13 +18,13 @@
package org.eclipse.jetty.http;
import static java.lang.Integer.MIN_VALUE;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import static java.lang.Integer.MIN_VALUE;
/* ------------------------------------------------------------ */
/**
* Implements a quoted comma separated list of quality values
@ -36,10 +36,10 @@ import java.util.function.Function;
* @see "https://tools.ietf.org/html/rfc7231#section-5.3.1"
*/
public class QuotedQualityCSV extends QuotedCSV implements Iterable<String>
{
private final static Double ZERO=new Double(0.0);
private final static Double ONE=new Double(1.0);
{
private final static Double ZERO = 0.0D;
private final static Double ONE = 1.0D;
/**
* Function to apply a most specific MIME encoding secondary ordering
@ -121,8 +121,8 @@ public class QuotedQualityCSV extends QuotedCSV implements Iterable<String>
try
{
q=(_keepQuotes && buffer.charAt(paramValue)=='"')
?new Double(buffer.substring(paramValue+1,buffer.length()-1))
:new Double(buffer.substring(paramValue));
? (Double) Double.parseDouble(buffer.substring(paramValue + 1, buffer.length() - 1))
: (Double) Double.parseDouble(buffer.substring(paramValue));
}
catch(Exception e)
{

View File

@ -1,163 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.http;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
/**
* ReadLineInputStream
*
* Read from an input stream, accepting CR/LF, LF or just CR.
*/
@Deprecated
public class ReadLineInputStream extends BufferedInputStream
{
boolean _seenCRLF;
boolean _skipLF;
private EnumSet<Termination> _lineTerminations = EnumSet.noneOf(Termination.class);
public EnumSet<Termination> getLineTerminations() { return _lineTerminations; }
public enum Termination
{
CRLF,
LF,
CR,
EOF
}
public ReadLineInputStream(InputStream in)
{
super(in);
}
public ReadLineInputStream(InputStream in, int size)
{
super(in,size);
}
public String readLine() throws IOException
{
mark(buf.length);
while (true)
{
int b=super.read();
if (markpos < 0)
throw new IOException("Buffer size exceeded: no line terminator");
if(_skipLF && b!='\n')
_lineTerminations.add(Termination.CR);
if (b==-1)
{
int m=markpos;
markpos=-1;
if (pos>m)
{
_lineTerminations.add(Termination.EOF);
return new String(buf,m,pos-m, StandardCharsets.UTF_8);
}
return null;
}
if (b=='\r')
{
int p=pos;
// if we have seen CRLF before, hungrily consume LF
if (_seenCRLF && pos<count)
{
if (buf[pos]=='\n')
{
_lineTerminations.add(Termination.CRLF);
pos+=1;
}
else
{
_lineTerminations.add(Termination.CR);
}
}
else
_skipLF=true;
int m=markpos;
markpos=-1;
return new String(buf,m,p-m-1,StandardCharsets.UTF_8);
}
if (b=='\n')
{
if (_skipLF)
{
_skipLF=false;
_seenCRLF=true;
markpos++;
_lineTerminations.add(Termination.CRLF);
continue;
}
int m=markpos;
markpos=-1;
_lineTerminations.add(Termination.LF);
return new String(buf,m,pos-m-1,StandardCharsets.UTF_8);
}
}
}
@Override
public synchronized int read() throws IOException
{
int b = super.read();
if (_skipLF)
{
_skipLF=false;
if (_seenCRLF && b=='\n')
b=super.read();
}
return b;
}
@Override
public synchronized int read(byte[] buf, int off, int len) throws IOException
{
if (_skipLF && len>0)
{
_skipLF=false;
if (_seenCRLF)
{
int b = super.read();
if (b==-1)
return -1;
if (b!='\n')
{
buf[off]=(byte)(0xff&b);
return 1+super.read(buf,off+1,len-1);
}
}
}
return super.read(buf,off,len);
}
}

View File

@ -18,6 +18,18 @@
package org.eclipse.jetty.http;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jetty.http.HttpParser.State;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.eclipse.jetty.http.HttpComplianceSection.NO_FIELD_FOLDING;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
@ -29,26 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jetty.http.HttpParser.State;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class HttpParserTest
{
static
{
HttpCompliance.CUSTOM0.sections().remove(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME);
}
/**
* Parse until {@link State#END} state.
* If the parser is already in the END state, then it is {@link HttpParser#reset()} and re-parsed.
@ -450,74 +444,6 @@ public class HttpParserTest
assertEquals(2, _headers);
}
@Test
public void testSpaceinNameCustom0() throws Exception
{
ByteBuffer buffer = BufferUtil.toBuffer(
"GET / HTTP/1.0\r\n" +
"Host: localhost\r\n" +
"Name with space: value\r\n" +
"Other: value\r\n" +
"\r\n");
HttpParser.RequestHandler handler = new Handler();
HttpParser parser = new HttpParser(handler,HttpCompliance.CUSTOM0);
parseAll(parser, buffer);
assertThat(_bad, containsString("Illegal character"));
assertThat(_complianceViolation,contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME));
}
@Test
public void testNoColonCustom0() throws Exception
{
ByteBuffer buffer = BufferUtil.toBuffer(
"GET / HTTP/1.0\r\n" +
"Host: localhost\r\n" +
"Name \r\n" +
"Other: value\r\n" +
"\r\n");
HttpParser.RequestHandler handler = new Handler();
HttpParser parser = new HttpParser(handler,HttpCompliance.CUSTOM0);
parseAll(parser, buffer);
assertThat(_bad, containsString("Illegal character"));
assertThat(_complianceViolation,contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME));
}
@Test
public void testTrailingSpacesInHeaderNameInCustom0Mode() throws Exception
{
ByteBuffer buffer = BufferUtil.toBuffer(
"HTTP/1.1 204 No Content\r\n" +
"Access-Control-Allow-Headers : Origin\r\n" +
"Other\t : value\r\n" +
"\r\n");
HttpParser.ResponseHandler handler = new Handler();
HttpParser parser = new HttpParser(handler, -1, HttpCompliance.CUSTOM0);
parseAll(parser, buffer);
assertTrue(_headerCompleted);
assertTrue(_messageCompleted);
assertEquals("HTTP/1.1", _methodOrVersion);
assertEquals("204", _uriOrStatus);
assertEquals("No Content", _versionOrReason);
assertEquals(null, _content);
assertEquals(1, _headers);
System.out.println(Arrays.asList(_hdr));
System.out.println(Arrays.asList(_val));
assertEquals("Access-Control-Allow-Headers", _hdr[0]);
assertEquals("Origin", _val[0]);
assertEquals("Other", _hdr[1]);
assertEquals("value", _val[1]);
assertThat(_complianceViolation, contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME,HttpComplianceSection.NO_WS_AFTER_FIELD_NAME));
}
@Test
public void testTrailingSpacesInHeaderNameNoCustom0() throws Exception
{

View File

@ -33,7 +33,6 @@ import java.util.Locale;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
@ -154,34 +153,6 @@ public class MultiPartCaptureTest
public WorkDir testingDir;
@ParameterizedTest
@MethodSource("data")
public void testUtilParse(String rawPrefix) throws Exception
{
Path multipartRawFile = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".raw");
Path expectationPath = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".expected.txt");
MultipartExpectations multipartExpectations = new MultipartExpectations(expectationPath);
Path outputDir = testingDir.getEmptyPathDir();
MultipartConfigElement config = newMultipartConfigElement(outputDir);
try (InputStream in = Files.newInputStream(multipartRawFile))
{
MultiPartInputStreamParser parser = new MultiPartInputStreamParser(in,multipartExpectations.contentType,config,outputDir.toFile());
multipartExpectations.checkParts(parser.getParts(),s->
{
try
{
return parser.getPart(s);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
});
}
}
@ParameterizedTest
@MethodSource("data")
public void testHttpParse(String rawPrefix) throws Exception

View File

@ -1,263 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.http.internal;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.http.ReadLineInputStream;
import org.eclipse.jetty.http.ReadLineInputStream.Termination;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReadLineInputStreamTest
{
BlockingArrayQueue<String> _queue = new BlockingArrayQueue<>();
PipedInputStream _pin;
volatile PipedOutputStream _pout;
ReadLineInputStream _in;
volatile Thread _writer;
@BeforeEach
public void before() throws Exception
{
_queue.clear();
_pin=new PipedInputStream();
_pout=new PipedOutputStream(_pin);
_in=new ReadLineInputStream(_pin);
_writer=new Thread()
{
@Override
public void run()
{
try
{
OutputStream out=_pout;
while (out!=null)
{
String s = _queue.poll(100,TimeUnit.MILLISECONDS);
if (s!=null)
{
if ("__CLOSE__".equals(s))
_pout.close();
else
{
_pout.write(s.getBytes(StandardCharsets.UTF_8));
Thread.sleep(50);
}
}
out=_pout;
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
_writer=null;
}
}
};
_writer.start();
}
@AfterEach
public void after() throws Exception
{
_pout=null;
while (_writer!=null)
Thread.sleep(10);
}
@Test
public void testCR() throws Exception
{
_queue.add("\rHello\rWorld\r\r");
_queue.add("__CLOSE__");
assertEquals("",_in.readLine());
assertEquals("Hello",_in.readLine());
assertEquals("World",_in.readLine());
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.CR), _in.getLineTerminations());
}
@Test
public void testLF() throws Exception
{
_queue.add("\nHello\nWorld\n\n");
_queue.add("__CLOSE__");
assertEquals("",_in.readLine());
assertEquals("Hello",_in.readLine());
assertEquals("World",_in.readLine());
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.LF), _in.getLineTerminations());
}
@Test
public void testCRLF() throws Exception
{
_queue.add("\r\nHello\r\nWorld\r\n\r\n");
_queue.add("__CLOSE__");
assertEquals("",_in.readLine());
assertEquals("Hello",_in.readLine());
assertEquals("World",_in.readLine());
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.CRLF), _in.getLineTerminations());
}
@Test
public void testCRBlocking() throws Exception
{
_queue.add("");
_queue.add("\r");
_queue.add("Hello");
_queue.add("\rWorld\r");
_queue.add("\r");
_queue.add("__CLOSE__");
assertEquals("",_in.readLine());
assertEquals("Hello",_in.readLine());
assertEquals("World",_in.readLine());
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.CR), _in.getLineTerminations());
}
@Test
public void testLFBlocking() throws Exception
{
_queue.add("");
_queue.add("\n");
_queue.add("Hello");
_queue.add("\nWorld\n");
_queue.add("\n");
_queue.add("__CLOSE__");
assertEquals("",_in.readLine());
assertEquals("Hello",_in.readLine());
assertEquals("World",_in.readLine());
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.LF), _in.getLineTerminations());
}
@Test
public void testCRLFBlocking() throws Exception
{
_queue.add("\r");
_queue.add("\nHello");
_queue.add("\r\nWorld\r");
_queue.add("\n\r");
_queue.add("\n");
_queue.add("");
_queue.add("__CLOSE__");
assertEquals("",_in.readLine());
assertEquals("Hello",_in.readLine());
assertEquals("World",_in.readLine());
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.CRLF), _in.getLineTerminations());
}
@Test
public void testHeaderLFBodyLF() throws Exception
{
_queue.add("Header\n");
_queue.add("\n");
_queue.add("\nBody\n");
_queue.add("\n");
_queue.add("__CLOSE__");
assertEquals("Header",_in.readLine());
assertEquals("",_in.readLine());
byte[] body = new byte[6];
_in.read(body);
assertEquals("\nBody\n",new String(body,0,6,StandardCharsets.UTF_8));
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.LF), _in.getLineTerminations());
}
@Test
public void testHeaderCRBodyLF() throws Exception
{
_queue.add("Header\r");
_queue.add("\r");
_queue.add("\nBody\n");
_queue.add("\r");
_queue.add("__CLOSE__");
assertEquals("Header",_in.readLine());
assertEquals("",_in.readLine());
byte[] body = new byte[6];
_in.read(body);
assertEquals("\nBody\n",new String(body,0,6,StandardCharsets.UTF_8));
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.CR), _in.getLineTerminations());
}
@Test
public void testHeaderCRLFBodyLF() throws Exception
{
_queue.add("Header\r\n");
_queue.add("\r\n");
_queue.add("\nBody\n");
_queue.add("\r\n");
_queue.add("__CLOSE__");
assertEquals("Header",_in.readLine());
assertEquals("",_in.readLine());
byte[] body = new byte[6];
_in.read(body);
assertEquals("\nBody\n",new String(body,0,6,StandardCharsets.UTF_8));
assertEquals("",_in.readLine());
assertEquals(null,_in.readLine());
assertEquals(EnumSet.of(Termination.CRLF), _in.getLineTerminations());
}
}

View File

@ -18,6 +18,20 @@
package org.eclipse.jetty.http2.client;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpStatus;
@ -38,19 +52,11 @@ import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.Test;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TrailersTest extends AbstractTest
@ -245,7 +251,8 @@ public class TrailersTest extends AbstractTest
Request jettyRequest = (Request)request;
Response jettyResponse = jettyRequest.getResponse();
HttpFields trailers = new HttpFields();
jettyResponse.setTrailerHttpFields(() -> trailers);
jettyResponse.setTrailerFields(() ->
trailers.stream().collect(Collectors.toMap(HttpField::getName, HttpField::getValue)));
jettyResponse.getOutputStream().write("hello_trailers".getBytes(StandardCharsets.UTF_8));
jettyResponse.flushBuffer();

View File

@ -46,16 +46,6 @@ public class PriorityFrame extends Frame
return streamId;
}
/**
* @deprecated use {@link #getParentStreamId()} instead.
* @return <code>int</code> of the Parent Stream
*/
@Deprecated
public int getDependentStreamId()
{
return getParentStreamId();
}
public int getParentStreamId()
{
return parentStreamId;

View File

@ -152,7 +152,7 @@ public class HpackContext
case C_STATUS:
{
entry=new StaticEntry(i,new StaticTableHttpField(header,name,value,Integer.valueOf(value)));
entry=new StaticEntry(i,new StaticTableHttpField(header,name,value,value));
break;
}

View File

@ -85,7 +85,7 @@ public class MetaDataBuilder
{
case C_STATUS:
if(checkPseudoHeader(header, _status))
_status = (Integer)staticField.getStaticValue();
_status = staticField.getIntValue();
_response = true;
break;
@ -111,7 +111,7 @@ public class MetaDataBuilder
{
case C_STATUS:
if(checkPseudoHeader(header, _status))
_status = Integer.valueOf(field.getIntValue());
_status = field.getIntValue();
_response = true;
break;

View File

@ -176,27 +176,6 @@ public abstract class AbstractHTTP2ServerConnectionFactory extends AbstractConne
this.maxSettingsKeys = maxSettingsKeys;
}
/**
* @return -1
* @deprecated feature removed, no replacement
*/
@Deprecated
public int getReservedThreads()
{
return -1;
}
/**
* @param threads ignored
* @deprecated feature removed, no replacement
* @throws UnsupportedOperationException when invoked
*/
@Deprecated
public void setReservedThreads(int threads)
{
throw new UnsupportedOperationException();
}
public HttpConfiguration getHttpConfiguration()
{
return httpConfiguration;

View File

@ -1,85 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.session.infinispan;
import org.infinispan.commons.marshall.jboss.AbstractJBossMarshaller;
import org.jboss.marshalling.ContextClassResolver;
/**
* WebAppMarshaller
*
* An implementation of the AbstractJBossMarshaller code that is just
* enough to provide a ContextClassResolver that will use the Thread Context Classloader
* in order to deserialize session attribute classes.
*
* This is necessary because the standard infinispan marshaller (GenericJBossMarshaller) uses the
* classloader of the loader that loaded itself. When using the infinispan module in Jetty, all of
* the infinispan classes will be on the container classpath. That means that the GenericJBossMarshaller
* returns the container classloader which is unable to load any webapp classes. This class ensures
* that it is always the webapp's classloader that will be used.
*
* In order to use this class, you should put a hotrod-client.properties file into the
* ${jetty.base}/resources directory that contains this line:
*
* infinispan.client.hotrod.marshaller=org.eclipse.jetty.session.infinispan.WebAppMarshaller
*
* You will also need to add the following lines to a context xml file for your webapp to
* permit the webapp's classloader to see the org.eclipse.jetty.session.infinispan classes for
* the deserialization to work correctly:
*
* &lt;Call name="prependServerClass"&gt;
* &lt;Arg&gt;-org.eclipse.jetty.session.infinispan.&lt;/Arg&gt;
* &lt;/Call&gt;
*
*/
@Deprecated
public class WebAppMarshaller extends AbstractJBossMarshaller
{
/**
* WebAppContextClassResolver
*
* Provides the Thread Context Classloader to use for deserializing.
*
*/
public static class WebAppContextClassResolver extends ContextClassResolver
{
public WebAppContextClassResolver ()
{
super();
}
@Override
protected ClassLoader getClassLoader()
{
return Thread.currentThread().getContextClassLoader();
}
}
public WebAppMarshaller ()
{
super();
baseCfg.setClassResolver(new WebAppContextClassResolver());
}
}

View File

@ -133,26 +133,6 @@ public abstract class SelectorManager extends ContainerLifeCycle implements Dump
_connectTimeout = milliseconds;
}
/**
* @return -1
* @deprecated
*/
@Deprecated
public int getReservedThreads()
{
return -1;
}
/**
* @param threads ignored
* @deprecated
*/
@Deprecated
public void setReservedThreads(int threads)
{
throw new UnsupportedOperationException();
}
/**
* Executes the given task in a different thread.
*

View File

@ -18,15 +18,6 @@
package org.eclipse.jetty.io;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@ -49,7 +40,6 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSocket;
@ -73,6 +63,15 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@SuppressWarnings("Duplicates")
public class SocketChannelEndPointTest
{
@ -263,7 +262,7 @@ public class SocketChannelEndPointTest
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertThrows(SocketTimeoutException.class, ()-> clientInputStream.read());
int elapsed = Long.valueOf(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start).intValue();
int elapsed = (int) (TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start);
assertThat("Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4));
// write remaining characters

View File

@ -97,7 +97,7 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory
RegistrationListener listener = (layer, appContext) -> {};
Subject serviceSubject=findServiceSubject(server);
String serverName=findServerName(server, serviceSubject);
String serverName=findServerName(server);
String contextPath=context.getContextPath();
if (contextPath==null || contextPath.length()==0)
@ -168,19 +168,4 @@ public class JaspiAuthenticatorFactory extends DefaultAuthenticatorFactory
return "server";
}
/* ------------------------------------------------------------ */
/** Find a servername.
* If {@link #setServerName(String)} has not been called, then
* use the name of the a principal in the service subject.
* If not found, return "server".
* @param server the server to use
* @param subject not used
* @return the server name from the subject of the server (or default value if not found in subject or principals)
*/
@Deprecated
protected String findServerName(Server server, Subject subject)
{
return findServerName(server);
}
}

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.security.jaspi.modules;
import java.io.IOException;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

View File

@ -1,91 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.security.jaspi.modules;
import java.io.IOException;
import java.security.Principal;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.security.Password;
@Deprecated
public class ClientCertAuthModule extends BaseAuthModule
{
public ClientCertAuthModule()
{
}
public ClientCertAuthModule(CallbackHandler callbackHandler)
{
super(callbackHandler);
}
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject,
Subject serviceSubject)
throws AuthException
{
HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
java.security.cert.X509Certificate[] certs = (java.security.cert.X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
try
{
// Need certificates.
if (certs == null || certs.length == 0 || certs[0] == null)
{
response.sendError(HttpServletResponse.SC_FORBIDDEN,
"A client certificate is required for accessing this web application but the server's listener is not configured for mutual authentication (or the client did not provide a certificate).");
return AuthStatus.SEND_FAILURE;
}
Principal principal = certs[0].getSubjectDN();
if (principal == null) principal = certs[0].getIssuerDN();
final String username = principal == null ? "clientcert" : principal.getName();
// TODO no idea if this is correct
final String password = new String(B64Code.encode(certs[0].getSignature()));
// TODO is cert_auth correct?
if (login(clientSubject, username, new Password(password), Constraint.__CERT_AUTH, messageInfo)) { return AuthStatus.SUCCESS; }
if (!isMandatory(messageInfo)) { return AuthStatus.SUCCESS; }
response.sendError(HttpServletResponse.SC_FORBIDDEN, "The provided client certificate does not correspond to a trusted user.");
return AuthStatus.SEND_FAILURE;
}
catch (IOException e)
{
throw new AuthException(e.getMessage());
}
catch (UnsupportedCallbackException e)
{
throw new AuthException(e.getMessage());
}
}
}

View File

@ -1,355 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.security.jaspi.modules;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.QuotedStringTokenizer;
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.security.Constraint;
import org.eclipse.jetty.util.security.Credential;
@Deprecated
public class DigestAuthModule extends BaseAuthModule
{
private static final Logger LOG = Log.getLogger(DigestAuthModule.class);
protected long maxNonceAge = 0;
protected long nonceSecret = this.hashCode() ^ System.currentTimeMillis();
protected boolean useStale = false;
private String realmName;
private static final String REALM_KEY = "org.eclipse.jetty.security.jaspi.modules.RealmName";
public DigestAuthModule()
{
}
public DigestAuthModule(CallbackHandler callbackHandler, String realmName)
{
super(callbackHandler);
this.realmName = realmName;
}
@Override
public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy,
CallbackHandler handler, Map options)
throws AuthException
{
super.initialize(requestPolicy, responsePolicy, handler, options);
realmName = (String) options.get(REALM_KEY);
}
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject,
Subject serviceSubject)
throws AuthException
{
HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
try
{
boolean stale = false;
// TODO extract from request
long timestamp = System.currentTimeMillis();
if (credentials != null)
{
if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;
String name = null;
while (tokenizer.hasMoreTokens())
{
String tok = tokenizer.nextToken();
char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
switch (c)
{
case '=':
name = last;
last = tok;
break;
case ',':
name = null;
case ' ':
break;
default:
last = tok;
if (name != null)
{
if ("username".equalsIgnoreCase(name))
digest.username = tok;
else if ("realm".equalsIgnoreCase(name))
digest.realm = tok;
else if ("nonce".equalsIgnoreCase(name))
digest.nonce = tok;
else if ("nc".equalsIgnoreCase(name))
digest.nc = tok;
else if ("cnonce".equalsIgnoreCase(name))
digest.cnonce = tok;
else if ("qop".equalsIgnoreCase(name))
digest.qop = tok;
else if ("uri".equalsIgnoreCase(name))
digest.uri = tok;
else if ("response".equalsIgnoreCase(name)) digest.response = tok;
break;
}
}
}
int n = checkNonce(digest.nonce, timestamp);
if (n > 0)
{
if (login(clientSubject, digest.username, digest, Constraint.__DIGEST_AUTH, messageInfo)) { return AuthStatus.SUCCESS; }
}
else if (n == 0) stale = true;
}
if (!isMandatory(messageInfo)) { return AuthStatus.SUCCESS; }
String domain = request.getContextPath();
if (domain == null) domain = "/";
response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + realmName
+ "\", domain=\""
+ domain
+ "\", nonce=\""
+ newNonce(timestamp)
+ "\", algorithm=MD5, qop=\"auth\""
+ (useStale ? (" stale=" + stale) : ""));
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return AuthStatus.SEND_CONTINUE;
}
catch (IOException e)
{
throw new AuthException(e.getMessage());
}
catch (UnsupportedCallbackException e)
{
throw new AuthException(e.getMessage());
}
}
public String newNonce(long ts)
{
// long ts=request.getTimeStamp();
long sk = nonceSecret;
byte[] nounce = new byte[24];
for (int i = 0; i < 8; i++)
{
nounce[i] = (byte) (ts & 0xff);
ts = ts >> 8;
nounce[8 + i] = (byte) (sk & 0xff);
sk = sk >> 8;
}
byte[] hash = null;
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(nounce, 0, 16);
hash = md.digest();
}
catch (Exception e)
{
LOG.warn(e);
}
for (int i = 0; i < hash.length; i++)
{
nounce[8 + i] = hash[i];
if (i == 23) break;
}
return new String(B64Code.encode(nounce));
}
/**
* @param nonce the nonce
* @param timestamp should be timestamp of request.
* @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
*/
public int checkNonce(String nonce, long timestamp)
{
try
{
byte[] n = B64Code.decode(nonce.toCharArray());
if (n.length != 24) return -1;
long ts = 0;
long sk = nonceSecret;
byte[] n2 = new byte[16];
System.arraycopy(n, 0, n2, 0, 8);
for (int i = 0; i < 8; i++)
{
n2[8 + i] = (byte) (sk & 0xff);
sk = sk >> 8;
ts = (ts << 8) + (0xff & (long) n[7 - i]);
}
long age = timestamp - ts;
if (LOG.isDebugEnabled()) LOG.debug("age=" + age);
byte[] hash = null;
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(n2, 0, 16);
hash = md.digest();
}
catch (Exception e)
{
LOG.warn(e);
}
for (int i = 0; i < 16; i++)
if (n[i + 8] != hash[i]) return -1;
if (maxNonceAge > 0 && (age < 0 || age > maxNonceAge)) return 0; // stale
return 1;
}
catch (Exception e)
{
LOG.ignore(e);
}
return -1;
}
private static class Digest extends Credential
{
private static final long serialVersionUID = -1866670896275159116L;
String method = null;
String username = null;
String realm = null;
String nonce = null;
String nc = null;
String cnonce = null;
String qop = null;
String uri = null;
String response = null;
/* ------------------------------------------------------------ */
Digest(String m)
{
method = m;
}
/* ------------------------------------------------------------ */
@Override
public boolean check(Object credentials)
{
String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] ha1;
if (credentials instanceof Credential.MD5)
{
// Credentials are already a MD5 digest - assume it's in
// form user:realm:password (we have no way to know since
// it's a digest, alright?)
ha1 = ((Credential.MD5) credentials).getDigest();
}
else
{
// calc A1 digest
md.update(username.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(realm.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(password.getBytes(StandardCharsets.ISO_8859_1));
ha1 = md.digest();
}
// calc A2 digest
md.reset();
md.update(method.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(uri.getBytes(StandardCharsets.ISO_8859_1));
byte[] ha2 = md.digest();
// calc digest
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
// nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
// <">
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
// ) > <">
md.update(TypeUtil.toString(ha1, 16).getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(nonce.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(nc.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(cnonce.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(qop.getBytes(StandardCharsets.ISO_8859_1));
md.update((byte) ':');
md.update(TypeUtil.toString(ha2, 16).getBytes(StandardCharsets.ISO_8859_1));
byte[] digest = md.digest();
// check digest
return stringEquals(TypeUtil.toString(digest, 16).toLowerCase(), response == null ? null : response.toLowerCase());
}
catch (Exception e)
{
LOG.warn(e);
}
return false;
}
@Override
public String toString()
{
return username + "," + response;
}
}
}

View File

@ -1,297 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
// 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.
// ========================================================================
//
package org.eclipse.jetty.security.jaspi.modules;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.security.authentication.DeferredAuthentication;
import org.eclipse.jetty.security.authentication.LoginCallbackImpl;
import org.eclipse.jetty.security.authentication.SessionAuthentication;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.security.Password;
@Deprecated
public class FormAuthModule extends BaseAuthModule
{
private static final Logger LOG = Log.getLogger(FormAuthModule.class);
/* ------------------------------------------------------------ */
public final static String __J_URI = "org.eclipse.jetty.util.URI";
public final static String __J_AUTHENTICATED = "org.eclipse.jetty.server.Auth";
public final static String __J_SECURITY_CHECK = "/j_security_check";
public final static String __J_USERNAME = "j_username";
public final static String __J_PASSWORD = "j_password";
// private String realmName;
public static final String LOGIN_PAGE_KEY = "org.eclipse.jetty.security.jaspi.modules.LoginPage";
public static final String ERROR_PAGE_KEY = "org.eclipse.jetty.security.jaspi.modules.ErrorPage";
public static final String SSO_SOURCE_KEY = "org.eclipse.jetty.security.jaspi.modules.SsoSource";
private String _formErrorPage;
private String _formErrorPath;
private String _formLoginPage;
private String _formLoginPath;
public FormAuthModule()
{
}
public FormAuthModule(CallbackHandler callbackHandler, String loginPage, String errorPage)
{
super(callbackHandler);
setLoginPage(loginPage);
setErrorPage(errorPage);
}
@Override
public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy,
CallbackHandler handler, Map options)
throws AuthException
{
super.initialize(requestPolicy, responsePolicy, handler, options);
setLoginPage((String) options.get(LOGIN_PAGE_KEY));
setErrorPage((String) options.get(ERROR_PAGE_KEY));
}
private void setLoginPage(String path)
{
if (!path.startsWith("/"))
{
LOG.warn("form-login-page must start with /");
path = "/" + path;
}
_formLoginPage = path;
_formLoginPath = path;
if (_formLoginPath.indexOf('?') > 0) _formLoginPath = _formLoginPath.substring(0, _formLoginPath.indexOf('?'));
}
/* ------------------------------------------------------------ */
private void setErrorPage(String path)
{
if (path == null || path.trim().length() == 0)
{
_formErrorPath = null;
_formErrorPage = null;
}
else
{
if (!path.startsWith("/"))
{
LOG.warn("form-error-page must start with /");
path = "/" + path;
}
_formErrorPage = path;
_formErrorPath = path;
if (_formErrorPath.indexOf('?') > 0) _formErrorPath = _formErrorPath.substring(0, _formErrorPath.indexOf('?'));
}
}
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException
{
HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
String uri = request.getRequestURI();
if (uri==null)
uri=URIUtil.SLASH;
boolean mandatory = isMandatory(messageInfo);
mandatory |= isJSecurityCheck(uri);
HttpSession session = request.getSession(mandatory);
// not mandatory or its the login or login error page don't authenticate
if (!mandatory || isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(),request.getPathInfo())))
return AuthStatus.SUCCESS; // TODO return null for do nothing?
try
{
// Handle a request for authentication.
if (isJSecurityCheck(uri))
{
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
boolean success = tryLogin(messageInfo, clientSubject, response, session, username, new Password(password));
if (success)
{
// Redirect to original request
String nuri=null;
synchronized(session)
{
nuri = (String) session.getAttribute(__J_URI);
}
if (nuri == null || nuri.length() == 0)
{
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(nuri));
return AuthStatus.SEND_CONTINUE;
}
// not authenticated
if (LOG.isDebugEnabled()) LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null)
{
if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else
{
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
}
// TODO is this correct response if isMandatory false??? Can
// that occur?
return AuthStatus.SEND_FAILURE;
}
// Check if the session is already authenticated.
SessionAuthentication sessionAuth = (SessionAuthentication)session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
if (sessionAuth != null)
{
//TODO: ideally we would like the form auth module to be able to invoke the
//loginservice.validate() method to check the previously authed user, but it is not visible
//to FormAuthModule
if (sessionAuth.getUserIdentity().getSubject() == null)
return AuthStatus.SEND_FAILURE;
Set<Object> credentials = sessionAuth.getUserIdentity().getSubject().getPrivateCredentials();
if (credentials == null || credentials.isEmpty())
return AuthStatus.SEND_FAILURE; //if no private credentials, assume it cannot be authenticated
clientSubject.getPrivateCredentials().addAll(credentials);
clientSubject.getPrivateCredentials().add(sessionAuth.getUserIdentity());
return AuthStatus.SUCCESS;
}
// if we can't send challenge
if (DeferredAuthentication.isDeferred(response))
return AuthStatus.SUCCESS;
// redirect to login page
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
synchronized (session)
{
session.setAttribute(__J_URI, buf.toString());
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
return AuthStatus.SEND_CONTINUE;
}
catch (IOException e)
{
throw new AuthException(e.getMessage());
}
catch (UnsupportedCallbackException e)
{
throw new AuthException(e.getMessage());
}
}
/* ------------------------------------------------------------ */
public boolean isJSecurityCheck(String uri)
{
int jsc = uri.indexOf(__J_SECURITY_CHECK);
if (jsc<0)
return false;
int e=jsc+__J_SECURITY_CHECK.length();
if (e==uri.length())
return true;
char c = uri.charAt(e);
return c==';'||c=='#'||c=='/'||c=='?';
}
private boolean tryLogin(MessageInfo messageInfo, Subject clientSubject,
HttpServletResponse response, HttpSession session,
String username, Password password)
throws AuthException, IOException, UnsupportedCallbackException
{
if (login(clientSubject, username, password, Constraint.__FORM_AUTH, messageInfo))
{
char[] pwdChars = password.toString().toCharArray();
Set<LoginCallbackImpl> loginCallbacks = clientSubject.getPrivateCredentials(LoginCallbackImpl.class);
if (!loginCallbacks.isEmpty())
{
LoginCallbackImpl loginCallback = loginCallbacks.iterator().next();
Set<UserIdentity> userIdentities = clientSubject.getPrivateCredentials(UserIdentity.class);
if (!userIdentities.isEmpty())
{
UserIdentity userIdentity = userIdentities.iterator().next();
SessionAuthentication sessionAuth = new SessionAuthentication(Constraint.__FORM_AUTH, userIdentity, password);
session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, sessionAuth);
}
}
return true;
}
return false;
}
public boolean isLoginOrErrorPage(String pathInContext)
{
return pathInContext != null && (pathInContext.equals(_formErrorPath) || pathInContext.equals(_formLoginPath));
}
}

View File

@ -121,17 +121,6 @@ public class ObjectMBean implements DynamicMBean
return this._mbeanContainer;
}
/**
* @param o the object to wrap as MBean
* @return a new instance of an MBean for the object or null if the MBean cannot be created
* @deprecated Use {@link MBeanContainer#mbeanFor(Object)} instead
*/
@Deprecated
public static Object mbeanFor(Object o)
{
return MBeanContainer.mbeanFor(null, o);
}
@Override
public MBeanInfo getMBeanInfo()
{

View File

@ -46,8 +46,8 @@ import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
/**
* JettyWebAppContext
@ -350,17 +350,17 @@ public class JettyWebAppContext extends WebAppContext
// classpath
// that will be scanned - note that by default NO jars are scanned
String tmp = _containerIncludeJarPattern;
if (tmp == null || "".equals(tmp)) tmp = (String) getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
if (tmp == null || "".equals(tmp)) tmp = (String) getAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN);
tmp = addPattern(tmp, DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN);
setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, tmp);
setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, tmp);
// Allow user to set up pattern of jar names from WEB-INF that will be
// scanned.
// Note that by default ALL jars considered to be in WEB-INF will be
// scanned - setting
// a pattern restricts scanning
if (_webInfIncludeJarPattern != null) setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, _webInfIncludeJarPattern);
if (_webInfIncludeJarPattern != null) setAttribute(MetaInfConfiguration.WEBINF_JAR_PATTERN, _webInfIncludeJarPattern);
// Set up the classes dirs that comprises the equivalent of
// WEB-INF/classes

View File

@ -99,15 +99,6 @@ public class MavenServerConnector extends ContainerLifeCycle implements Connecto
this.idleTimeout = idleTimeout;
}
/**
* @param lingerTime the socket close linger time
* @deprecated don't use as socket close linger time has undefined behavior for non-blocking sockets
*/
@Deprecated
public void setSoLingerTime(int lingerTime)
{
}
@Override
protected void doStart() throws Exception
{

View File

@ -43,7 +43,7 @@ public abstract class NoSqlSessionDataStore extends AbstractSessionDataStore
public NoSqlSessionData(String id, String cpath, String vhost, long created, long accessed, long lastAccessed, long maxInactiveMs)
{
super(id, cpath, vhost, created, accessed, lastAccessed, maxInactiveMs);
setVersion (new Long(0));
setVersion (0L);
}
public void setVersion (Object v)

View File

@ -27,16 +27,6 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.jetty.nosql.NoSqlSessionDataStore;
import org.eclipse.jetty.server.session.SessionContext;
import org.eclipse.jetty.server.session.SessionData;
import org.eclipse.jetty.server.session.UnreadableSessionDataException;
import org.eclipse.jetty.util.ClassLoadingObjectInputStream;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
@ -46,6 +36,15 @@ import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import org.eclipse.jetty.nosql.NoSqlSessionDataStore;
import org.eclipse.jetty.server.session.SessionContext;
import org.eclipse.jetty.server.session.SessionData;
import org.eclipse.jetty.server.session.UnreadableSessionDataException;
import org.eclipse.jetty.util.ClassLoadingObjectInputStream;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* MongoSessionDataStore
@ -478,7 +477,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore
if (lastSaveTime <= 0)
{
upsert = true;
version = new Long(1);
version = 1L;
sets.put(__CREATED,data.getCreated());
sets.put(__VALID,true);
sets.put(getContextSubfield(__VERSION),version);
@ -492,7 +491,7 @@ public class MongoSessionDataStore extends NoSqlSessionDataStore
{
sets.put(getContextSubfield(__LASTSAVED), data.getLastSaved());
sets.put(getContextSubfield(__LASTNODE), data.getLastNode());
version = new Long(((Number)version).longValue() + 1);
version = ((Number)version).longValue() + 1L;
((NoSqlSessionData)data).setVersion(version);
update.put("$inc",_version_1);
//if max idle time and/or expiry is smaller for this context, then choose that for the whole session doc

View File

@ -21,15 +21,12 @@ package org.eclipse.jetty.nosql.mongodb;
import java.net.UnknownHostException;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.eclipse.jetty.server.session.AbstractSessionDataStoreFactory;
import org.eclipse.jetty.server.session.SessionDataStore;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.server.session.SessionDataStore;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoURI;
/**
* MongoSessionDataStoreFactory
@ -135,16 +132,16 @@ public class MongoSessionDataStoreFactory extends AbstractSessionDataStoreFactor
MongoSessionDataStore store = new MongoSessionDataStore();
store.setGracePeriodSec(getGracePeriodSec());
store.setSavePeriodSec(getSavePeriodSec());
Mongo mongo;
MongoClient mongo;
if (!StringUtil.isBlank(getConnectionString()))
mongo = new Mongo(new MongoURI(getConnectionString()));
mongo = new MongoClient(new MongoClientURI(getConnectionString()));
else if (!StringUtil.isBlank(getHost()) && getPort() != -1)
mongo = new Mongo(getHost(), getPort());
mongo = new MongoClient(getHost(), getPort());
else if (!StringUtil.isBlank(getHost()))
mongo = new Mongo(getHost());
mongo = new MongoClient(getHost());
else
mongo = new Mongo();
mongo = new MongoClient();
store.setDBCollection(mongo.getDB(getDbName()).getCollection(getCollectionName()));
return store;
}

View File

@ -26,12 +26,11 @@ import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import javax.servlet.jsp.JspFactory;
import org.eclipse.jetty.deploy.DeploymentManager;
import org.eclipse.jetty.osgi.boot.JettyBootstrapActivator;
import org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration;
import org.eclipse.jetty.osgi.boot.OSGiMetaInfConfiguration;
import org.eclipse.jetty.osgi.boot.utils.BundleFileLocatorHelper;
import org.eclipse.jetty.osgi.boot.utils.TldBundleDiscoverer;
import org.eclipse.jetty.util.log.Log;
@ -102,7 +101,7 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer
Bundle[] bundles = FrameworkUtil.getBundle(ContainerTldBundleDiscoverer.class).getBundleContext().getBundles();
HashSet<URL> urls = new HashSet<URL>();
String tmp = System.getProperty(OSGiWebInfConfiguration.SYS_PROP_TLD_BUNDLES); //comma separated exact names
String tmp = System.getProperty(OSGiMetaInfConfiguration.SYS_PROP_TLD_BUNDLES); //comma separated exact names
List<String> sysNames = new ArrayList<String>();
if (tmp != null)
{
@ -110,7 +109,7 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer
while (tokenizer.hasMoreTokens())
sysNames.add(tokenizer.nextToken());
}
tmp = (String) deploymentManager.getContextAttribute(OSGiWebInfConfiguration.CONTAINER_BUNDLE_PATTERN); //bundle name patterns
tmp = (String) deploymentManager.getContextAttribute(OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN); //bundle name patterns
Pattern pattern = (tmp==null? null : Pattern.compile(tmp));
@ -122,13 +121,13 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer
if (pattern == null)
{
pattern = Pattern.compile(jstlBundle.getSymbolicName());
deploymentManager.setContextAttribute(OSGiWebInfConfiguration.CONTAINER_BUNDLE_PATTERN, jstlBundle.getSymbolicName());
deploymentManager.setContextAttribute(OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN, jstlBundle.getSymbolicName());
}
else if (!(pattern.matcher(jstlBundle.getSymbolicName()).matches()))
{
String s = tmp+"|"+jstlBundle.getSymbolicName();
pattern = Pattern.compile(s);
deploymentManager.setContextAttribute(OSGiWebInfConfiguration.CONTAINER_BUNDLE_PATTERN, s);
deploymentManager.setContextAttribute(OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN, s);
}
}

View File

@ -54,21 +54,19 @@
-->
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="secureScheme"><Property name="jetty.httpConfig.secureScheme" default="https" /></Set>
<Set name="securePort"><Property name="jetty.httpConfig.securePort" deprecated="jetty.secure.port" default="8443" /></Set>
<Set name="outputBufferSize"><Property name="jetty.httpConfig.outputBufferSize" deprecated="jetty.output.buffer.size" default="32768" /></Set>
<Set name="outputAggregationSize"><Property name="jetty.httpConfig.outputAggregationSize" deprecated="jetty.output.aggregation.size" default="8192" /></Set>
<Set name="requestHeaderSize"><Property name="jetty.httpConfig.requestHeaderSize" deprecated="jetty.request.header.size" default="8192" /></Set>
<Set name="responseHeaderSize"><Property name="jetty.httpConfig.responseHeaderSize" deprecated="jetty.response.header.size" default="8192" /></Set>
<Set name="sendServerVersion"><Property name="jetty.httpConfig.sendServerVersion" deprecated="jetty.send.server.version" default="true" /></Set>
<Set name="sendDateHeader"><Property name="jetty.httpConfig.sendDateHeader" deprecated="jetty.send.date.header" default="false" /></Set>
<Set name="securePort"><Property name="jetty.httpConfig.securePort" default="8443" /></Set>
<Set name="outputBufferSize"><Property name="jetty.httpConfig.outputBufferSize" default="32768" /></Set>
<Set name="outputAggregationSize"><Property name="jetty.httpConfig.outputAggregationSize" default="8192" /></Set>
<Set name="requestHeaderSize"><Property name="jetty.httpConfig.requestHeaderSize" default="8192" /></Set>
<Set name="responseHeaderSize"><Property name="jetty.httpConfig.responseHeaderSize" default="8192" /></Set>
<Set name="sendServerVersion"><Property name="jetty.httpConfig.sendServerVersion" default="true" /></Set>
<Set name="sendDateHeader"><Property name="jetty.httpConfig.sendDateHeader" default="false" /></Set>
<Set name="headerCacheSize"><Property name="jetty.httpConfig.headerCacheSize" default="4096" /></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" deprecated="jetty.delayDispatchUntilContent" default="true"/></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" default="true"/></Set>
<Set name="maxErrorDispatches"><Property name="jetty.httpConfig.maxErrorDispatches" default="10"/></Set>
<Set name="blockingTimeout"><Property deprecated="jetty.httpConfig.blockingTimeout" name="jetty.httpConfig.blockingTimeout.DEPRECATED" default="-1"/></Set>
<Set name="persistentConnectionsEnabled"><Property name="jetty.httpConfig.persistentConnectionsEnabled" default="true"/></Set>
<Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" deprecated="jetty.httpConfig.cookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="responseCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.responseCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="multiPartFormDataCompliance"><Call class="org.eclipse.jetty.server.MultiPartFormDataCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.multiPartFormDataCompliance" default="RFC7578"/></Arg></Call></Set>
</New>
<!-- =========================================================== -->
@ -76,31 +74,34 @@
<!-- =========================================================== -->
<Set name="stopAtShutdown"><Property name="jetty.server.stopAtShutdown" default="true"/></Set>
<Set name="stopTimeout"><Property name="jetty.server.stopTimeout" default="5000"/></Set>
<Set name="dumpAfterStart"><Property name="jetty.server.dumpAfterStart" deprecated="jetty.dump.start" default="false"/></Set>
<Set name="dumpBeforeStop"><Property name="jetty.server.dumpBeforeStop" deprecated="jetty.dump.stop" default="false"/></Set>
<Set name="dumpAfterStart"><Property name="jetty.server.dumpAfterStart" default="false"/></Set>
<Set name="dumpBeforeStop"><Property name="jetty.server.dumpBeforeStop" default="false"/></Set>
<Call class="org.eclipse.jetty.webapp.Configurations" name="setKnown">
<Arg>
<Array type="String">
<Item>org.eclipse.jetty.webapp.FragmentConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JettyWebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebAppConfiguration</Item>
<Item>org.eclipse.jetty.webapp.ServletsConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JspConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JaasConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JndiConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JmxConfiguration</Item>
<Item>org.eclipse.jetty.websocket.server.JettyWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.websocket.javax.server.JavaxWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.osgi.annotations.AnnotationConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiMetaInfConfiguration</Item>
</Array>
</Arg>
<Call class="org.eclipse.jetty.webapp.Configurations" name="setServerDefault">
<Arg><Ref refid="Server"/></Arg>
<Call name="add">
<Arg>
<Array type="String">
<Item>org.eclipse.jetty.webapp.FragmentConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JettyWebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebAppConfiguration</Item>
<Item>org.eclipse.jetty.webapp.ServletsConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JspConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JaasConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JndiConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JmxConfiguration</Item>
<Item>org.eclipse.jetty.osgi.annotations.AnnotationConfiguration</Item>
<Item>org.eclipse.jetty.websocket.server.JettyWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.websocket.javax.server.JavaxWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiMetaInfConfiguration</Item>
</Array>
</Arg>
</Call>
</Call>

View File

@ -22,11 +22,10 @@ import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import org.eclipse.jetty.annotations.AnnotationParser.Handler;
import org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration;
import org.eclipse.jetty.osgi.boot.OSGiMetaInfConfiguration;
import org.eclipse.jetty.osgi.boot.OSGiWebappConstants;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
@ -117,7 +116,7 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot
Bundle webbundle = (Bundle) context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE);
@SuppressWarnings("unchecked")
Set<Bundle> fragAndRequiredBundles = (Set<Bundle>)context.getAttribute(OSGiWebInfConfiguration.FRAGMENT_AND_REQUIRED_BUNDLES);
Set<Bundle> fragAndRequiredBundles = (Set<Bundle>)context.getAttribute(OSGiMetaInfConfiguration.FRAGMENT_AND_REQUIRED_BUNDLES);
if (fragAndRequiredBundles != null)
{
//index and scan fragments

View File

@ -109,8 +109,6 @@ public abstract class AbstractContextProvider extends AbstractLifeCycle implemen
//Override for bundle root may have been set
String bundleOverrideLocation = (String)_properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE);
if (bundleOverrideLocation == null)
bundleOverrideLocation = (String)_properties.get(OSGiWebappConstants.SERVICE_PROP_BUNDLE_INSTALL_LOCATION_OVERRIDE);
//Location on filesystem of bundle or the bundle override location
File bundleLocation = BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle);
@ -188,8 +186,6 @@ public abstract class AbstractContextProvider extends AbstractLifeCycle implemen
//If a bundle/service property specifies context path, let it override the context xml
String contextPath = (String)_properties.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
if (contextPath == null)
contextPath = (String)_properties.get(OSGiWebappConstants.SERVICE_PROP_CONTEXT_PATH);
if (contextPath != null)
_contextHandler.setContextPath(contextPath);

View File

@ -168,9 +168,7 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu
}
String contextFiles = (String)bundle.getHeaders().get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH);
if (contextFiles == null)
contextFiles = (String)bundle.getHeaders().get(OSGiWebappConstants.SERVICE_PROP_CONTEXT_FILE_PATH);
if (contextFiles == null)
return false;

View File

@ -181,7 +181,7 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund
Dictionary<String,String> headers = bundle.getHeaders();
//does the bundle have a OSGiWebappConstants.JETTY_WAR_FOLDER_PATH
String resourcePath = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_FOLDER_PATH, OSGiWebappConstants.JETTY_WAR_RESOURCE_PATH, headers);
String resourcePath = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_RESOURCE_PATH, headers);
if (resourcePath != null)
{
String base = resourcePath;

View File

@ -243,22 +243,22 @@ public class OSGiMetaInfConfiguration extends MetaInfConfiguration
// looked up.
for (Bundle frag : fragments)
{
String path = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_FRAGMENT_FOLDER_PATH,OSGiWebappConstants.JETTY_WAR_FRAGMENT_RESOURCE_PATH,frag.getHeaders());
String path = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_FRAGMENT_RESOURCE_PATH, frag.getHeaders());
convertFragmentPathToResource(path, frag, appendedResourcesPath);
path = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_PATCH_FRAGMENT_FOLDER_PATH, OSGiWebappConstants.JETTY_WAR_PREPEND_FRAGMENT_RESOURCE_PATH, frag.getHeaders());
path = Util.getManifestHeaderValue(OSGiWebappConstants.JETTY_WAR_PREPEND_FRAGMENT_RESOURCE_PATH, frag.getHeaders());
convertFragmentPathToResource(path, frag, prependedResourcesPath);
}
if (!appendedResourcesPath.isEmpty())
{
LinkedHashSet<Resource> resources = new LinkedHashSet<Resource>();
//Add in any existing setting of extra resource dirs
Set<Resource> resourceDirs = (Set<Resource>)context.getAttribute(WebInfConfiguration.RESOURCE_DIRS);
Set<Resource> resourceDirs = (Set<Resource>)context.getAttribute(MetaInfConfiguration.RESOURCE_DIRS);
if (resourceDirs != null && !resourceDirs.isEmpty())
resources.addAll(resourceDirs);
//Then append the values from JETTY_WAR_FRAGMENT_FOLDER_PATH
resources.addAll(appendedResourcesPath.values());
context.setAttribute(WebInfConfiguration.RESOURCE_DIRS, resources);
context.setAttribute(MetaInfConfiguration.RESOURCE_DIRS, resources);
}
}
}

View File

@ -30,15 +30,6 @@ import org.eclipse.jetty.webapp.WebInfConfiguration;
*/
public class OSGiWebInfConfiguration extends WebInfConfiguration
{
@Deprecated
public static final String SYS_PROP_TLD_BUNDLES = OSGiMetaInfConfiguration.SYS_PROP_TLD_BUNDLES;
@Deprecated
public static final String CONTAINER_BUNDLE_PATTERN = OSGiMetaInfConfiguration.CONTAINER_BUNDLE_PATTERN;
@Deprecated
public static final String FRAGMENT_AND_REQUIRED_BUNDLES = OSGiMetaInfConfiguration.FRAGMENT_AND_REQUIRED_BUNDLES;
@Deprecated
public static final String FRAGMENT_AND_REQUIRED_RESOURCES = OSGiMetaInfConfiguration.FRAGMENT_AND_REQUIRED_RESOURCES;
@Override
public Class<? extends Configuration> replaces()
{

View File

@ -67,82 +67,47 @@ public class OSGiWebappConstants
public static final String JETTY_CONTEXT_FILE_PATH = "Jetty-ContextFilePath";
/** path within the bundle to the folder that contains the basic resources. */
@Deprecated
public static final String JETTY_WAR_FOLDER_PATH = "Jetty-WarFolderPath";
public static final String JETTY_WAR_RESOURCE_PATH = "Jetty-WarResourcePath";
/** path within a fragment hosted by a web-bundle to a folder that contains basic resources.
* the path is appended to the lookup path where jetty locates static resources */
@Deprecated
public static final String JETTY_WAR_FRAGMENT_FOLDER_PATH = "Jetty-WarFragmentFolderPath";
public static final String JETTY_WAR_FRAGMENT_RESOURCE_PATH = "Jetty-WarFragmentResourcePath";
/** path within a fragment hosted by a web-bundle to a folder that contains basic resources.
* The path is prefixed to the lookup path where jetty locates static resources:
* this will override static resources with the same name in the web-bundle. */
@Deprecated
public static final String JETTY_WAR_PATCH_FRAGMENT_FOLDER_PATH = "Jetty-WarPatchFragmentFolderPath";
public static final String JETTY_WAR_PREPEND_FRAGMENT_RESOURCE_PATH = "Jetty-WarPrependFragmentResourcePath";
/** installation path of webapp bundle
*
/**
* installation path of webapp bundle
*/
public static final String JETTY_BUNDLE_ROOT = "bundle.root";
/**
* web app context path
* @deprecated see RFC66_WEB_CONTEXTPATH
*/
public static final String SERVICE_PROP_CONTEXT_PATH = "contextPath";
/**
* Path to the web application base folder
* @deprecated see JETTY_WAR_FOLDER_PATH
*/
public static final String SERVICE_PROP_WAR = "war";
/**
/**
* Extra classpath
* @deprecated see JETTY_EXTRA_CLASSPATH
*/
public static final String SERVICE_PROP_EXTRA_CLASSPATH = "extraClasspath";
public static final String JETTY_EXTRA_CLASSPATH = "Jetty-extraClasspath";
/**
* jetty context file path
* @deprecated see JETTY_CONTEXT_FILE_PATH
*/
public static final String SERVICE_PROP_CONTEXT_FILE_PATH = "contextFilePath";
/**
/**
* web.xml file path
* @deprecated see JETTY_WEB_XML_PATH
*/
public static final String SERVICE_PROP_WEB_XML_PATH = "webXmlFilePath";
public static final String JETTY_WEB_XML_PATH = "Jetty-WebXmlFilePath";
/**
* defaultweb.xml file path
* @deprecated see JETTY_DEFAULT_WEB_XML_PATH
*/
public static final String SERVICE_PROP_DEFAULT_WEB_XML_PATH = "defaultWebXmlFilePath";
public static final String JETTY_DEFAULT_WEB_XML_PATH = "Jetty-defaultWebXmlFilePath";
/**
* path to the base folder that overrides the computed bundle installation
* location if not null useful to install webapps or jetty context files
* that are in fact not embedded in a bundle
* @deprecated see JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE
*/
public static final String SERVICE_PROP_BUNDLE_INSTALL_LOCATION_OVERRIDE = "thisBundleInstall";
public static final String JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE = "Jetty-bundleInstall";
/**
* Comma separated list of bundles that contain tld file used by the webapp.
*/

View File

@ -164,9 +164,7 @@ public class ServiceContextProvider extends AbstractContextProvider implements S
{
//See if there is a context file to apply to this pre-made context
String contextFile = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH);
if (contextFile == null)
contextFile = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_CONTEXT_FILE_PATH);
String[] keys = serviceRef.getPropertyKeys();
Dictionary<String,Object> properties = new Hashtable<>();
if (keys != null)

View File

@ -170,41 +170,27 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser
Dictionary<String,String> properties = new Hashtable<>();
String contextPath = (String)serviceRef.getProperty(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
if (contextPath == null)
contextPath = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_CONTEXT_PATH);
if (contextPath == null)
return false; //No context path
String base = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_WAR_FOLDER_PATH);
if (base == null)
base = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_WAR_RESOURCE_PATH);
if (base == null)
base = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_WAR);
String base = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_WAR_RESOURCE_PATH);
if (base == null)
return false; //No webapp base
String webdefaultXml = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH);
if (webdefaultXml == null)
webdefaultXml = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_DEFAULT_WEB_XML_PATH);
if (webdefaultXml != null)
properties.put(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH, webdefaultXml);
String webXml = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_WEB_XML_PATH);
if (webXml == null)
webXml = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_WEB_XML_PATH);
if (webXml != null)
properties.put(OSGiWebappConstants.JETTY_WEB_XML_PATH, webXml);
String extraClassPath = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_EXTRA_CLASSPATH);
if (extraClassPath == null)
extraClassPath = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_EXTRA_CLASSPATH);
if (extraClassPath != null)
properties.put(OSGiWebappConstants.JETTY_EXTRA_CLASSPATH, extraClassPath);
String bundleInstallOverride = (String)serviceRef.getProperty(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE);
if (bundleInstallOverride == null)
bundleInstallOverride = (String)serviceRef.getProperty(OSGiWebappConstants.SERVICE_PROP_BUNDLE_INSTALL_LOCATION_OVERRIDE);
if (bundleInstallOverride != null)
properties.put(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE, bundleInstallOverride);

View File

@ -82,8 +82,19 @@ public class Util
return (String)manifest.get(name);
return (String)manifest.get(altName);
}
/**
* Get the value of a manifest header.
*
* @param name the name of the header
* @param manifest the dictionary
* @return the value from the manifest
*/
public static String getManifestHeaderValue (String name, Dictionary<String,String> manifest)
{
return getManifestHeaderValue(name, null, manifest);
}
/* ------------------------------------------------------------ */
/**

View File

@ -20,7 +20,6 @@ package com.acme.osgi;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
@ -62,7 +61,7 @@ public class Activator implements BundleActivator
});
Dictionary props = new Hashtable();
props.put("contextPath","/acme");
props.put("Web-ContextPath","/acme");
props.put("Jetty-ContextFilePath", "acme.xml");
_sr = context.registerService(ContextHandler.class.getName(),ch,props);
}

View File

@ -38,8 +38,8 @@
<Bundle-SymbolicName>${bundle-symbolic-name}</Bundle-SymbolicName>
<Bundle-Name>Jetty OSGi Test WebApp Fragment</Bundle-Name>
<Bundle-RequiredExecutionEnvironment>J2SE-1.5</Bundle-RequiredExecutionEnvironment>
<Fragment-Host>org.eclipse.jetty.tests.test-spec-webapp</Fragment-Host>
<Jetty-WarFragmentFolderPath>/</Jetty-WarFragmentFolderPath>
<Fragment-Host>org.eclipse.jetty.tests.test-spec-webapp</Fragment-Host>
<Jetty-WarFragmentResourcePath>/</Jetty-WarFragmentResourcePath>
</instructions>
</configuration>
</plugin>

View File

@ -26,7 +26,6 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.webapp.Configurations;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
@ -68,7 +67,7 @@ public class Activator implements BundleActivator
});
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
//server.setDumpAfterStart(true);
// server.setDumpAfterStart(true);
String[] list = new String[]{
"org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration",

View File

@ -22,13 +22,11 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
import org.osgi.framework.BundleActivator;
@ -78,8 +76,8 @@ public class Activator implements BundleActivator
WebAppContext webapp = new WebAppContext();
webapp.addServlet(new ServletHolder(new TestServlet()), "/mime");
Dictionary props = new Hashtable();
props.put("war","webappA");
props.put("contextPath","/acme");
props.put("Jetty-WarResourcePath","webappA");
props.put("Web-ContextPath","/acme");
props.put("managedServerName", "defaultJettyServer");
_srA = context.registerService(WebAppContext.class.getName(),webapp,props);
@ -87,8 +85,8 @@ public class Activator implements BundleActivator
//deployed by another bundle
WebAppContext webappB = new WebAppContext();
Dictionary propsB = new Hashtable();
propsB.put("war", "webappB");
propsB.put("contextPath", "/acme");
propsB.put("Jetty-WarResourcePath", "webappB");
propsB.put("Web-ContextPath", "/acme");
propsB.put("managedServerName", "fooServer");
_srB = context.registerService(WebAppContext.class.getName(), webappB, propsB);
}

View File

@ -15,8 +15,8 @@
<Call name="addConnectionFactory">
<Arg>
<New id="alpn" class="org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory">
<Arg name="protocols" type="String"><Property name="jetty.alpn.protocols" deprecated="alpn.protocols" default="h2,http/1.1" /></Arg>
<Set name="defaultProtocol"><Property name="jetty.alpn.defaultProtocol" deprecated="alpn.defaultProtocol" /></Set>
<Arg name="protocols" type="String"><Property name="jetty.alpn.protocols" default="h2,http/1.1" /></Arg>
<Set name="defaultProtocol"><Property name="jetty.alpn.defaultProtocol" /></Set>
</New>
</Arg>
</Call>

View File

@ -9,7 +9,7 @@
<Arg>
<New class="org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory">
<Arg name="config"><Ref refid="sslHttpConfig"/></Arg>
<Set name="maxConcurrentStreams"><Property name="jetty.http2.maxConcurrentStreams" deprecated="http2.maxConcurrentStreams" default="128"/></Set>
<Set name="maxConcurrentStreams"><Property name="jetty.http2.maxConcurrentStreams" default="128"/></Set>
<Set name="initialStreamRecvWindow"><Property name="jetty.http2.initialStreamRecvWindow" default="524288"/></Set>
<Set name="initialSessionRecvWindow"><Property name="jetty.http2.initialSessionRecvWindow" default="1048576"/></Set>
</New>

View File

@ -9,7 +9,7 @@
<Arg>
<New class="org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory">
<Arg name="config"><Ref refid="sslHttpConfig"/></Arg>
<Set name="maxConcurrentStreams"><Property name="jetty.http2.maxConcurrentStreams" deprecated="http2.maxConcurrentStreams" default="128"/></Set>
<Set name="maxConcurrentStreams"><Property name="jetty.http2.maxConcurrentStreams" default="128"/></Set>
<Set name="initialStreamRecvWindow"><Property name="jetty.http2.initialStreamRecvWindow" default="524288"/></Set>
<Set name="initialSessionRecvWindow"><Property name="jetty.http2.initialSessionRecvWindow" default="1048576"/></Set>
</New>

View File

@ -35,20 +35,8 @@
<Set name="KeyStorePassword"><Property name="jetty.sslContext.keyStorePassword" default="OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"/></Set>
<Set name="TrustStorePath"><Property name="jetty.base" default="." />/<Property name="jetty.sslContext.trustStorePath" default="etc/keystore"/></Set>
<Set name="TrustStorePassword"><Property name="jetty.sslContext.trustStorePassword" default="OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"/></Set>
<Set name="EndpointIdentificationAlgorithm"></Set>
<Set name="NeedClientAuth"><Property name="jetty.sslContext.needClientAuth" default="false"/></Set>
<Set name="WantClientAuth"><Property name="jetty.sslContext.wantClientAuth" default="false"/></Set>
<Set name="ExcludeCipherSuites">
<Array type="String">
<Item>SSL_RSA_WITH_DES_CBC_SHA</Item>
<Item>SSL_DHE_RSA_WITH_DES_CBC_SHA</Item>
<Item>SSL_DHE_DSS_WITH_DES_CBC_SHA</Item>
<Item>SSL_RSA_EXPORT_WITH_RC4_40_MD5</Item>
<Item>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
<Item>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
<Item>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</Item>
</Array>
</Set>
</New>
<!-- =========================================================== -->

View File

@ -43,22 +43,19 @@
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="secureScheme"><Property name="jetty.httpConfig.secureScheme" default="https" /></Set>
<Set name="securePort"><Property name="jetty.httpConfig.securePort" deprecated="jetty.secure.port" default="8443" /></Set>
<Set name="outputBufferSize"><Property name="jetty.httpConfig.outputBufferSize" deprecated="jetty.output.buffer.size" default="32768" /></Set>
<Set name="outputAggregationSize"><Property name="jetty.httpConfig.outputAggregationSize" deprecated="jetty.output.aggregation.size" default="8192" /></Set>
<Set name="requestHeaderSize"><Property name="jetty.httpConfig.requestHeaderSize" deprecated="jetty.request.header.size" default="8192" /></Set>
<Set name="responseHeaderSize"><Property name="jetty.httpConfig.responseHeaderSize" deprecated="jetty.response.header.size" default="8192" /></Set>
<Set name="sendServerVersion"><Property name="jetty.httpConfig.sendServerVersion" deprecated="jetty.send.server.version" default="true" /></Set>
<Set name="sendDateHeader"><Property name="jetty.httpConfig.sendDateHeader" deprecated="jetty.send.date.header" default="false" /></Set>
<Set name="securePort"><Property name="jetty.httpConfig.securePort" default="8443" /></Set>
<Set name="outputBufferSize"><Property name="jetty.httpConfig.outputBufferSize" default="32768" /></Set>
<Set name="outputAggregationSize"><Property name="jetty.httpConfig.outputAggregationSize" default="8192" /></Set>
<Set name="requestHeaderSize"><Property name="jetty.httpConfig.requestHeaderSize" default="8192" /></Set>
<Set name="responseHeaderSize"><Property name="jetty.httpConfig.responseHeaderSize" default="8192" /></Set>
<Set name="sendServerVersion"><Property name="jetty.httpConfig.sendServerVersion" default="true" /></Set>
<Set name="sendDateHeader"><Property name="jetty.httpConfig.sendDateHeader" default="false" /></Set>
<Set name="headerCacheSize"><Property name="jetty.httpConfig.headerCacheSize" default="4096" /></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" deprecated="jetty.delayDispatchUntilContent" default="true"/></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" default="true"/></Set>
<Set name="maxErrorDispatches"><Property name="jetty.httpConfig.maxErrorDispatches" default="10"/></Set>
<Set name="blockingTimeout"><Property deprecated="jetty.httpConfig.blockingTimeout" name="jetty.httpConfig.blockingTimeout.DEPRECATED" default="-1"/></Set>
<Set name="persistentConnectionsEnabled"><Property name="jetty.httpConfig.persistentConnectionsEnabled" default="true"/></Set>
<Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" deprecated="jetty.httpConfig.cookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="responseCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.responseCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="multiPartFormDataCompliance"><Call class="org.eclipse.jetty.http.MultiPartFormDataCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.multiPartFormDataCompliance" default="RFC7578"/></Arg></Call></Set>
</New>
@ -67,31 +64,33 @@
<!-- =========================================================== -->
<Set name="stopAtShutdown"><Property name="jetty.server.stopAtShutdown" default="true"/></Set>
<Set name="stopTimeout"><Property name="jetty.server.stopTimeout" default="5000"/></Set>
<Set name="dumpAfterStart"><Property name="jetty.server.dumpAfterStart" deprecated="jetty.dump.start" default="false"/></Set>
<Set name="dumpBeforeStop"><Property name="jetty.server.dumpBeforeStop" deprecated="jetty.dump.stop" default="false"/></Set>
<Set name="dumpAfterStart"><Property name="jetty.server.dumpAfterStart" default="false"/></Set>
<Set name="dumpBeforeStop"><Property name="jetty.server.dumpBeforeStop" default="false"/></Set>
<Call class="org.eclipse.jetty.webapp.Configurations" name="setKnown">
<Arg>
<Array type="String">
<Item>org.eclipse.jetty.webapp.FragmentConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JettyWebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebAppConfiguration</Item>
<Item>org.eclipse.jetty.webapp.ServletsConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JspConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JaasConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JndiConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JmxConfiguration</Item>
<Item>org.eclipse.jetty.osgi.annotations.AnnotationConfiguration</Item>
<Item>org.eclipse.jetty.websocket.server.JettyWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.websocket.javax.server.JavaxWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiMetaInfConfiguration</Item>
</Array>
</Arg>
<Call class="org.eclipse.jetty.webapp.Configurations" name="setServerDefault">
<Arg><Ref refid="Server"/></Arg>
<Call name="add">
<Arg>
<Array type="String">
<Item>org.eclipse.jetty.webapp.FragmentConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JettyWebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebXmlConfiguration</Item>
<Item>org.eclipse.jetty.webapp.WebAppConfiguration</Item>
<Item>org.eclipse.jetty.webapp.ServletsConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JspConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JaasConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JndiConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
<Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
<Item>org.eclipse.jetty.webapp.JmxConfiguration</Item>
<Item>org.eclipse.jetty.osgi.annotations.AnnotationConfiguration</Item>
<Item>org.eclipse.jetty.websocket.server.JettyWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.websocket.javax.server.JavaxWebSocketConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiWebInfConfiguration</Item>
<Item>org.eclipse.jetty.osgi.boot.OSGiMetaInfConfiguration</Item>
</Array>
</Arg>
</Call>
</Call>
<Call class="java.lang.System" name="setProperty">

View File

@ -18,14 +18,7 @@
package org.eclipse.jetty.osgi.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.util.ArrayList;
import javax.inject.Inject;
import org.eclipse.jetty.client.HttpClient;
@ -42,6 +35,12 @@ import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
/**
* TestJettyOSGiBootContextAsService
*
@ -95,7 +94,7 @@ public class TestJettyOSGiBootContextAsService
client.start();
String tmp = System.getProperty("boot.context.service.port");
assertNotNull(tmp);
int port = Integer.valueOf(tmp).intValue();
int port = Integer.parseInt(tmp);
ContentResponse response = client.GET("http://127.0.0.1:" + port + "/acme/index.html");
assertEquals(HttpStatus.OK_200, response.getStatus());

View File

@ -18,15 +18,8 @@
package org.eclipse.jetty.osgi.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.jetty.client.HttpClient;
@ -42,6 +35,11 @@ import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
/**
* TestJettyOSGiBootWebAppAsService
*
@ -65,6 +63,7 @@ public class TestJettyOSGiBootWebAppAsService
public static Option[] configure()
{
ArrayList<Option> options = new ArrayList<>();
options.add(TestOSGiUtil.optionalRemoteDebug());
options.add(CoreOptions.junitBundles());
options.addAll(TestOSGiUtil.configureJettyHomeAndPort(false, "jetty-http-boot-webapp-as-service.xml"));
options.add(CoreOptions.bootDelegationPackages("org.xml.sax", "org.xml.*", "org.w3c.*", "javax.xml.*"));
@ -108,11 +107,17 @@ public class TestJettyOSGiBootWebAppAsService
@Test
public void testBundle() throws Exception
{
if (Boolean.getBoolean(TestOSGiUtil.BUNDLE_DEBUG))
assertAllBundlesActiveOrResolved();
ServiceReference<?>[] refs = bundleContext.getServiceReferences(WebAppContext.class.getName(), null);
assertNotNull(refs);
assertEquals(2, refs.length);
WebAppContext wac = (WebAppContext) bundleContext.getService(refs[0]);
assertEquals("/acme", wac.getContextPath());
wac = (WebAppContext) bundleContext.getService(refs[1]);
assertEquals("/acme", wac.getContextPath());
// now test getting a static file
HttpClient client = new HttpClient();
try
@ -122,34 +127,30 @@ public class TestJettyOSGiBootWebAppAsService
assertNotNull(port);
ContentResponse response = client.GET("http://127.0.0.1:" + port + "/acme/index.html");
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals("Response status code", HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertTrue(content.indexOf("<h1>Test OSGi WebAppA</h1>") != -1);
TestOSGiUtil.assertContains("Response contents", content,
"<h1>Test OSGi WebAppA</h1>");
response = client.GET("http://127.0.0.1:" + port + "/acme/mime");
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals("Response status code", HttpStatus.OK_200, response.getStatus());
content = response.getContentAsString();
assertTrue(content.indexOf("MIMETYPE=application/gzip") != -1);
TestOSGiUtil.assertContains("Response contents", content,
"MIMETYPE=application/gzip");
port = System.getProperty("bundle.server.port");
assertNotNull(port);
response = client.GET("http://127.0.0.1:" + port + "/acme/index.html");
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals("Response status code", HttpStatus.OK_200, response.getStatus());
content = response.getContentAsString();
assertTrue(content.indexOf("<h1>Test OSGi WebAppB</h1>") != -1);
TestOSGiUtil.assertContains("Response contents", content,
"<h1>Test OSGi WebAppB</h1>");
}
finally
{
client.stop();
}
ServiceReference<?>[] refs = bundleContext.getServiceReferences(WebAppContext.class.getName(), null);
assertNotNull(refs);
assertEquals(2, refs.length);
WebAppContext wac = (WebAppContext) bundleContext.getService(refs[0]);
assertEquals("/acme", wac.getContextPath());
wac = (WebAppContext) bundleContext.getService(refs[1]);
assertEquals("/acme", wac.getContextPath());
}
}

View File

@ -18,15 +18,8 @@
package org.eclipse.jetty.osgi.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.jetty.client.HttpClient;
@ -41,6 +34,11 @@ import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.BundleContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
/**
* Pax-Exam to make sure the jetty-osgi-boot can be started along with the
* httpservice web-bundle. Then make sure we can deploy an OSGi service on the
@ -59,6 +57,7 @@ public class TestJettyOSGiBootWithAnnotations
public static Option[] configure()
{
ArrayList<Option> options = new ArrayList<>();
options.add(TestOSGiUtil.optionalRemoteDebug());
options.add(CoreOptions.junitBundles());
options.addAll(TestOSGiUtil.configureJettyHomeAndPort(false, "jetty-http-boot-with-annotations.xml"));
options.add(CoreOptions.bootDelegationPackages("org.xml.sax", "org.xml.*", "org.w3c.*", "javax.sql.*","javax.xml.*", "javax.activation.*"));
@ -100,8 +99,6 @@ public class TestJettyOSGiBootWithAnnotations
TestOSGiUtil.assertAllBundlesActiveOrResolved(bundleContext);
}
@Test
public void testIndex() throws Exception
{
@ -117,19 +114,22 @@ public class TestJettyOSGiBootWithAnnotations
assertNotNull(port);
ContentResponse response = client.GET("http://127.0.0.1:" + port + "/index.html");
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals("Response status code", HttpStatus.OK_200, response.getStatus());
String content = response.getContentAsString();
assertTrue(content.contains("Test WebApp"));
TestOSGiUtil.assertContains("Response contents", content, "Test WebApp");
Request req = client.POST("http://127.0.0.1:" + port + "/test");
response = req.send();
assertEquals("Response status code", HttpStatus.OK_200, response.getStatus());
content = response.getContentAsString();
assertTrue(content.contains("<p><b>Result: <span class=\"pass\">PASS</span></p>"));
TestOSGiUtil.assertContains("Response contents", content,
"<p><b>Result: <span class=\"pass\">PASS</span></p>");
response = client.GET("http://127.0.0.1:" + port + "/frag.html");
assertEquals("Response status code", HttpStatus.OK_200, response.getStatus());
content = response.getContentAsString();
assertTrue(content.contains("<h1>FRAGMENT</h1>"));
TestOSGiUtil.assertContains("Response contents", content,"<h1>FRAGMENT</h1>");
}
finally
{

View File

@ -18,18 +18,12 @@
package org.eclipse.jetty.osgi.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.jetty.client.HttpClient;
@ -48,6 +42,11 @@ import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
/**
* TestJettyOSGiBootWithBundle
*
@ -120,7 +119,7 @@ public class TestJettyOSGiBootWithBundle
client.start();
String tmp = System.getProperty("boot.bundle.port");
assertNotNull(tmp);
int port = Integer.valueOf(tmp.trim()).intValue();
int port = Integer.parseInt(tmp.trim());
ContentResponse response = client.GET("http://127.0.0.1:" + port);
assertEquals(HttpStatus.NOT_FOUND_404, response.getStatus());
String content = new String(response.getContent());

View File

@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -300,6 +299,11 @@ public class TestOSGiUtil
return options;
}
public static void assertContains(String message, String haystack, String needle)
{
assertTrue(message + "\nContains: <" + needle + ">\nIn:\n" + haystack, haystack.contains(needle));
}
protected static void testHttpServiceGreetings(BundleContext bundleContext, String protocol, int port) throws Exception
{
assertActiveBundle(bundleContext, "org.eclipse.jetty.osgi.boot");

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.plus.webapp;
import java.util.Random;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
@ -116,7 +115,7 @@ public class PlusConfiguration extends AbstractConfiguration
try
{
Random random = new Random ();
_key = new Integer(random.nextInt());
_key = random.nextInt();
Context context = new InitialContext();
Context compCtx = (Context)context.lookup("java:comp");
compCtx.addToEnvironment("org.eclipse.jetty.jndi.lock", _key);

View File

@ -46,40 +46,6 @@ public class QuickStartWebApp extends WebAppContext
setCopyWebInf(false);
}
@Deprecated
public boolean isPreconfigure()
{
switch(_quickStartConfiguration.getMode())
{
case AUTO:
case GENERATE:
return true;
default: return false;
}
}
@Deprecated
public void setPreconfigure(boolean preconfigure)
{
_quickStartConfiguration.setMode(preconfigure?Mode.GENERATE:Mode.DISABLED);
}
@Deprecated
public boolean isAutoPreconfigure()
{
switch(_quickStartConfiguration.getMode())
{
case AUTO: return true;
default: return false;
}
}
@Deprecated
public void setAutoPreconfigure(boolean autoPrecompile)
{
_quickStartConfiguration.setMode(autoPrecompile?Mode.AUTO:Mode.DISABLED);
}
public void setOriginAttribute (String name)
{
setAttribute(QuickStartConfiguration.ORIGIN_ATTRIBUTE,name);

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import java.util.regex.Matcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -54,12 +53,6 @@ public class RedirectRegexRule extends RegexRule
setLocation(location);
}
@Deprecated
public void setReplacement(String replacement)
{
_location = replacement;
}
public void setLocation(String location)
{
_location = location;

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -59,20 +58,6 @@ public class ResponsePatternRule extends PatternRule
_code = code==null ? 0 : Integer.parseInt(code);
}
/* ------------------------------------------------------------ */
/**
* Sets the reason for the response status code. Reasons will only reflect
* if the code value is greater or equal to 400.
* @deprecated Reason has been replaced by message
* @param reason the reason
* @see #setMessage(String)
*/
@Deprecated
public void setReason(String reason)
{
setMessage(reason);
}
/* ------------------------------------------------------------ */
/**
* Sets the message for the {@link org.eclipse.jetty.server.Response#sendError(int, String)} method.

View File

@ -21,7 +21,6 @@ package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import java.util.Arrays;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -201,17 +200,6 @@ public class RewriteHandler extends HandlerWrapper
_rules.setRules(rules);
}
/*------------------------------------------------------------ */
/**
* Assigns the rules to process.
* @param rules a {@link RuleContainer} containing other rules to process
*/
@Deprecated
public void setRules(RuleContainer rules)
{
_rules = rules;
}
/*------------------------------------------------------------ */
/**
* Assigns the rules to process.

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -62,19 +61,6 @@ public class ValidUrlRule extends Rule
_code = code;
}
/* ------------------------------------------------------------ */
/**
* Sets the reason for the response status code.
*
* @param reason the reason
* @deprecated use {@link #setMessage(String)}
*/
@Deprecated
public void setReason(String reason)
{
_message = reason;
}
/* ------------------------------------------------------------ */
/**
* Sets the message for the {@link org.eclipse.jetty.server.Response#sendError(int, String)} method.

View File

@ -18,9 +18,6 @@
package org.eclipse.jetty.rewrite.handler;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.io.IOException;
import org.eclipse.jetty.http.HttpHeader;
@ -28,6 +25,9 @@ import org.eclipse.jetty.http.HttpStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class RedirectRegexRuleTest extends AbstractRuleTestCase
{
@BeforeEach
@ -45,9 +45,7 @@ public class RedirectRegexRuleTest extends AbstractRuleTestCase
@Test
public void testLocationWithReplacementGroupEmpty() throws IOException
{
RedirectRegexRule rule = new RedirectRegexRule();
rule.setRegex("/my/dir/file/(.*)$");
rule.setReplacement("http://www.mortbay.org/$1");
RedirectRegexRule rule = new RedirectRegexRule("/my/dir/file/(.*)$", "http://www.mortbay.org/$1");
// Resource is dir
rule.matchAndApply("/my/dir/file/", _request, _response);
@ -57,9 +55,7 @@ public class RedirectRegexRuleTest extends AbstractRuleTestCase
@Test
public void testLocationWithPathReplacement() throws IOException
{
RedirectRegexRule rule = new RedirectRegexRule();
rule.setRegex("/documentation/(.*)$");
rule.setReplacement("/docs/$1");
RedirectRegexRule rule = new RedirectRegexRule("/documentation/(.*)$", "/docs/$1");
// Resource is dir
rule.matchAndApply("/documentation/top.html", _request, _response);
@ -69,9 +65,7 @@ public class RedirectRegexRuleTest extends AbstractRuleTestCase
@Test
public void testLocationWithReplacmentGroupSimple() throws IOException
{
RedirectRegexRule rule = new RedirectRegexRule();
rule.setRegex("/my/dir/file/(.*)$");
rule.setReplacement("http://www.mortbay.org/$1");
RedirectRegexRule rule = new RedirectRegexRule("/my/dir/file/(.*)$", "http://www.mortbay.org/$1");
// Resource is an image
rule.matchAndApply("/my/dir/file/image.png", _request, _response);
@ -81,9 +75,7 @@ public class RedirectRegexRuleTest extends AbstractRuleTestCase
@Test
public void testLocationWithReplacementGroupDeepWithParams() throws IOException
{
RedirectRegexRule rule = new RedirectRegexRule();
rule.setRegex("/my/dir/file/(.*)$");
rule.setReplacement("http://www.mortbay.org/$1");
RedirectRegexRule rule = new RedirectRegexRule("/my/dir/file/(.*)$", "http://www.mortbay.org/$1");
// Resource is api with parameters
rule.matchAndApply("/my/dir/file/api/rest/foo?id=100&sort=date", _request, _response);
@ -95,7 +87,7 @@ public class RedirectRegexRuleTest extends AbstractRuleTestCase
{
RedirectRegexRule rule = new RedirectRegexRule();
rule.setRegex("/api/(.*)$");
rule.setReplacement("http://api.company.com/$1");
rule.setLocation("http://api.company.com/$1");
rule.setStatusCode(HttpStatus.MOVED_PERMANENTLY_301);
// Resource is api with parameters

View File

@ -18,11 +18,7 @@
package org.eclipse.jetty.rewrite.handler;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -34,6 +30,9 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class TerminatingPatternRuleTest extends AbstractRuleTestCase
{
private RewriteHandler rewriteHandler;
@ -60,9 +59,7 @@ public class TerminatingPatternRuleTest extends AbstractRuleTestCase
TerminatingPatternRule rule1 = new TerminatingPatternRule();
rule1.setPattern("/login.jsp");
rewriteHandler.addRule(rule1);
RedirectRegexRule rule2 = new RedirectRegexRule();
rule2.setRegex("^/login.*$");
rule2.setReplacement("http://login.company.com/");
RedirectRegexRule rule2 = new RedirectRegexRule("^/login.*$", "http://login.company.com/");
rewriteHandler.addRule(rule2);
start(false);

View File

@ -18,11 +18,7 @@
package org.eclipse.jetty.rewrite.handler;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -34,6 +30,9 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class TerminatingRegexRuleTest extends AbstractRuleTestCase
{
private RewriteHandler rewriteHandler;
@ -60,9 +59,7 @@ public class TerminatingRegexRuleTest extends AbstractRuleTestCase
TerminatingRegexRule rule1 = new TerminatingRegexRule();
rule1.setRegex("^/login.jsp$");
rewriteHandler.addRule(rule1);
RedirectRegexRule rule2 = new RedirectRegexRule();
rule2.setRegex("^/login.*$");
rule2.setReplacement("http://login.company.com/");
RedirectRegexRule rule2 = new RedirectRegexRule("^/login.*$", "http://login.company.com/");
rewriteHandler.addRule(rule2);
start(false);

View File

@ -78,7 +78,7 @@ public class ValidUrlRuleTest extends AbstractRuleTestCase
public void testInvalidJsp() throws Exception
{
_rule.setCode("405");
_rule.setReason("foo");
_rule.setMessage("foo");
_request.setURIPathQuery("/jsp/bean1.jsp%00");
String result = _rule.matchAndApply(_request.getRequestURI(), _request, _response);
@ -92,7 +92,7 @@ public class ValidUrlRuleTest extends AbstractRuleTestCase
public void testInvalidShamrock() throws Exception
{
_rule.setCode("405");
_rule.setReason("foo");
_rule.setMessage("foo");
_request.setURIPathQuery("/jsp/shamrock-%00%E2%98%98.jsp");
String result = _rule.matchAndApply(_request.getRequestURI(), _request, _response);
@ -106,7 +106,7 @@ public class ValidUrlRuleTest extends AbstractRuleTestCase
public void testValidShamrock() throws Exception
{
_rule.setCode("405");
_rule.setReason("foo");
_rule.setMessage("foo");
_request.setURIPathQuery("/jsp/shamrock-%E2%98%98.jsp");
String result = _rule.matchAndApply(_request.getRequestURI(), _request, _response);

View File

@ -54,8 +54,8 @@ import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.xml.XmlConfiguration;
/**
@ -304,7 +304,7 @@ public class Runner
stopKey = sysProps[1];
break;
} else if("STOP.PORT".equals( sysProps[0] )){
stopPort = Integer.valueOf(sysProps[1]);
stopPort = Integer.parseInt(sysProps[1]);
break;
}
}
@ -436,7 +436,7 @@ public class Runner
if (contextPathSet)
handler.setContextPath(contextPath);
_contexts.addHandler(handler);
String containerIncludeJarPattern = (String)handler.getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
String containerIncludeJarPattern = (String)handler.getAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN);
if (containerIncludeJarPattern == null)
containerIncludeJarPattern = __containerIncludeJarPattern;
else
@ -447,7 +447,7 @@ public class Runner
}
}
handler.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern);
handler.setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern);
//check the configurations, if not explicitly set up, then configure all of them
if (handler instanceof WebAppContext)
@ -462,7 +462,7 @@ public class Runner
// assume it is a WAR file
WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
webapp.setConfigurationClasses(__plusConfigurationClasses);
webapp.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN,
webapp.setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN,
__containerIncludeJarPattern);
}
}

View File

@ -18,8 +18,6 @@
package org.eclipse.jetty.security;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@ -27,7 +25,6 @@ import java.util.stream.Collectors;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
/* ------------------------------------------------------------ */
/**
@ -81,13 +78,6 @@ public class HashLoginService extends AbstractLoginService
}
/* ------------------------------------------------------------ */
@Deprecated
public Resource getConfigResource()
{
return null;
}
/* ------------------------------------------------------------ */
/**
* Load realm users from properties file.
@ -188,7 +178,7 @@ public class HashLoginService extends AbstractLoginService
LOG.debug("doStart: Starting new PropertyUserStore. PropertiesFile: " + _config + " hotReload: " + hotReload);
PropertyUserStore propertyUserStore = new PropertyUserStore();
propertyUserStore.setHotReload(hotReload);
propertyUserStore.setConfigPath(_config);
propertyUserStore.setConfig(_config);
propertyUserStore.start();
_userStore = propertyUserStore;
_userStoreAutoCreate = true;

View File

@ -122,17 +122,6 @@ public class PropertyUserStore extends UserStore implements PathWatcher.Listener
return _configPath;
}
/**
* Set the Config Path from a String reference to a file
*
* @param configFile the config file can a be a file path or a reference to a file within a jar file {@code jar:file:}
*/
@Deprecated
public void setConfigPath(String configFile)
{
setConfig(configFile);
}
private Path extractPackedFile(JarFileResource configResource) throws IOException
{
String uri = configResource.getURI().toASCIIString();
@ -156,17 +145,6 @@ public class PropertyUserStore extends UserStore implements PathWatcher.Listener
return extractedPath;
}
/**
* Set the Config Path from a {@link File} reference
*
* @param configFile the config file
*/
@Deprecated
public void setConfigPath(File configFile)
{
setConfigFile(configFile);
}
/**
* Set the Config Path from a {@link File} reference
*

View File

@ -18,13 +18,11 @@
package org.eclipse.jetty.security.authentication;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.Principal;
import java.security.cert.CRL;
import java.security.cert.X509Certificate;
import java.util.Collection;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@ -139,11 +137,6 @@ public class ClientCertAuthenticator extends LoginAuthenticator
}
}
@Deprecated
protected KeyStore getKeyStore(InputStream storeStream, String storePath, String storeType, String storeProvider, String storePassword) throws Exception
{
return getKeyStore(storePath, storeType, storeProvider, storePassword);
}
/* ------------------------------------------------------------ */
/**
* Loads keystore using an input stream or a file path in the same

View File

@ -24,7 +24,6 @@ import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@ -186,6 +185,7 @@ public class DeferredAuthentication implements Authentication.Deferred
}
@Override
@Deprecated(since = "Servlet API 2.1")
public String encodeRedirectUrl(String url)
{
return null;
@ -198,6 +198,7 @@ public class DeferredAuthentication implements Authentication.Deferred
}
@Override
@Deprecated(since = "Servlet API 2.1")
public String encodeUrl(String url)
{
return null;
@ -239,6 +240,7 @@ public class DeferredAuthentication implements Authentication.Deferred
}
@Override
@Deprecated(since = "Servlet API 2.1")
public void setStatus(int sc, String sm)
{
}

View File

@ -66,11 +66,9 @@
<Set name="headerCacheSize"><Property name="jetty.httpConfig.headerCacheSize" default="4096" /></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" deprecated="jetty.delayDispatchUntilContent" default="true"/></Set>
<Set name="maxErrorDispatches"><Property name="jetty.httpConfig.maxErrorDispatches" default="10"/></Set>
<Set name="blockingTimeout"><Property deprecated="jetty.httpConfig.blockingTimeout" name="jetty.httpConfig.blockingTimeout.DEPRECATED" default="-1"/></Set>
<Set name="persistentConnectionsEnabled"><Property name="jetty.httpConfig.persistentConnectionsEnabled" default="true"/></Set>
<Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="responseCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.responseCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="multiPartFormDataCompliance"><Call class="org.eclipse.jetty.http.MultiPartFormDataCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.multiPartFormDataCompliance" default="RFC7578"/></Arg></Call></Set>
</New>
<!-- =========================================================== -->

View File

@ -158,12 +158,6 @@ public class CachedContentFactory implements HttpContent.ContentFactory
}
}
@Deprecated
public HttpContent lookup(String pathInContext) throws IOException
{
return getContent(pathInContext, _maxCachedFileSize);
}
/**
* <p>Returns an entry from the cache, or creates a new one.</p>
*

View File

@ -64,7 +64,7 @@ public class ClassLoaderDump implements Dumpable
}
else if (_loader.getDefinedPackages()!=null)
{
DumpableCollection packages = DumpableCollection.from("packages", _loader.getDefinedPackages());
DumpableCollection packages = DumpableCollection.from("packages", (Object[]) _loader.getDefinedPackages());
ClassLoader parent = _loader.getParent();
if (parent==Server.class.getClassLoader())
Dumpable.dumpObjects(out,indent,_loader,packages,"Server loader: " + parent);

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.server;
import java.net.InetSocketAddress;
import javax.servlet.ServletRequest;
import org.eclipse.jetty.http.HostPortHttpField;
@ -462,24 +461,6 @@ public class ForwardedRequestCustomizer implements Customizer
return String.format("%s@%x",this.getClass().getSimpleName(),hashCode());
}
@Deprecated
public String getHostHeader()
{
return _forcedHost.getValue();
}
/**
* Set a forced valued for the host header to control what is returned by {@link ServletRequest#getServerName()} and {@link ServletRequest#getServerPort()}.
*
* @param hostHeader
* The value of the host header to force.
*/
@Deprecated
public void setHostHeader(String hostHeader)
{
_forcedHost = new HostPortHttpField(hostHeader);
}
private final class RFC7239 extends QuotedCSV
{
HostPortHttpField _by;

View File

@ -27,7 +27,6 @@ import org.eclipse.jetty.http.CookieCompliance;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.MultiPartFormDataCompliance;
import org.eclipse.jetty.util.Jetty;
import org.eclipse.jetty.util.TreeTrie;
import org.eclipse.jetty.util.Trie;
@ -64,7 +63,6 @@ public class HttpConfiguration implements Dumpable
private int _headerCacheSize=4*1024;
private int _securePort;
private long _idleTimeout=-1;
private long _blockingTimeout=-1;
private String _secureScheme = HttpScheme.HTTPS.asString();
private boolean _sendServerVersion = true;
private boolean _sendXPoweredBy = false;
@ -78,7 +76,6 @@ public class HttpConfiguration implements Dumpable
private HttpCompliance _httpCompliance = HttpCompliance.RFC7230;
private CookieCompliance _requestCookieCompliance = CookieCompliance.RFC6265;
private CookieCompliance _responseCookieCompliance = CookieCompliance.RFC6265;
private MultiPartFormDataCompliance _multiPartCompliance = MultiPartFormDataCompliance.RFC7578;
private boolean _notifyRemoteAsyncErrors = true;
/**
@ -131,7 +128,6 @@ public class HttpConfiguration implements Dumpable
_secureScheme=config._secureScheme;
_securePort=config._securePort;
_idleTimeout=config._idleTimeout;
_blockingTimeout=config._blockingTimeout;
_sendDateHeader=config._sendDateHeader;
_sendServerVersion=config._sendServerVersion;
_sendXPoweredBy=config._sendXPoweredBy;
@ -244,41 +240,6 @@ public class HttpConfiguration implements Dumpable
_idleTimeout=timeoutMs;
}
/**
* <p>This timeout is in addition to the {@link Connector#getIdleTimeout()}, and applies
* to the total operation (as opposed to the idle timeout that applies to the time no
* data is being sent). This applies only to blocking operations and does not affect
* asynchronous read and write.</p>
*
* @return -1, for no blocking timeout (default), 0 for a blocking timeout equal to the
* idle timeout; &gt;0 for a timeout in ms applied to the total blocking operation.
* @deprecated Replaced by {@link #getMinResponseDataRate()} and {@link #getMinRequestDataRate()}
*/
@ManagedAttribute(value = "Total timeout in ms for blocking I/O operations. DEPRECATED!", readonly = true)
@Deprecated
public long getBlockingTimeout()
{
return _blockingTimeout;
}
/**
* <p>This timeout is in addition to the {@link Connector#getIdleTimeout()}, and applies
* to the total operation (as opposed to the idle timeout that applies to the time no
* data is being sent).This applies only to blocking operations and does not affect
* asynchronous read and write.</p>
*
* @param blockingTimeout -1, for no blocking timeout (default), 0 for a blocking timeout equal to the
* idle timeout; &gt;0 for a timeout in ms applied to the total blocking operation.
* @deprecated Replaced by {@link #setMinResponseDataRate(long)} and {@link #setMinRequestDataRate(long)}
*/
@Deprecated
public void setBlockingTimeout(long blockingTimeout)
{
if (blockingTimeout>0)
LOG.warn("HttpConfiguration.setBlockingTimeout is deprecated!");
_blockingTimeout = blockingTimeout;
}
public void setPersistentConnectionsEnabled(boolean persistentConnectionsEnabled)
{
_persistentConnectionsEnabled = persistentConnectionsEnabled;
@ -600,22 +561,6 @@ public class HttpConfiguration implements Dumpable
_responseCookieCompliance = cookieCompliance==null?CookieCompliance.RFC6265:cookieCompliance;
}
/**
* Sets the compliance level for multipart/form-data handling.
*
* @param multiPartCompliance The multipart/form-data compliance level.
*/
public void setMultiPartFormDataCompliance(MultiPartFormDataCompliance multiPartCompliance)
{
_multiPartCompliance = multiPartCompliance==null?MultiPartFormDataCompliance.RFC7578:multiPartCompliance;
}
public MultiPartFormDataCompliance getMultipartFormDataCompliance()
{
return _multiPartCompliance;
}
/**
* @param notifyRemoteAsyncErrors whether remote errors, when detected, are notified to async applications
*/
@ -651,7 +596,6 @@ public class HttpConfiguration implements Dumpable
"secureScheme=" + _secureScheme,
"securePort=" + _securePort,
"idleTimeout=" + _idleTimeout,
"blockingTimeout=" + _blockingTimeout,
"sendDateHeader=" + _sendDateHeader,
"sendServerVersion=" + _sendServerVersion,
"sendXPoweredBy=" + _sendXPoweredBy,
@ -660,8 +604,8 @@ public class HttpConfiguration implements Dumpable
"maxErrorDispatches=" + _maxErrorDispatches,
"minRequestDataRate=" + _minRequestDataRate,
"minResponseDataRate=" + _minResponseDataRate,
"cookieCompliance=" + _requestCookieCompliance,
"setRequestCookieCompliance=" + _responseCookieCompliance,
"requestCookieCompliance=" + _requestCookieCompliance,
"responseCookieCompliance=" + _responseCookieCompliance,
"notifyRemoteAsyncErrors=" + _notifyRemoteAsyncErrors
);
}

View File

@ -26,8 +26,6 @@ import java.util.Deque;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
@ -245,11 +243,6 @@ public class HttpInput extends ServletInputStream implements Runnable
executor.execute(channel);
}
private long getBlockingTimeout()
{
return getHttpChannelState().getHttpChannel().getHttpConfiguration().getBlockingTimeout();
}
@Override
public int read() throws IOException
{
@ -266,17 +259,6 @@ public class HttpInput extends ServletInputStream implements Runnable
int l;
synchronized (_inputQ)
{
if (!isAsync())
{
// Setup blocking only if not async
if (_blockUntil == 0)
{
long blockingTimeout = getBlockingTimeout();
if (blockingTimeout > 0)
_blockUntil = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(blockingTimeout);
}
}
// Calculate minimum request rate for DOS protection
long minRequestDataRate = _channelState.getHttpChannel().getHttpConfiguration().getMinRequestDataRate();
if (minRequestDataRate > 0 && _firstByteTimeStamp != -1)
@ -555,13 +537,6 @@ public class HttpInput extends ServletInputStream implements Runnable
long timeout = 0;
while (true)
{
if (_blockUntil != 0)
{
timeout = TimeUnit.NANOSECONDS.toMillis(_blockUntil - System.nanoTime());
if (timeout <= 0)
throw new TimeoutException(String.format("Blocking timeout %d ms", getBlockingTimeout()));
}
// This method is called from a loop, so we just
// need to check the timeout before and after waiting.
if (loop)

View File

@ -31,7 +31,6 @@ import java.nio.charset.CodingErrorAction;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
@ -1522,14 +1521,5 @@ public class HttpOutput extends ServletOutputStream implements Runnable
{
_channel = channel;
}
@Override
protected long getIdleTimeout()
{
long blockingTimeout = _channel.getHttpConfiguration().getBlockingTimeout();
if (blockingTimeout == 0)
return _channel.getIdleTimeout();
return blockingTimeout;
}
}
}

View File

@ -84,91 +84,6 @@ public class LocalConnector extends AbstractConnector
return this;
}
/** Sends requests and get responses based on thread activity.
* Returns all the responses received once the thread activity has
* returned to the level it was before the requests.
* <p>
* This methods waits until the connection is closed or
* is idle for 5s before returning the responses.
* <p>Use {@link #getResponse(String)} for an alternative that does not wait for idle.
* @param requests the requests
* @return the responses
* @throws Exception if the requests fail
* @deprecated Use {@link #getResponse(String)}
*/
@Deprecated
public String getResponses(String requests) throws Exception
{
return getResponses(requests, 5, TimeUnit.SECONDS);
}
/** Sends requests and get responses based on thread activity.
* Returns all the responses received once the thread activity has
* returned to the level it was before the requests.
* <p>
* This methods waits until the connection is closed or
* an idle period before returning the responses.
* <p>Use {@link #getResponse(String)} for an alternative that does not wait for idle.
* @param requests the requests
* @param idleFor The time the response stream must be idle for before returning
* @param units The units of idleFor
* @return the responses
* @throws Exception if the requests fail
* @deprecated Use {@link #getResponse(String, boolean, long, TimeUnit)}
*/
@Deprecated
public String getResponses(String requests,long idleFor,TimeUnit units) throws Exception
{
ByteBuffer result = getResponses(BufferUtil.toBuffer(requests,StandardCharsets.UTF_8),idleFor,units);
return result==null?null:BufferUtil.toString(result,StandardCharsets.UTF_8);
}
/** Sends requests and get's responses based on thread activity.
* Returns all the responses received once the thread activity has
* returned to the level it was before the requests.
* <p>
* This methods waits until the connection is closed or
* is idle for 5s before returning the responses.
* <p>Use {@link #getResponse(ByteBuffer)} for an alternative that does not wait for idle.
* @param requestsBuffer the requests
* @return the responses
* @throws Exception if the requests fail
* @deprecated Use {@link #getResponse(ByteBuffer)}
*/
@Deprecated
public ByteBuffer getResponses(ByteBuffer requestsBuffer) throws Exception
{
return getResponses(requestsBuffer, 5, TimeUnit.SECONDS);
}
/** Sends requests and get's responses based on thread activity.
* Returns all the responses received once the thread activity has
* returned to the level it was before the requests.
* <p>
* This methods waits until the connection is closed or
* an idle period before returning the responses.
* @param requestsBuffer the requests
* @param idleFor The time the response stream must be idle for before returning
* @param units The units of idleFor
* @return the responses
* @throws Exception if the requests fail
* @deprecated Use {@link #getResponse(ByteBuffer, boolean, long, TimeUnit)}
*/
@Deprecated
public ByteBuffer getResponses(ByteBuffer requestsBuffer,long idleFor,TimeUnit units) throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("requests {}", BufferUtil.toUTF8String(requestsBuffer));
LocalEndPoint endp = executeRequest(requestsBuffer);
endp.waitUntilClosedOrIdleFor(idleFor,units);
ByteBuffer responses = endp.takeOutput();
if (endp.isOutputShutdown())
endp.close();
if (LOG.isDebugEnabled())
LOG.debug("responses {}", BufferUtil.toUTF8String(responses));
return responses;
}
/**
* Execute a request and return the EndPoint through which
* multiple responses can be received or more input provided.

View File

@ -18,6 +18,15 @@
package org.eclipse.jetty.server;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -29,15 +38,6 @@ import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
import org.eclipse.jetty.util.thread.ThreadPool;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*
@ -48,11 +48,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
* <li>If {@link #setMaxMemory(long)} is non zero then low resources is detected if the JVMs
* {@link Runtime} instance has {@link Runtime#totalMemory()} minus {@link Runtime#freeMemory()}
* greater than {@link #getMaxMemory()}</li>
* <li>If {@link #setMaxConnections(int)} is non zero then low resources is detected if the total number
* of connections exceeds {@link #getMaxConnections()}. This feature is deprecated and replaced by
* {@link ConnectionLimit}</li>
* </ul>
*
*/
@ManagedObject ("Monitor for low resource conditions and activate a low resource mode if detected")
public class LowResourceMonitor extends ContainerLifeCycle
@ -115,48 +111,6 @@ public class LowResourceMonitor extends ContainerLifeCycle
getBeans(ConnectorsThreadPoolLowResourceCheck.class).forEach(this::removeBean);
}
/**
* @return The maximum connections allowed for the monitored connectors before low resource handling is activated
* @deprecated Replaced by ConnectionLimit
*/
@ManagedAttribute("The maximum connections allowed for the monitored connectors before low resource handling is activated")
@Deprecated
public int getMaxConnections()
{
for(MaxConnectionsLowResourceCheck lowResourceCheck : getBeans(MaxConnectionsLowResourceCheck.class))
{
if (lowResourceCheck.getMaxConnections()>0)
{
return lowResourceCheck.getMaxConnections();
}
}
return -1;
}
/**
* @param maxConnections The maximum connections before low resources state is triggered
* @deprecated Replaced by ConnectionLimit
*/
@Deprecated
public void setMaxConnections(int maxConnections)
{
if (maxConnections>0)
{
if (getBeans(MaxConnectionsLowResourceCheck.class).isEmpty())
{
addLowResourceCheck(new MaxConnectionsLowResourceCheck(maxConnections));
} else
{
getBeans(MaxConnectionsLowResourceCheck.class).forEach( c -> c.setMaxConnections( maxConnections ) );
}
}
else
{
getBeans(ConnectorsThreadPoolLowResourceCheck.class).forEach(this::removeBean);
}
}
@ManagedAttribute("The reasons the monitored connectors are low on resources")
public String getReasons()
{
@ -545,29 +499,6 @@ public class LowResourceMonitor extends ContainerLifeCycle
this.maxConnections = maxConnections;
}
/**
* @return The maximum connections allowed for the monitored connectors before low resource handling is activated
* @deprecated Replaced by ConnectionLimit
*/
@ManagedAttribute("The maximum connections allowed for the monitored connectors before low resource handling is activated")
@Deprecated
public int getMaxConnections()
{
return maxConnections;
}
/**
* @param maxConnections The maximum connections before low resources state is triggered
* @deprecated Replaced by ConnectionLimit
*/
@Deprecated
public void setMaxConnections(int maxConnections)
{
if (maxConnections>0)
LOG.warn("LowResourceMonitor.setMaxConnections is deprecated. Use ConnectionLimit.");
this.maxConnections = maxConnections;
}
@Override
public boolean isLowOnResources()
{

View File

@ -22,18 +22,11 @@ import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.MultiPartFormInputStream;
import org.eclipse.jetty.http.MultiPartInputStreamParser;
import org.eclipse.jetty.http.MultiPartInputStreamParser.NonCompliance;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
@ -105,77 +98,4 @@ public interface MultiParts extends Closeable
}
}
@SuppressWarnings("deprecation")
class MultiPartsUtilParser implements MultiParts
{
private final MultiPartInputStreamParser _utilParser;
private final ContextHandler.Context _context;
public MultiPartsUtilParser(InputStream in, String contentType, MultipartConfigElement config, File contextTmpDir, Request request) throws IOException
{
_utilParser = new MultiPartInputStreamParser(in, contentType, config, contextTmpDir);
_context = request.getContext();
_utilParser.getParts();
EnumSet<NonCompliance> nonComplianceWarnings = _utilParser.getNonComplianceWarnings();
if (!nonComplianceWarnings.isEmpty())
{
@SuppressWarnings("unchecked")
List<String> violations = (List<String>)request.getAttribute(HttpCompliance.VIOLATIONS_ATTR);
if (violations==null)
{
violations = new ArrayList<>();
request.setAttribute(HttpCompliance.VIOLATIONS_ATTR,violations);
}
for(NonCompliance nc : nonComplianceWarnings)
violations.add(nc.name()+": "+nc.getURL());
}
}
@Override
public Collection<Part> getParts()
{
try
{
return _utilParser.getParts();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public Part getPart(String name)
{
try
{
return _utilParser.getPart(name);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public void close()
{
_utilParser.deleteParts();
}
@Override
public boolean isEmpty()
{
return _utilParser.getParsedParts().isEmpty();
}
@Override
public Context getContext()
{
return _context;
}
}
}

View File

@ -42,7 +42,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncListener;
import javax.servlet.DispatcherType;
@ -80,10 +79,9 @@ import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.MultiPartFormDataCompliance;
import org.eclipse.jetty.http.pathmap.PathSpec;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.http.pathmap.ServletPathSpec;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.session.Session;
@ -281,13 +279,6 @@ public class Request implements HttpServletRequest
return !isPush() && getHttpChannel().getHttpTransport().isPushSupported();
}
/* ------------------------------------------------------------ */
@Deprecated
public PushBuilder getPushBuilder()
{
return newPushBuilder();
}
/* ------------------------------------------------------------ */
@Override
public PushBuilder newPushBuilder()
@ -1192,10 +1183,8 @@ public class Request implements HttpServletRequest
}
/* ------------------------------------------------------------ */
/*
* @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
*/
@Override
@Deprecated(since = "Servlet API 2.1")
public String getRealPath(String path)
{
if (_context == null)
@ -1680,6 +1669,7 @@ public class Request implements HttpServletRequest
* @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
*/
@Override
@Deprecated(since = "Servlet API 2.1")
public boolean isRequestedSessionIdFromUrl()
{
return _requestedSessionId != null && !_requestedSessionIdFromCookie;
@ -2395,25 +2385,11 @@ public class Request implements HttpServletRequest
return _multiParts.getParts();
}
private MultiParts newMultiParts(ServletInputStream inputStream, String contentType, MultipartConfigElement config, Object object) throws IOException
{
MultiPartFormDataCompliance compliance = getHttpChannel().getHttpConfiguration().getMultipartFormDataCompliance();
if(LOG.isDebugEnabled())
LOG.debug("newMultiParts {} {}",compliance, this);
switch(compliance)
{
case RFC7578:
return new MultiParts.MultiPartsHttpParser(getInputStream(), getContentType(), config,
(_context != null?(File)_context.getAttribute("javax.servlet.context.tempdir"):null), this);
case LEGACY:
default:
return new MultiParts.MultiPartsUtilParser(getInputStream(), getContentType(), config,
(_context != null?(File)_context.getAttribute("javax.servlet.context.tempdir"):null), this);
}
return new MultiParts.MultiPartsHttpParser(getInputStream(), getContentType(), config,
(_context != null ? (File) _context.getAttribute("javax.servlet.context.tempdir") : null), this);
}
/* ------------------------------------------------------------ */

View File

@ -107,12 +107,6 @@ public class RequestLogWriter extends AbstractLifeCycle implements RequestLog.Wr
return null;
}
@Deprecated
protected boolean isEnabled()
{
return (_fileOut != null);
}
/**
* Set the number of days before rotated log files are deleted.
*

View File

@ -30,7 +30,6 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
@ -572,14 +571,14 @@ public class Response implements HttpServletResponse
}
@Override
@Deprecated
@Deprecated(since = "Servlet API 2.1")
public String encodeUrl(String url)
{
return encodeURL(url);
}
@Override
@Deprecated
@Deprecated(since = "Servlet API 2.1")
public String encodeRedirectUrl(String url)
{
return encodeRedirectURL(url);
@ -868,7 +867,7 @@ public class Response implements HttpServletResponse
}
@Override
@Deprecated
@Deprecated(since = "Servlet API 2.1")
public void setStatus(int sc, String message)
{
setStatusWithReason(sc, null);
@ -1309,12 +1308,6 @@ public class Response implements HttpServletResponse
_out.resetBuffer();
}
@Deprecated
public void setTrailerHttpFields(Supplier<HttpFields> trailers)
{
this._trailers = trailers;
}
@Override
public void setTrailerFields(Supplier<Map<String,String>> trailers)
{

Some files were not shown because too many files have changed in this diff Show More