Issue #2431 - Upgrade to Junit 5 (#2436)

+ Changes needed for new Junit 5
+ Migrating from Vintage junit API to Jupiter junit API
+ Relies on SNAPSHOT jetty-test-helper
  - this will be a formal release once this issue has been
    resolved satisfactory
+ Have jenkins always pull latest SNAPSHOT for each build
+ Adding jetty.snapshots repository
+ Using surefire 2.22.0 per advice from junit
+ Ensuring <reuseForks>true</reuseForks> to work around issue junit-team/junit5#801
+ Disabling <forkMode>always</forkMode> in maven-surefire-plugin
  due to bug https://github.com/junit-team/junit5/issues/801
+ OSGi tests must remain at vintage due to PaxExam
+ Moving from vintage TestingDir to jupiter WorkDir
+ Fixing imports to use jupiter, not vintage
+ Migrating vintage ExpectedException to jupiter assertThrows
+ Migrating vintage TestName to jupiter TestInfo
+ Migrating @RunWith(Parameterized.class)
  to @ParameterizedTest with Argument Sources
+ Migrating assertTrue(val.contains(needle))
  to assertThat(val, containsString(needle))
+ Aligning junit versions per recommendations from @sormuras
+ Adjusting parameter order change for assertEquals()
+ Test LifeCycle Annotation Migration

junit 4      | junit 5 / jupiter
------------ | -----------
@Before      | @BeforeEach
@After       | @AfterEach
@BeforeClass | @BeforeAll
@AfterClass  | @AfterAll

Signed-off-by: Joakim Erdfelt <joakim.erdfelt@gmail.com>
Signed-off-by: olivier lamy <oliver.lamy@gmail.com>
This commit is contained in:
Joakim Erdfelt 2018-09-04 19:07:17 -05:00 committed by olivier lamy
parent 8dd05ac3f7
commit e24fc48539
785 changed files with 38504 additions and 20579 deletions

4
Jenkinsfile vendored
View File

@ -2,7 +2,7 @@
// in case of change update method isMainBuild
def jdks = ["jdk8","jdk9","jdk10","jdk11"]
def oss = ["linux"]
def oss = ["linux"]
def builds = [:]
for (def os in oss) {
for (def jdk in jdks) {
@ -18,7 +18,7 @@ def getFullBuild(jdk, os) {
node(os) {
// System Dependent Locations
def mvnName = 'maven3.5'
def localRepo = "${env.JENKINS_HOME}/${env.EXECUTOR_NUMBER}" // ".repository" //
def localRepo = "${env.JENKINS_HOME}/${env.EXECUTOR_NUMBER}" // ".repository" //
def settingsName = 'oss-settings.xml'
def mavenOpts = '-Xms1g -Xmx4g -Djava.awt.headless=true'

View File

@ -105,6 +105,13 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-http</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-helper</artifactId>

View File

@ -18,7 +18,9 @@
package org.eclipse.jetty.jsp;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import java.io.File;
import java.io.IOException;
@ -31,21 +33,27 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.jasper.runtime.JspFactoryImpl;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.SimpleInstanceManager;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WorkDirExtension.class)
public class TestJettyJspServlet
{
File _dir;
ServletTester _tester;
public WorkDir workdir;
private File _dir;
private ServletTester _tester;
public static class DfltServlet extends HttpServlet
{
@ -67,7 +75,7 @@ public class TestJettyJspServlet
}
@Before
@BeforeEach
public void setUp () throws Exception
{
JspFactory.setDefaultFactory(new JspFactoryImpl());
@ -75,7 +83,7 @@ public class TestJettyJspServlet
_tester = new ServletTester("/context");
_tester.getContext().setClassLoader(new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader()));
ServletHolder jspHolder = _tester.getContext().addServlet(JettyJspServlet.class, "/*");
jspHolder.setInitParameter("scratchdir", MavenTestingUtils.getTargetTestingDir().getAbsolutePath());
jspHolder.setInitParameter("scratchdir", workdir.getPath().toString());
_tester.getContext().setResourceBase(_dir.getAbsolutePath());
_tester.getContext().setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
ServletHolder dfltHolder = new ServletHolder();
@ -86,7 +94,7 @@ public class TestJettyJspServlet
_tester.start();
}
@After
@AfterEach
public void tearDown() throws Exception
{
if (_tester != null)
@ -102,8 +110,10 @@ public class TestJettyJspServlet
"Host: localhost\r\n" +
"Connection: close\r\n" +
"\r\n";
String response = _tester.getResponses(request);
assertTrue(!response.contains("This.Is.The.Default."));
String rawResponse = _tester.getResponses(request);
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat(response.toString(), response.getContent(), not(containsString("This.Is.The.Default.")));
}
@ -116,8 +126,8 @@ public class TestJettyJspServlet
"Host: localhost\r\n" +
"Connection: close\r\n" +
"\r\n";
String response = _tester.getResponses(request);
assertTrue(response.contains("This.Is.The.Default."));
String rawResponse = _tester.getResponses(request);
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat(response.toString(), response.getContent(), containsString("This.Is.The.Default."));
}
}

View File

@ -19,7 +19,7 @@
package org.eclipse.jetty.jsp;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.net.URL;
@ -32,7 +32,7 @@ import org.apache.tomcat.util.descriptor.tld.TldResourcePath;
import org.eclipse.jetty.apache.jsp.JettyTldPreScanned;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* TestJettyTldPreScanned

View File

@ -18,9 +18,11 @@
package org.eclipse.jetty.jsp;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestJspFileNameToClass
{
@ -32,27 +34,27 @@ public class TestJspFileNameToClass
h.setName("test");
Assert.assertEquals(null, h.getClassNameForJsp(null));
assertEquals(null, h.getClassNameForJsp(null));
Assert.assertEquals(null, h.getClassNameForJsp(""));
assertEquals(null, h.getClassNameForJsp(""));
Assert.assertEquals(null, h.getClassNameForJsp("/blah/"));
assertEquals(null, h.getClassNameForJsp("/blah/"));
Assert.assertEquals(null, h.getClassNameForJsp("//blah///"));
assertEquals(null, h.getClassNameForJsp("//blah///"));
Assert.assertEquals(null, h.getClassNameForJsp("/a/b/c/blah/"));
assertEquals(null, h.getClassNameForJsp("/a/b/c/blah/"));
Assert.assertEquals("org.apache.jsp.a.b.c.blah", h.getClassNameForJsp("/a/b/c/blah"));
assertEquals("org.apache.jsp.a.b.c.blah", h.getClassNameForJsp("/a/b/c/blah"));
Assert.assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("/blah.jsp"));
assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("/blah.jsp"));
Assert.assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("//blah.jsp"));
assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("//blah.jsp"));
Assert.assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("blah.jsp"));
assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("blah.jsp"));
Assert.assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("/a/b/c/blah.jsp"));
assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("/a/b/c/blah.jsp"));
Assert.assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("a/b/c/blah.jsp"));
assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("a/b/c/blah.jsp"));
}
}

View File

@ -20,7 +20,7 @@ package org.eclipse.jetty.jstl;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.IOException;
@ -41,16 +41,16 @@ import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.Configurations;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class JspIncludeTest
{
private static Server server;
private static URI baseUri;
@BeforeClass
@BeforeAll
public static void startServer() throws Exception
{
// Setup Server
@ -93,7 +93,7 @@ public class JspIncludeTest
baseUri = new URI(String.format("http://%s:%d/", host, port));
}
@AfterClass
@AfterAll
public static void stopServer() throws Exception
{
server.stop();

View File

@ -21,7 +21,7 @@ package org.eclipse.jetty.jstl;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.IOException;
@ -41,17 +41,16 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class JstlTest
{
private static Server server;
private static URI baseUri;
@BeforeClass
@BeforeAll
public static void startServer() throws Exception
{
// Setup Server
@ -95,7 +94,7 @@ public class JstlTest
baseUri = new URI(String.format("http://%s:%d/",host,port));
}
@AfterClass
@AfterAll
public static void stopServer() throws Exception
{
if (server != null)

View File

@ -65,13 +65,8 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-helper</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.alpn.java.server;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@ -42,8 +45,7 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class JDK9ALPNTest
{
@ -109,7 +111,7 @@ public class JDK9ALPNTest
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
String line = reader.readLine();
Assert.assertTrue(line.contains(" 200 "));
assertThat(line, containsString(" 200 "));
while (true)
{
if (reader.readLine() == null)
@ -154,7 +156,7 @@ public class JDK9ALPNTest
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
String line = reader.readLine();
Assert.assertTrue(line.contains(" 200 "));
assertThat(line, containsString(" 200 "));
while (true)
{
if (reader.readLine() == null)

View File

@ -18,10 +18,10 @@
package org.eclipse.jetty.annotations;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
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;
@ -38,7 +38,7 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.FragmentDescriptor;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* TestAnnotationConfiguration

View File

@ -18,10 +18,14 @@
package org.eclipse.jetty.annotations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasKey;
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.util.ArrayList;
import java.util.Collections;
@ -37,8 +41,8 @@ import org.eclipse.jetty.annotations.AnnotationParser.AbstractHandler;
import org.eclipse.jetty.annotations.AnnotationParser.ClassInfo;
import org.eclipse.jetty.annotations.AnnotationParser.FieldInfo;
import org.eclipse.jetty.annotations.AnnotationParser.MethodInfo;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
/**
*
@ -86,7 +90,7 @@ public class TestAnnotationInheritance
}
}
@After
@AfterEach
public void destroy() throws Exception
{
classNames.clear();
@ -171,17 +175,14 @@ public class TestAnnotationInheritance
assertNotNull(map);
assertFalse(map.isEmpty());
assertEquals(2, map.size());
assertTrue (map.keySet().contains("org.eclipse.jetty.annotations.ClassA"));
assertTrue (map.keySet().contains("org.eclipse.jetty.annotations.InterfaceD"));
assertThat(map, hasKey("org.eclipse.jetty.annotations.ClassA"));
assertThat(map, hasKey("org.eclipse.jetty.annotations.InterfaceD"));
Set<String> classes = map.get("org.eclipse.jetty.annotations.ClassA");
assertEquals(1, classes.size());
assertEquals ("org.eclipse.jetty.annotations.ClassB", classes.iterator().next());
assertThat(classes, contains("org.eclipse.jetty.annotations.ClassB"));
classes = map.get("org.eclipse.jetty.annotations.InterfaceD");
assertEquals(2, classes.size());
assertTrue(classes.contains("org.eclipse.jetty.annotations.ClassB"));
assertTrue(classes.contains(Foo.class.getName()));
assertThat(classes, containsInAnyOrder("org.eclipse.jetty.annotations.ClassB",
Foo.class.getName()));
}
}

View File

@ -18,11 +18,13 @@
package org.eclipse.jetty.annotations;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
@ -46,13 +48,14 @@ import org.eclipse.jetty.annotations.AnnotationParser.MethodInfo;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WorkDirExtension.class)
public class TestAnnotationParser
{
public static class TrackingAnnotationHandler extends AnnotationParser.AbstractHandler
@ -102,8 +105,7 @@ public class TestAnnotationParser
}
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
@Test
public void testSampleAnnotation() throws Exception
@ -140,7 +142,7 @@ public class TestAnnotationParser
if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation))
return;
assertEquals("org.eclipse.jetty.annotations.ClassA",info.getClassInfo().getClassName());
assertTrue(methods.contains(info.getMethodName()));
assertThat(info.getMethodName(), isIn(methods));
assertEquals("org.eclipse.jetty.annotations.Sample",annotation);
}
}
@ -171,11 +173,9 @@ public class TestAnnotationParser
@Override
public void handle(FieldInfo info, String annotation)
{
if (annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation))
return;
// there should not be any
fail();
{
assertTrue(annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation),
"There should not be any");
}
@Override
@ -256,7 +256,7 @@ public class TestAnnotationParser
parser.parse(Collections.singleton(tracker), basedir.toURI());
// Validate
Assert.assertThat("Found Class", tracker.foundClasses, contains(ClassA.class.getName()));
assertThat("Found Class", tracker.foundClasses, contains(ClassA.class.getName()));
}
@ -271,9 +271,9 @@ public class TestAnnotationParser
parser.parse(handlers, testJar);
parser.parse(handlers, testJar2);
List<String> locations = handler.getParsedList("org.acme.ClassOne");
Assert.assertNotNull(locations);
Assert.assertEquals(2, locations.size());
Assert.assertTrue(!(locations.get(0).equals(locations.get(1))));
assertNotNull(locations);
assertEquals(2, locations.size());
assertTrue(!(locations.get(0).equals(locations.get(1))));
}
@ -288,9 +288,9 @@ public class TestAnnotationParser
parser.parse(handlers, testJar);
parser.parse(handlers, Resource.newResource(testClasses));
List<String>locations = handler.getParsedList("org.acme.ClassOne");
Assert.assertNotNull(locations);
Assert.assertEquals(2, locations.size());
Assert.assertTrue(!(locations.get(0).equals(locations.get(1))));
assertNotNull(locations);
assertEquals(2, locations.size());
assertTrue(!(locations.get(0).equals(locations.get(1))));
}
@ -299,7 +299,7 @@ public class TestAnnotationParser
{
String classname = clazz.getName().replace('.',File.separatorChar) + ".class";
URL url = this.getClass().getResource('/'+classname);
Assert.assertThat("URL for: " + classname,url,notNullValue());
assertThat("URL for: " + classname,url,notNullValue());
String classpath = classname.substring(0,classname.lastIndexOf(File.separatorChar));
FS.ensureDirExists(new File(basedir,classpath));

View File

@ -18,11 +18,11 @@
package org.eclipse.jetty.annotations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
import java.util.List;
@ -41,7 +41,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestSecurityAnnotationConversions
{

View File

@ -18,6 +18,15 @@
package org.eclipse.jetty.annotations;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -29,14 +38,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
import org.eclipse.jetty.webapp.DiscoveredAnnotation;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.jupiter.api.Test;
/**
* TestServletAnnotations
@ -132,7 +134,7 @@ public class TestServletAnnotations
resultMappings[0].getServletName().equals("DServlet");
for (String s:resultMappings[0].getPathSpecs())
{
assertTrue (s.equals("/") || s.equals("/bah/*"));
assertThat(s, anyOf(is("/"), is("/bah/*")));
}
}
@ -185,7 +187,7 @@ public class TestServletAnnotations
}
}
else
fail("Unexpected servlet mapping");
fail("Unexpected servlet mapping: " + r);
}
}
@ -222,7 +224,7 @@ public class TestServletAnnotations
assertEquals(1, r.getPathSpecs().length);
}
else
fail("Unexpected servlet name");
fail("Unexpected servlet name: " + r);
}
}
@ -258,7 +260,7 @@ public class TestServletAnnotations
{
assertEquals(1, r.getPathSpecs().length);
if (!r.getPathSpecs()[0].equals("/default") && !r.getPathSpecs()[0].equals("/other"))
fail("Unexpected path in mapping");
fail("Unexpected path in mapping: " + r);
}
}
@ -282,8 +284,7 @@ public class TestServletAnnotations
assertEquals(2, resultMappings[0].getPathSpecs().length);
for (String s:resultMappings[0].getPathSpecs())
{
if (!s.equals("/") && !s.equals("/bah/*"))
fail("Unexpected path mapping");
assertThat(s, anyOf(is("/"), is("/bah/*")));
}
}
@ -299,8 +300,6 @@ public class TestServletAnnotations
sh.setRoles(new HashSet<String>(Arrays.asList(new String[]{"humpty", "dumpty"})));
DeclareRolesAnnotationHandler handler = new DeclareRolesAnnotationHandler(wac);
handler.doHandle(ServletC.class);
assertTrue(sh.getRoles().contains("alice"));
assertTrue(sh.getRoles().contains("humpty"));
assertTrue(sh.getRoles().contains("dumpty"));
assertThat(sh.getRoles(), containsInAnyOrder("humpty", "alice", "dumpty"));
}
}

View File

@ -18,8 +18,8 @@
package org.eclipse.jetty.annotations.resources;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.lang.reflect.Field;
import java.util.List;
@ -34,9 +34,9 @@ import org.eclipse.jetty.plus.annotation.Injection;
import org.eclipse.jetty.plus.annotation.InjectionCollection;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestResourceAnnotations
{
@ -48,7 +48,7 @@ public class TestResourceAnnotations
private Object objA = 1000;
private Object objB = 2000;
@Before
@BeforeEach
public void init() throws Exception
{
server = new Server();
@ -61,7 +61,7 @@ public class TestResourceAnnotations
env = comp.createSubcontext("env");
}
@After
@AfterEach
public void destroy() throws Exception
{
comp.destroySubcontext("env");

View File

@ -19,13 +19,13 @@
package org.eclipse.jetty.ant;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import java.net.HttpURLConnection;
import java.net.URI;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class JettyAntTaskTest
{

View File

@ -151,7 +151,6 @@
<artifactId>jetty-ant</artifactId>
<version>10.0.0-SNAPSHOT</version>
</dependency>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
@ -390,6 +389,7 @@
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-common</artifactId>
<version>10.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-server</artifactId>
@ -488,4 +488,4 @@
</build>
</profile>
</profiles>
</project>
</project>

View File

@ -0,0 +1,78 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.core;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
public abstract class AbstractWeldTest
{
public static class TestBean<T>
{
public Bean<T> bean;
public CreationalContext<T> cCtx;
public T instance;
public void destroy()
{
bean.destroy(instance,cCtx);
}
}
@BeforeAll
public static void initWeld()
{
weld = new Weld();
container = weld.initialize();
}
@AfterAll
public static void shutdownWeld()
{
weld.shutdown();
}
private static WeldContainer container;
private static Weld weld;
@SuppressWarnings("unchecked")
public <T> TestBean<T> newInstance(Class<T> clazz) throws Exception
{
TestBean<T> testBean = new TestBean<>();
Set<Bean<?>> beans = container.getBeanManager().getBeans(clazz,AnyLiteral.INSTANCE);
if (beans.size() > 0)
{
testBean.bean = (Bean<T>)beans.iterator().next();
testBean.cCtx = container.getBeanManager().createCreationalContext(testBean.bean);
testBean.instance = (T)container.getBeanManager().getReference(testBean.bean,clazz,testBean.cCtx);
return testBean;
}
else
{
throw new Exception(String.format("Can't find class %s",clazz));
}
}
}

View File

@ -0,0 +1,121 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.servlet;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.JettyLogHandler;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class WeldInitializationTest
{
private static final Logger LOG = Log.getLogger(WeldInitializationTest.class);
private static Server server;
private static URI serverHttpURI;
@BeforeAll
public static void startServer() throws Exception
{
JettyLogHandler.config();
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.addConnector(connector);
EmbeddedCdiHandler context = new EmbeddedCdiHandler(ServletContextHandler.SESSIONS);
File baseDir = MavenTestingUtils.getTestResourcesDir();
context.setBaseResource(Resource.newResource(baseDir));
context.setContextPath("/");
server.setHandler(context);
// Add some servlets
context.addServlet(TimeServlet.class,"/time");
context.addServlet(RequestInfoServlet.class,"/req-info");
server.start();
String host = connector.getHost();
if (host == null)
{
host = "localhost";
}
int port = connector.getLocalPort();
serverHttpURI = new URI(String.format("http://%s:%d/",host,port));
}
@AfterAll
public static void stopServer()
{
try
{
server.stop();
}
catch (Exception e)
{
LOG.warn(e);
}
}
@Test
public void testRequestParamServletDefault() throws Exception
{
HttpURLConnection http = (HttpURLConnection) serverHttpURI.resolve("req-info").toURL().openConnection();
assertThat("response code", http.getResponseCode(), is(200));
try(InputStream inputStream = http.getInputStream())
{
String resp = IO.toString(inputStream);
assertThat("Response", resp, containsString("request is PRESENT"));
assertThat("Response", resp, containsString("parameters.size = [0]"));
}
}
@Test
public void testRequestParamServletAbc() throws Exception
{
HttpURLConnection http = (HttpURLConnection) serverHttpURI.resolve("req-info?abc=123").toURL().openConnection();
assertThat("response code", http.getResponseCode(), is(200));
try(InputStream inputStream = http.getInputStream())
{
String resp = IO.toString(inputStream);
assertThat("Response", resp, containsString("request is PRESENT"));
assertThat("Response", resp, containsString("parameters.size = [1]"));
assertThat("Response", resp, containsString(" param[abc] = [123]"));
}
}
}

View File

@ -0,0 +1,99 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.websocket;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket
public class CheckSocket extends WebSocketAdapter
{
private static final Logger LOG = Log.getLogger(CheckSocket.class);
private CountDownLatch closeLatch = new CountDownLatch(1);
private CountDownLatch openLatch = new CountDownLatch(1);
public LinkedBlockingQueue<String> textMessages = new LinkedBlockingQueue<>();
public void awaitClose(int timeout, TimeUnit timeunit) throws InterruptedException
{
assertTrue(closeLatch.await(timeout,timeunit), "Timeout waiting for close");
}
public void awaitOpen(int timeout, TimeUnit timeunit) throws InterruptedException
{
assertTrue(openLatch.await(timeout,timeunit), "Timeout waiting for open");
}
public LinkedBlockingQueue<String> getTextMessages()
{
return textMessages;
}
@Override
public void onWebSocketClose(int statusCode, String reason)
{
LOG.debug("Close: {}, {}",statusCode,reason);
super.onWebSocketClose(statusCode,reason);
closeLatch.countDown();
}
@Override
public void onWebSocketConnect(Session sess)
{
LOG.debug("Open: {}",sess);
super.onWebSocketConnect(sess);
openLatch.countDown();
}
@Override
public void onWebSocketError(Throwable cause)
{
LOG.warn("WebSocket Error",cause);
super.onWebSocketError(cause);
}
@Override
public void onWebSocketText(String message)
{
LOG.debug("TEXT: {}",message);
textMessages.add(message);
}
public void sendText(String msg) throws IOException
{
if (isConnected())
{
getRemote().sendString(msg);
}
}
public void close(int statusCode, String reason)
{
getSession().close(statusCode,reason);
}
}

View File

@ -0,0 +1,130 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.websocket.basicapp;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import javax.websocket.server.ServerContainer;
import org.eclipse.jetty.cdi.servlet.EmbeddedCdiHandler;
import org.eclipse.jetty.cdi.websocket.CheckSocket;
import org.eclipse.jetty.cdi.websocket.cdiapp.InfoSocket;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.log.JettyLogHandler;
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.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class BasicAppTest
{
private static final Logger LOG = Log.getLogger(BasicAppTest.class);
private static Server server;
@SuppressWarnings("unused")
private static URI serverHttpURI;
private static URI serverWebsocketURI;
@BeforeAll
public static void startServer() throws Exception
{
JettyLogHandler.config();
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.addConnector(connector);
EmbeddedCdiHandler context = new EmbeddedCdiHandler();
File baseDir = MavenTestingUtils.getTestResourcesDir();
context.setBaseResource(Resource.newResource(baseDir));
context.setContextPath("/");
server.setHandler(context);
// Add some websockets
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
container.addEndpoint(EchoSocket.class);
container.addEndpoint(InfoSocket.class);
server.start();
String host = connector.getHost();
if (host == null)
{
host = "localhost";
}
int port = connector.getLocalPort();
serverHttpURI = new URI(String.format("http://%s:%d/",host,port));
serverWebsocketURI = new URI(String.format("ws://%s:%d/",host,port));
}
@AfterAll
public static void stopServer()
{
try
{
server.stop();
}
catch (Exception e)
{
LOG.warn(e);
}
}
@Test
public void testWebSocketEcho() throws Exception
{
WebSocketClient client = new WebSocketClient();
try
{
client.start();
CheckSocket socket = new CheckSocket();
client.connect(socket,serverWebsocketURI.resolve("/echo"));
socket.awaitOpen(2,TimeUnit.SECONDS);
socket.sendText("Hello World");
socket.close(StatusCode.NORMAL,"Test complete");
socket.awaitClose(2,TimeUnit.SECONDS);
assertThat("Messages received",socket.getTextMessages().size(),is(1));
String response = socket.getTextMessages().poll();
System.err.println(response);
assertThat("Message[0]",response,is("Hello World"));
}
finally
{
client.stop();
}
}
}

View File

@ -0,0 +1,97 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.websocket.basicscope;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Set;
import javax.enterprise.inject.spi.Bean;
import org.eclipse.jetty.cdi.core.AnyLiteral;
import org.eclipse.jetty.cdi.core.ScopedInstance;
import org.eclipse.jetty.cdi.core.logging.Logging;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class ScopeBasicsTest
{
private static Weld weld;
private static WeldContainer container;
@BeforeAll
public static void startWeld()
{
Logging.config();
weld = new Weld();
container = weld.initialize();
}
@AfterAll
public static void stopWeld()
{
weld.shutdown();
}
/**
* Validation of Scope / Inject logic on non-websocket-scoped classes
* @throws Exception on test failure
*/
@Test
public void testBasicBehavior() throws Exception
{
ScopedInstance<Meal> meal1Bean = newInstance(Meal.class);
Meal meal1 = meal1Bean.instance;
ScopedInstance<Meal> meal2Bean = newInstance(Meal.class);
Meal meal2 = meal2Bean.instance;
assertThat("Meals are not the same",meal1,not(sameInstance(meal2)));
assertThat("Meal 1 Entree Constructed",meal1.getEntree().isConstructed(),is(true));
assertThat("Meal 1 Side Constructed",meal1.getSide().isConstructed(),is(true));
assertThat("Meal parts not the same",meal1.getEntree(),not(sameInstance(meal1.getSide())));
assertThat("Meal entrees are the same",meal1.getEntree(),not(sameInstance(meal2.getEntree())));
assertThat("Meal sides are the same",meal1.getSide(),not(sameInstance(meal2.getSide())));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> ScopedInstance<T> newInstance(Class<T> clazz) throws Exception
{
ScopedInstance sbean = new ScopedInstance();
Set<Bean<?>> beans = container.getBeanManager().getBeans(clazz,AnyLiteral.INSTANCE);
if (beans.size() > 0)
{
sbean.bean = beans.iterator().next();
sbean.creationalContext = container.getBeanManager().createCreationalContext(sbean.bean);
sbean.instance = container.getBeanManager().getReference(sbean.bean,clazz,sbean.creationalContext);
return sbean;
}
else
{
throw new Exception(String.format("Can't find class %s",clazz));
}
}
}

View File

@ -0,0 +1,185 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.websocket.cdiapp;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import javax.websocket.server.ServerContainer;
import org.eclipse.jetty.cdi.servlet.EmbeddedCdiHandler;
import org.eclipse.jetty.cdi.websocket.CheckSocket;
import org.eclipse.jetty.cdi.websocket.WebSocketCdiInitializer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.log.JettyLogHandler;
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.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CdiAppTest
{
private static final Logger LOG = Log.getLogger(CdiAppTest.class);
private static Server server;
private static URI serverWebsocketURI;
@BeforeAll
public static void startServer() throws Exception
{
JettyLogHandler.config();
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.addConnector(connector);
EmbeddedCdiHandler context = new EmbeddedCdiHandler();
WebSocketCdiInitializer.configureContext(context);
File baseDir = MavenTestingUtils.getTestResourcesDir();
context.setBaseResource(Resource.newResource(baseDir));
context.setContextPath("/");
server.setHandler(context);
// Add some websockets
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
container.addEndpoint(EchoSocket.class);
container.addEndpoint(InfoSocket.class);
server.start();
String host = connector.getHost();
if (host == null)
{
host = "localhost";
}
int port = connector.getLocalPort();
serverWebsocketURI = new URI(String.format("ws://%s:%d/",host,port));
}
@AfterAll
public static void stopServer()
{
try
{
server.stop();
}
catch (Exception e)
{
LOG.warn(e);
}
}
@Test
public void testWebSocketActivated() throws Exception
{
WebSocketClient client = new WebSocketClient();
try
{
client.start();
CheckSocket socket = new CheckSocket();
client.connect(socket,serverWebsocketURI.resolve("/echo"));
socket.awaitOpen(2,TimeUnit.SECONDS);
socket.sendText("Hello");
socket.close(StatusCode.NORMAL,"Test complete");
socket.awaitClose(2,TimeUnit.SECONDS);
assertThat("Messages received",socket.getTextMessages().size(),is(1));
assertThat("Message[0]",socket.getTextMessages().poll(),is("Hello"));
}
finally
{
client.stop();
}
}
@Test
public void testWebSocket_Info_FieldPresence() throws Exception
{
WebSocketClient client = new WebSocketClient();
try
{
client.start();
CheckSocket socket = new CheckSocket();
client.connect(socket,serverWebsocketURI.resolve("/cdi-info"));
socket.awaitOpen(2,TimeUnit.SECONDS);
socket.sendText("info");
socket.close(StatusCode.NORMAL,"Test complete");
socket.awaitClose(2,TimeUnit.SECONDS);
assertThat("Messages received",socket.getTextMessages().size(),is(1));
String response = socket.getTextMessages().poll();
System.err.println(response);
assertThat("Message[0]",response,
allOf(
containsString("websocketSession is PRESENT"),
containsString("httpSession is PRESENT"),
containsString("servletContext is PRESENT")
));
}
finally
{
client.stop();
}
}
@Test
public void testWebSocket_Info_DataFromCdi() throws Exception
{
WebSocketClient client = new WebSocketClient();
try
{
client.start();
CheckSocket socket = new CheckSocket();
client.connect(socket,serverWebsocketURI.resolve("/cdi-info"));
socket.awaitOpen(2,TimeUnit.SECONDS);
socket.sendText("data|stuff");
socket.close(StatusCode.NORMAL,"Test complete");
socket.awaitClose(2,TimeUnit.SECONDS);
assertThat("Messages received",socket.getTextMessages().size(),is(2));
String response = socket.getTextMessages().poll();
System.out.println("[0]" + response);
assertThat("Message[0]",response,containsString("Hello there stuff"));
System.out.println("[1]" + socket.getTextMessages().poll());
}
finally
{
client.stop();
}
}
}

View File

@ -0,0 +1,131 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.websocket.wsscope;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Set;
import javax.enterprise.inject.spi.Bean;
import org.eclipse.jetty.cdi.core.AnyLiteral;
import org.eclipse.jetty.cdi.core.ScopedInstance;
import org.eclipse.jetty.cdi.core.logging.Logging;
import org.eclipse.jetty.cdi.websocket.WebSocketScopeContext;
import org.eclipse.jetty.cdi.websocket.annotation.WebSocketScope;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class WebSocketScopeBaselineTest
{
private static Weld weld;
private static WeldContainer container;
@BeforeAll
public static void startWeld()
{
Logging.config();
weld = new Weld();
container = weld.initialize();
}
@AfterAll
public static void stopWeld()
{
weld.shutdown();
}
/**
* Test behavior of {@link WebSocketScope} in basic operation.
* <p>
* Food is declared as part of WebSocketScope, and as such, only 1 instance of it can exist.
* @throws Exception on test failure
*/
@Test
public void testScopeBehavior() throws Exception
{
ScopedInstance<WebSocketScopeContext> wsScopeBean = newInstance(WebSocketScopeContext.class);
WebSocketScopeContext wsScope = wsScopeBean.instance;
wsScope.create();
Meal meal1;
try
{
wsScope.begin();
ScopedInstance<Meal> meal1Bean = newInstance(Meal.class);
meal1 = meal1Bean.instance;
ScopedInstance<Meal> meal2Bean = newInstance(Meal.class);
Meal meal2 = meal2Bean.instance;
assertThat("Meals are not the same",meal1,not(sameInstance(meal2)));
assertThat("Meal 1 Entree Constructed",meal1.getEntree().isConstructed(),is(true));
assertThat("Meal 1 Side Constructed",meal1.getSide().isConstructed(),is(true));
/* Since Food is annotated with @WebSocketScope, there can only be one instance of it
* in use with the 2 Meal objects.
*/
assertThat("Meal parts not the same",meal1.getEntree(),sameInstance(meal1.getSide()));
assertThat("Meal entrees are the same",meal1.getEntree(),sameInstance(meal2.getEntree()));
assertThat("Meal sides are the same",meal1.getSide(),sameInstance(meal2.getSide()));
meal1Bean.destroy();
meal2Bean.destroy();
}
finally
{
wsScope.end();
}
Food entree1 = meal1.getEntree();
Food side1 = meal1.getSide();
assertThat("Meal 1 entree destroyed",entree1.isDestroyed(),is(false));
assertThat("Meal 1 side destroyed",side1.isDestroyed(),is(false));
wsScope.destroy();
// assertThat("Meal 1 entree destroyed",entree1.isDestroyed(),is(true));
// assertThat("Meal 1 side destroyed",side1.isDestroyed(),is(true));
wsScopeBean.destroy();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> ScopedInstance<T> newInstance(Class<T> clazz) throws Exception
{
ScopedInstance sbean = new ScopedInstance();
Set<Bean<?>> beans = container.getBeanManager().getBeans(clazz,AnyLiteral.INSTANCE);
if (beans.size() > 0)
{
sbean.bean = beans.iterator().next();
sbean.creationalContext = container.getBeanManager().createCreationalContext(sbean.bean);
sbean.instance = container.getBeanManager().getReference(sbean.bean,clazz,sbean.creationalContext);
return sbean;
}
else
{
throw new Exception(String.format("Can't find class %s",clazz));
}
}
}

View File

@ -0,0 +1,253 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.cdi.websocket.wsscope;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.enterprise.inject.spi.Bean;
import org.eclipse.jetty.cdi.core.AnyLiteral;
import org.eclipse.jetty.cdi.core.ScopedInstance;
import org.eclipse.jetty.cdi.core.logging.Logging;
import org.eclipse.jetty.cdi.websocket.WebSocketScopeContext;
import org.eclipse.jetty.websocket.api.Session;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class WebSocketScopeSessionTest
{
private static Weld weld;
private static WeldContainer container;
@BeforeAll
public static void startWeld()
{
Logging.config();
weld = new Weld();
container = weld.initialize();
}
@AfterAll
public static void stopWeld()
{
weld.shutdown();
}
@Test
public void testSessionActivation() throws Exception
{
ScopedInstance<WebSocketScopeContext> wsScopeBean = newInstance(WebSocketScopeContext.class);
WebSocketScopeContext wsScope = wsScopeBean.instance;
wsScope.create();
try
{
// Scope 1
wsScope.begin();
BogusSession sess = new BogusSession("1");
wsScope.setSession(sess);
ScopedInstance<BogusSocket> sock1Bean = newInstance(BogusSocket.class);
BogusSocket sock1 = sock1Bean.instance;
assertThat("Socket 1 Session",sock1.getSession().toString(),is(sess.toString()));
sock1Bean.destroy();
}
finally
{
wsScope.end();
}
wsScope.destroy();
wsScopeBean.destroy();
}
@Test
public void testMultiSession_Sequential() throws Exception
{
ScopedInstance<WebSocketScopeContext> wsScope1Bean = newInstance(WebSocketScopeContext.class);
WebSocketScopeContext wsScope1 = wsScope1Bean.instance;
ScopedInstance<WebSocketScopeContext> wsScope2Bean = newInstance(WebSocketScopeContext.class);
WebSocketScopeContext wsScope2 = wsScope2Bean.instance;
wsScope1.create();
try
{
// Scope 1
wsScope1.begin();
BogusSession sess = new BogusSession("1");
wsScope1.setSession(sess);
ScopedInstance<BogusSocket> sock1Bean = newInstance(BogusSocket.class);
BogusSocket sock1 = sock1Bean.instance;
assertThat("Socket 1 Session",sock1.getSession(),sameInstance((Session)sess));
sock1Bean.destroy();
}
finally
{
wsScope1.end();
}
wsScope1.destroy();
wsScope1Bean.destroy();
wsScope2.create();
try
{
// Scope 2
wsScope2.begin();
BogusSession sess = new BogusSession("2");
wsScope2.setSession(sess);
ScopedInstance<BogusSocket> sock2Bean = newInstance(BogusSocket.class);
BogusSocket sock2 = sock2Bean.instance;
assertThat("Socket 2 Session",sock2.getSession(),sameInstance((Session)sess));
sock2Bean.destroy();
}
finally
{
wsScope2.end();
}
wsScope2.destroy();
wsScope2Bean.destroy();
}
@Test
public void testMultiSession_Overlapping() throws Exception
{
final CountDownLatch midLatch = new CountDownLatch(2);
final CountDownLatch end1Latch = new CountDownLatch(1);
Callable<Session> call1 = new Callable<Session>() {
@Override
public Session call() throws Exception
{
Session ret = null;
ScopedInstance<WebSocketScopeContext> wsScope1Bean = newInstance(WebSocketScopeContext.class);
WebSocketScopeContext wsScope1 = wsScope1Bean.instance;
wsScope1.create();
try
{
// Scope 1
wsScope1.begin();
BogusSession sess = new BogusSession("1");
wsScope1.setSession(sess);
midLatch.countDown();
midLatch.await(1, TimeUnit.SECONDS);
ScopedInstance<BogusSocket> sock1Bean = newInstance(BogusSocket.class);
BogusSocket sock1 = sock1Bean.instance;
assertThat("Socket 1 Session",sock1.getSession(),sameInstance((Session)sess));
ret = sock1.getSession();
sock1Bean.destroy();
}
finally
{
wsScope1.end();
}
wsScope1.destroy();
wsScope1Bean.destroy();
end1Latch.countDown();
return ret;
}
};
final CountDownLatch end2Latch = new CountDownLatch(1);
Callable<Session> call2 = new Callable<Session>() {
@Override
public Session call() throws Exception
{
Session ret = null;
ScopedInstance<WebSocketScopeContext> wsScope2Bean = newInstance(WebSocketScopeContext.class);
WebSocketScopeContext wsScope2 = wsScope2Bean.instance;
wsScope2.create();
try
{
// Scope 2
wsScope2.begin();
BogusSession sess = new BogusSession("2");
wsScope2.setSession(sess);
ScopedInstance<BogusSocket> sock2Bean = newInstance(BogusSocket.class);
midLatch.countDown();
midLatch.await(1, TimeUnit.SECONDS);
BogusSocket sock2 = sock2Bean.instance;
ret = sock2.getSession();
assertThat("Socket 2 Session",sock2.getSession(),sameInstance((Session)sess));
sock2Bean.destroy();
}
finally
{
wsScope2.end();
}
wsScope2.destroy();
wsScope2Bean.destroy();
end2Latch.countDown();
return ret;
}
};
ExecutorService svc = Executors.newFixedThreadPool(4);
Future<Session> fut1 = svc.submit(call1);
Future<Session> fut2 = svc.submit(call2);
Session sess1 = fut1.get(1,TimeUnit.SECONDS);
Session sess2 = fut2.get(1,TimeUnit.SECONDS);
assertThat("Sessions are different", sess1, not(sameInstance(sess2)));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> ScopedInstance<T> newInstance(Class<T> clazz)
{
ScopedInstance sbean = new ScopedInstance();
Set<Bean<?>> beans = container.getBeanManager().getBeans(clazz,AnyLiteral.INSTANCE);
if (beans.size() > 0)
{
sbean.bean = beans.iterator().next();
sbean.creationalContext = container.getBeanManager().createCreationalContext(sbean.bean);
sbean.instance = container.getBeanManager().getReference(sbean.bean,clazz,sbean.creationalContext);
return sbean;
}
else
{
throw new RuntimeException(String.format("Can't find class %s",clazz));
}
}
}

View File

@ -0,0 +1,47 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.tests;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import java.net.URI;
import org.eclipse.jetty.toolchain.test.SimpleRequest;
import org.junit.jupiter.api.Test;
public class ServerInfoIT
{
@Test
public void testGET() throws Exception {
URI serverURI = new URI("http://localhost:58080/cdi-webapp/");
SimpleRequest req = new SimpleRequest(serverURI);
// Typical response:
// context = ServletContext@o.e.j.w.WebAppContext@37cb63fd{/cdi-webapp,
// file:///tmp/jetty-0.0.0.0-58080-cdi-webapp.war-_cdi-webapp-any-417759194514596377.dir/webapp/,AVAILABLE}
// {/cdi-webapp.war}\ncontext.contextPath = /cdi-webapp\ncontext.effective-version = 3.1\n
assertThat(req.getString("serverinfo"),
allOf(
containsString("context = ServletContext@"),
containsString("context.contextPath = /cdi-webapp"),
containsString("context.effective-version = 3.1")
));
}
}

View File

@ -0,0 +1,106 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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.tests.ws;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.eclipse.jetty.toolchain.test.EventQueue;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.jupiter.api.Test;
public class SessionInfoIT
{
@ClientEndpoint
public static class ClientSessionInfoSocket
{
private static final Logger LOG = Log.getLogger(SessionInfoIT.ClientSessionInfoSocket.class);
public CountDownLatch openLatch = new CountDownLatch(1);
public CountDownLatch closeLatch = new CountDownLatch(1);
public Session session;
public EventQueue<String> messages = new EventQueue<>();
public CloseReason closeReason;
@OnOpen
public void onOpen(Session session)
{
LOG.info("onOpen(): {}", session);
this.session = session;
this.openLatch.countDown();
}
@OnClose
public void onClose(CloseReason close)
{
LOG.info("onClose(): {}", close);
this.session = null;
this.closeReason = close;
this.closeLatch.countDown();
}
@OnMessage
public void onMessage(String message)
{
LOG.info("onMessage(): {}", message);
this.messages.offer(message);
}
}
@Test
public void testSessionInfo() throws Exception
{
URI serverURI = new URI("ws://localhost:58080/cdi-webapp/");
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
ClientSessionInfoSocket socket = new ClientSessionInfoSocket();
container.connectToServer(socket,serverURI.resolve("sessioninfo"));
assertThat("Await open", socket.openLatch.await(1,TimeUnit.SECONDS), is(true));
socket.session.getBasicRemote().sendText("info");
socket.messages.awaitEventCount(1,2,TimeUnit.SECONDS);
System.out.printf("socket.messages.size = %s%n",socket.messages.size());
String msg = socket.messages.poll();
System.out.printf("Message is [%s]%n",msg);
assertThat("Message", msg, containsString("HttpSession = HttpSession"));
socket.session.getBasicRemote().sendText("close");
assertThat("Await close", socket.closeLatch.await(1,TimeUnit.SECONDS),is(true));
}
}

View File

@ -37,7 +37,7 @@
<artifactItem>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-policy</artifactId>
<version>${jetty-test-policy-version}</version>
<version>${jetty-test-policy.version}</version>
<type>jar</type>
<overWrite>true</overWrite>
<includes>**/*.keystore,**/*.pem</includes>

View File

@ -18,96 +18,153 @@
package org.eclipse.jetty.client;
import java.util.Arrays;
import java.util.Collection;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.SocketAddressResolver;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
@RunWith(Parameterized.class)
public abstract class AbstractHttpClientServerTest
{
@Parameterized.Parameters(name = "ssl={0}")
public static Collection<SslContextFactory[]> parameters()
{
return Arrays.asList(new SslContextFactory[]{null}, new SslContextFactory[]{new SslContextFactory()});
}
@Rule
public final TestTracker tracker = new TestTracker();
protected SslContextFactory sslContextFactory;
protected String scheme;
protected Server server;
protected HttpClient client;
protected ServerConnector connector;
public AbstractHttpClientServerTest(SslContextFactory sslContextFactory)
public void start(final Scenario scenario, Handler handler) throws Exception
{
this.sslContextFactory = sslContextFactory;
this.scheme = (sslContextFactory == null ? HttpScheme.HTTP : HttpScheme.HTTPS).asString();
startServer(scenario, handler);
startClient(scenario);
}
public void start(Handler handler) throws Exception
protected void startServer(final Scenario scenario, Handler handler) throws Exception
{
startServer(handler);
startClient();
}
protected void startServer(Handler handler) throws Exception
{
if (sslContextFactory != null)
{
sslContextFactory.setEndpointIdentificationAlgorithm("");
sslContextFactory.setKeyStorePath("src/test/resources/keystore.jks");
sslContextFactory.setKeyStorePassword("storepwd");
}
if (server == null)
{
QueuedThreadPool serverThreads = new QueuedThreadPool();
serverThreads.setName("server");
server = new Server(serverThreads);
}
connector = new ServerConnector(server, sslContextFactory);
connector = new ServerConnector(server, scenario.newSslContextFactory());
connector.setPort(0);
server.addConnector(connector);
server.setHandler(handler);
server.start();
}
protected void startClient() throws Exception
protected void startClient(final Scenario scenario) throws Exception
{
startClient(new HttpClientTransportOverHTTP(1));
startClient(scenario, new HttpClientTransportOverHTTP(1));
}
protected void startClient(HttpClientTransport transport) throws Exception
protected void startClient(final Scenario scenario, HttpClientTransport transport) throws Exception
{
QueuedThreadPool clientThreads = new QueuedThreadPool();
clientThreads.setName("client");
client = new HttpClient(transport, sslContextFactory);
client = new HttpClient(transport, scenario.newSslContextFactory());
client.setExecutor(clientThreads);
client.setSocketAddressResolver(new SocketAddressResolver.Sync());
client.start();
}
@After
public void dispose() throws Exception
@AfterEach
public void disposeClient() throws Exception
{
if (client != null)
{
client.stop();
client = null;
}
}
@AfterEach
public void disposeServer() throws Exception
{
if (server != null)
{
server.stop();
server = null;
server = null;
}
}
public static class ScenarioProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception
{
return Stream.of(
new NormalScenario(),
new SslScenario()
// TODO: add more ssl / non-ssl scenarios here
).map(Arguments::of);
}
}
public static class NonSslScenarioProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception
{
return Stream.of(
new NormalScenario()
// TODO: add more non-ssl scenarios here
).map(Arguments::of);
}
}
public interface Scenario
{
default SslContextFactory newSslContextFactory() { return null; }
String getScheme();
}
public static class NormalScenario implements Scenario
{
@Override
public String getScheme()
{
return HttpScheme.HTTP.asString();
}
@Override
public String toString()
{
return "HTTP";
}
}
public static class SslScenario implements Scenario
{
@Override
public SslContextFactory newSslContextFactory()
{
Path keystorePath = MavenTestingUtils.getTestResourcePath("keystore.jks");
SslContextFactory ssl = new SslContextFactory();
ssl.setEndpointIdentificationAlgorithm("");
ssl.setKeyStorePath(keystorePath.toString());
ssl.setKeyStorePassword("storepwd");
return ssl;
}
@Override
public String getScheme()
{
return HttpScheme.HTTPS.asString();
}
@Override
public String toString()
{
return "HTTPS";
}
}
}

View File

@ -18,6 +18,11 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
@ -39,22 +44,17 @@ import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
{
public ClientConnectionCloseTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Test
public void test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange(Scenario scenario) throws Exception
{
byte[] data = new byte[128 * 1024];
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -87,29 +87,30 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString())
.content(new StringContentProvider("0"))
.onRequestSuccess(request ->
{
HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next();
Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
assertFalse(connection.getEndPoint().isOutputShutdown());
})
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
Assert.assertEquals(0, connectionPool.getConnectionCount());
assertEquals(HttpStatus.OK_200, response.getStatus());
assertArrayEquals(data, response.getContent());
assertEquals(0, connectionPool.getConnectionCount());
}
@Test
public void test_ClientConnectionClose_ServerDoesNotRespond_ClientIdleTimeout() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_ClientConnectionClose_ServerDoesNotRespond_ClientIdleTimeout(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -123,19 +124,19 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
CountDownLatch resultLatch = new CountDownLatch(1);
long idleTimeout = 1000;
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString())
.idleTimeout(idleTimeout, TimeUnit.MILLISECONDS)
.onRequestSuccess(request ->
{
HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next();
Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
assertFalse(connection.getEndPoint().isOutputShutdown());
})
.send(result ->
{
@ -143,15 +144,16 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
resultLatch.countDown();
});
Assert.assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
Assert.assertEquals(0, connectionPool.getConnectionCount());
assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
assertEquals(0, connectionPool.getConnectionCount());
}
@Test
public void test_ClientConnectionClose_ServerPartialResponse_ClientIdleTimeout() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_ClientConnectionClose_ServerPartialResponse_ClientIdleTimeout(Scenario scenario) throws Exception
{
long idleTimeout = 1000;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -183,20 +185,20 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.allocate(8));
CountDownLatch resultLatch = new CountDownLatch(1);
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString())
.content(content)
.idleTimeout(idleTimeout, TimeUnit.MILLISECONDS)
.onRequestSuccess(request ->
{
HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next();
Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
assertFalse(connection.getEndPoint().isOutputShutdown());
})
.send(result ->
{
@ -206,14 +208,15 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
content.offer(ByteBuffer.allocate(8));
content.close();
Assert.assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
Assert.assertEquals(0, connectionPool.getConnectionCount());
assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
assertEquals(0, connectionPool.getConnectionCount());
}
@Test
public void test_ClientConnectionClose_ServerNoConnectionClose_ClientCloses() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_ClientConnectionClose_ServerNoConnectionClose_ClientCloses(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -237,21 +240,21 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString())
.onRequestSuccess(request ->
{
HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next();
Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
assertFalse(connection.getEndPoint().isOutputShutdown());
})
.onResponseHeaders(r -> r.getHeaders().remove(HttpHeader.CONNECTION))
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertEquals(0, connectionPool.getConnectionCount());
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(0, connectionPool.getConnectionCount());
}
}

View File

@ -18,13 +18,18 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -42,39 +47,32 @@ import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
@Ignore
@Disabled // Disabled by @gregw on issue #2540 - commit 621b946b10884e7308eacca241dcf8b5d6f6cff2
public class ConnectionPoolTest
{
private Server server;
private ServerConnector connector;
private HttpClient client;
@Parameterized.Parameters
public static ConnectionPool.Factory[] parameters()
public static Stream<Arguments> pools()
{
return new ConnectionPool.Factory[]
{
destination -> new DuplexConnectionPool(destination, 8, destination),
destination -> new RoundRobinConnectionPool(destination, 8, destination)
};
List<Object[]> pools = new ArrayList<>();
pools.add(new Object[] { DuplexConnectionPool.class,
(ConnectionPool.Factory)
destination -> new DuplexConnectionPool(destination, 8, destination)});
pools.add(new Object[] { RoundRobinConnectionPool.class,
(ConnectionPool.Factory)
destination -> new RoundRobinConnectionPool(destination, 8, destination)});
return pools.stream().map(Arguments::of);
}
private final ConnectionPool.Factory factory;
public ConnectionPoolTest(ConnectionPool.Factory factory)
{
this.factory = factory;
}
private void start(Handler handler) throws Exception
private void start(final ConnectionPool.Factory factory, Handler handler) throws Exception
{
server = new Server();
connector = new ServerConnector(server);
@ -83,23 +81,38 @@ public class ConnectionPoolTest
HttpClientTransport transport = new HttpClientTransportOverHTTP(1);
transport.setConnectionPoolFactory(factory);
client = new HttpClient(transport, null);
server.addBean(client);
server.start();
client = new HttpClient(transport, null);
client.start();
}
@After
public void dispose() throws Exception
@AfterEach
public void disposeServer() throws Exception
{
connector = null;
if (server != null)
{
server.stop();
server = null;
}
}
@Test
public void test() throws Exception
@AfterEach
public void disposeClient() throws Exception
{
start(new EmptyServerHandler()
if (client != null)
{
client.stop();
client = null;
}
}
@ParameterizedTest(name = "[{index}] {0}")
@MethodSource("pools")
public void test(Class<? extends ConnectionPool> connectionPoolClass, ConnectionPool.Factory factory) throws Exception
{
start(factory, new EmptyServerHandler()
{
@Override
protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -143,8 +156,8 @@ public class ConnectionPoolTest
IntStream.range(0, parallelism).parallel().forEach(i ->
IntStream.range(0, runs).forEach(j ->
run(latch, iterations, failures)));
Assert.assertTrue(latch.await(iterations, TimeUnit.SECONDS));
Assert.assertTrue(failures.toString(), failures.isEmpty());
assertTrue(latch.await(iterations, TimeUnit.SECONDS));
assertTrue(failures.isEmpty(), failures.toString());
}
private void run(CountDownLatch latch, int iterations, List<Throwable> failures)
@ -208,7 +221,7 @@ public class ConnectionPoolTest
try
{
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
catch (Throwable x)
{

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@ -30,23 +34,18 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class ContentResponseTest extends AbstractHttpClientServerTest
{
public ContentResponseTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Test
public void testResponseWithoutContentType() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testResponseWithoutContentType(Scenario scenario) throws Exception
{
final byte[] content = new byte[1024];
new Random().nextBytes(content);
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -57,22 +56,23 @@ public class ContentResponseTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(content, response.getContent());
Assert.assertNull(response.getMediaType());
Assert.assertNull(response.getEncoding());
assertEquals(200, response.getStatus());
assertArrayEquals(content, response.getContent());
assertNull(response.getMediaType());
assertNull(response.getEncoding());
}
@Test
public void testResponseWithMediaType() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testResponseWithMediaType(Scenario scenario) throws Exception
{
final String content = "The quick brown fox jumped over the lazy dog";
final String mediaType = "text/plain";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -84,24 +84,25 @@ public class ContentResponseTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(content, response.getContentAsString());
Assert.assertEquals(mediaType, response.getMediaType());
Assert.assertNull(response.getEncoding());
assertEquals(200, response.getStatus());
assertEquals(content, response.getContentAsString());
assertEquals(mediaType, response.getMediaType());
assertNull(response.getEncoding());
}
@Test
public void testResponseWithContentType() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testResponseWithContentType(Scenario scenario) throws Exception
{
final String content = "The quick brown fox jumped over the lazy dog";
final String mediaType = "text/plain";
final String encoding = "UTF-8";
final String contentType = mediaType + "; charset=" + encoding;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -113,24 +114,25 @@ public class ContentResponseTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(content, response.getContentAsString());
Assert.assertEquals(mediaType, response.getMediaType());
Assert.assertEquals(encoding, response.getEncoding());
assertEquals(200, response.getStatus());
assertEquals(content, response.getContentAsString());
assertEquals(mediaType, response.getMediaType());
assertEquals(encoding, response.getEncoding());
}
@Test
public void testResponseWithContentTypeWithQuotedCharset() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testResponseWithContentTypeWithQuotedCharset(Scenario scenario) throws Exception
{
final String content = "The quick brown fox jumped over the lazy dog";
final String mediaType = "text/plain";
final String encoding = "UTF-8";
final String contentType = mediaType + "; charset=\"" + encoding + "\"";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -142,13 +144,13 @@ public class ContentResponseTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(content, response.getContentAsString());
Assert.assertEquals(mediaType, response.getMediaType());
Assert.assertEquals(encoding, response.getEncoding());
assertEquals(200, response.getStatus());
assertEquals(content, response.getContentAsString());
assertEquals(mediaType, response.getMediaType());
assertEquals(encoding, response.getEncoding());
}
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -26,32 +30,25 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Ignore
@Disabled
public class ExternalSiteTest
{
@Rule
public final TestTracker tracker = new TestTracker();
private HttpClient client;
@Before
@BeforeEach
public void prepare() throws Exception
{
client = new HttpClient(new SslContextFactory());
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
client.stop();
@ -76,7 +73,7 @@ public class ExternalSiteTest
latch1.countDown();
}
});
Assert.assertTrue(latch1.await(10, TimeUnit.SECONDS));
assertTrue(latch1.await(10, TimeUnit.SECONDS));
// Try again the same URI, but without specifying the port
final CountDownLatch latch2 = new CountDownLatch(1);
@ -85,12 +82,12 @@ public class ExternalSiteTest
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isSucceeded());
Assert.assertEquals(200, result.getResponse().getStatus());
assertTrue(result.isSucceeded());
assertEquals(200, result.getResponse().getStatus());
latch2.countDown();
}
});
Assert.assertTrue(latch2.await(10, TimeUnit.SECONDS));
assertTrue(latch2.await(10, TimeUnit.SECONDS));
}
@Test
@ -116,7 +113,7 @@ public class ExternalSiteTest
latch.countDown();
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
@ -151,11 +148,11 @@ public class ExternalSiteTest
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
latch.countDown();
}
});
Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(latch.await(10, TimeUnit.SECONDS));
}
}
@ -172,7 +169,7 @@ public class ExternalSiteTest
.scheme(HttpScheme.HTTPS.asString())
.path("/twitter")
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
protected void assumeCanConnectTo(String host, int port)
@ -183,7 +180,7 @@ public class ExternalSiteTest
}
catch (Throwable x)
{
Assume.assumeNoException(x);
assumeTrue(x == null, "Unable to connect");
}
}
}

View File

@ -18,9 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -29,16 +29,11 @@ import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
@Deprecated
public class GZIPContentDecoderTest
{
@Rule
public final TestTracker tracker = new TestTracker();
@Test
public void testStreamNoBlocks() throws Exception
{

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.concurrent.ExecutionException;
@ -35,17 +39,17 @@ import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* This test class runs tests to make sure that hostname verification (http://www.ietf.org/rfc/rfc2818.txt
* section 3.1) is configurable in SslContextFactory and works as expected.
*/
@Ignore
@Disabled
public class HostnameVerificationTest
{
private SslContextFactory clientSslContextFactory = new SslContextFactory();
@ -53,7 +57,7 @@ public class HostnameVerificationTest
private HttpClient client;
private NetworkConnector connector;
@Before
@BeforeEach
public void setUp() throws Exception
{
QueuedThreadPool serverThreads = new QueuedThreadPool();
@ -87,7 +91,7 @@ public class HostnameVerificationTest
client.start();
}
@After
@AfterEach
public void tearDown() throws Exception
{
client.stop();
@ -107,18 +111,14 @@ public class HostnameVerificationTest
{
clientSslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
String uri = "https://localhost:" + connector.getLocalPort() + "/";
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.GET(uri);
Assert.fail("sending request to client should have failed with an Exception!");
}
catch (ExecutionException x)
{
Throwable cause = x.getCause();
Assert.assertThat(cause, Matchers.instanceOf(SSLHandshakeException.class));
Throwable root = cause.getCause().getCause();
Assert.assertThat(root, Matchers.instanceOf(CertificateException.class));
}
});
Throwable cause = x.getCause();
assertThat(cause, Matchers.instanceOf(SSLHandshakeException.class));
Throwable root = cause.getCause().getCause();
assertThat(root, Matchers.instanceOf(CertificateException.class));
}
/**
@ -139,7 +139,7 @@ public class HostnameVerificationTest
}
catch (ExecutionException e)
{
Assert.fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage());
fail("SSLHandshake should work just fine as hostname verification is disabled!", e);
}
}
@ -160,7 +160,7 @@ public class HostnameVerificationTest
}
catch (ExecutionException e)
{
Assert.fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage());
fail("SSLHandshake should work just fine as hostname verification is disabled!", e);
}
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.net.URI;
import org.eclipse.jetty.client.api.Authentication;
@ -25,8 +27,8 @@ import org.eclipse.jetty.client.api.AuthenticationStore;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.BasicAuthentication;
import org.eclipse.jetty.client.util.DigestAuthentication;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HttpAuthenticationStoreTest
{
@ -41,7 +43,7 @@ public class HttpAuthenticationStoreTest
store.addAuthentication(new BasicAuthentication(uri1, realm, "user", "password"));
Authentication result = store.findAuthentication("Basic", uri2, realm);
Assert.assertNotNull(result);
assertNotNull(result);
store.clearAuthentications();
@ -50,7 +52,7 @@ public class HttpAuthenticationStoreTest
uri2 = URI.create("https://server:443/path");
store.addAuthentication(new DigestAuthentication(uri1, realm, "user", "password"));
result = store.findAuthentication("Digest", uri2, realm);
Assert.assertNotNull(result);
assertNotNull(result);
}
@Test
@ -74,7 +76,7 @@ public class HttpAuthenticationStoreTest
URI uri2 = URI.create("http://host");
Authentication.Result result = store.findAuthenticationResult(uri2);
Assert.assertNotNull(result);
assertNotNull(result);
store.clearAuthenticationResults();
@ -95,6 +97,6 @@ public class HttpAuthenticationStoreTest
uri2 = URI.create("https://server:443/path");
result = store.findAuthenticationResult(uri2);
Assert.assertNotNull(result);
assertNotNull(result);
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
@ -35,21 +38,16 @@ import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest
{
public HttpClientAsyncContentTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testSmallAsyncContent(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testSmallAsyncContent() throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -66,7 +64,7 @@ public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest
final AtomicReference<CountDownLatch> contentLatch = new AtomicReference<>(new CountDownLatch(1));
final CountDownLatch completeLatch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseContentAsync(new Response.AsyncContentListener()
{
@Override
@ -86,34 +84,34 @@ public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest
}
});
Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
Callback callback = callbackRef.get();
// Wait a while to be sure that the parsing does not proceed.
TimeUnit.MILLISECONDS.sleep(1000);
Assert.assertEquals(1, contentCount.get());
assertEquals(1, contentCount.get());
// Succeed the content callback to proceed with parsing.
callbackRef.set(null);
contentLatch.set(new CountDownLatch(1));
callback.succeeded();
Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
callback = callbackRef.get();
// Wait a while to be sure that the parsing does not proceed.
TimeUnit.MILLISECONDS.sleep(1000);
Assert.assertEquals(2, contentCount.get());
Assert.assertEquals(1, completeLatch.getCount());
assertEquals(2, contentCount.get());
assertEquals(1, completeLatch.getCount());
// Succeed the content callback to proceed with parsing.
callbackRef.set(null);
contentLatch.set(new CountDownLatch(1));
callback.succeeded();
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertEquals(2, contentCount.get());
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertEquals(2, contentCount.get());
}
}

View File

@ -18,6 +18,13 @@
package org.eclipse.jetty.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URI;
@ -63,31 +70,25 @@ import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
{
private String realm = "TestRealm";
public HttpClientAuthenticationTest(SslContextFactory sslContextFactory)
public void startBasic(final Scenario scenario, Handler handler) throws Exception
{
super(sslContextFactory);
start(scenario, new BasicAuthenticator(), handler);
}
public void startBasic(Handler handler) throws Exception
public void startDigest(final Scenario scenario, Handler handler) throws Exception
{
start(new BasicAuthenticator(), handler);
start(scenario, new DigestAuthenticator(), handler);
}
public void startDigest(Handler handler) throws Exception
{
start(new DigestAuthenticator(), handler);
}
private void start(Authenticator authenticator, Handler handler) throws Exception
private void start(final Scenario scenario, Authenticator authenticator, Handler handler) throws Exception
{
server = new Server();
File realmFile = MavenTestingUtils.getTestResourceFile("realm.properties");
@ -108,51 +109,56 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
securityHandler.setLoginService(loginService);
securityHandler.setHandler(handler);
start(securityHandler);
start(scenario, securityHandler);
}
@Test
public void test_BasicAuthentication() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BasicAuthentication(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
test_Authentication(new BasicAuthentication(uri, realm, "basic", "basic"));
startBasic(scenario, new EmptyServerHandler());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
test_Authentication(scenario, new BasicAuthentication(uri, realm, "basic", "basic"));
}
@Test
public void test_BasicEmptyRealm() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BasicEmptyRealm(Scenario scenario) throws Exception
{
realm = "";
startBasic(new EmptyServerHandler());
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
test_Authentication(new BasicAuthentication(uri, realm, "basic", "basic"));
startBasic(scenario, new EmptyServerHandler());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
test_Authentication(scenario, new BasicAuthentication(uri, realm, "basic", "basic"));
}
@Test
public void test_BasicAnyRealm() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BasicAnyRealm(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
test_Authentication(new BasicAuthentication(uri, Authentication.ANY_REALM, "basic", "basic"));
startBasic(scenario, new EmptyServerHandler());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
test_Authentication(scenario, new BasicAuthentication(uri, Authentication.ANY_REALM, "basic", "basic"));
}
@Test
public void test_DigestAuthentication() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_DigestAuthentication(Scenario scenario) throws Exception
{
startDigest(new EmptyServerHandler());
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
test_Authentication(new DigestAuthentication(uri, realm, "digest", "digest"));
startDigest(scenario, new EmptyServerHandler());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
test_Authentication(scenario, new DigestAuthentication(uri, realm, "digest", "digest"));
}
@Test
public void test_DigestAnyRealm() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_DigestAnyRealm(Scenario scenario) throws Exception
{
startDigest(new EmptyServerHandler());
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
test_Authentication(new DigestAuthentication(uri, Authentication.ANY_REALM, "digest", "digest"));
startDigest(scenario, new EmptyServerHandler());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
test_Authentication(scenario, new DigestAuthentication(uri, Authentication.ANY_REALM, "digest", "digest"));
}
private void test_Authentication(Authentication authentication) throws Exception
private void test_Authentication(final Scenario scenario, Authentication authentication) throws Exception
{
AuthenticationStore authenticationStore = client.getAuthenticationStore();
@ -168,11 +174,11 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
client.getRequestListeners().add(requestListener);
// Request without Authentication causes a 401
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(401, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(401, response.getStatus());
assertTrue(requests.get().await(5, TimeUnit.SECONDS));
client.getRequestListeners().remove(requestListener);
authenticationStore.addAuthentication(authentication);
@ -189,11 +195,11 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
client.getRequestListeners().add(requestListener);
// Request with authentication causes a 401 (no previous successful authentication) + 200
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertTrue(requests.get().await(5, TimeUnit.SECONDS));
client.getRequestListeners().remove(requestListener);
requests.set(new CountDownLatch(1));
@ -209,18 +215,19 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
// Further requests do not trigger 401 because there is a previous successful authentication
// Remove existing header to be sure it's added by the implementation
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertTrue(requests.get().await(5, TimeUnit.SECONDS));
client.getRequestListeners().remove(requestListener);
}
@Test
public void test_BasicAuthentication_ThenRedirect() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BasicAuthentication_ThenRedirect(Scenario scenario) throws Exception
{
startBasic(new AbstractHandler()
startBasic(scenario, new AbstractHandler()
{
private final AtomicInteger requests = new AtomicInteger();
@ -229,11 +236,11 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
{
baseRequest.setHandled(true);
if (requests.incrementAndGet() == 1)
response.sendRedirect(URIUtil.newURI(scheme, request.getServerName(), request.getServerPort(), request.getRequestURI(), null));
response.sendRedirect(URIUtil.newURI(scenario.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI(), null));
}
});
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, "basic", "basic"));
final CountDownLatch requests = new CountDownLatch(3);
@ -248,31 +255,32 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
client.getRequestListeners().add(requestListener);
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/secure")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertTrue(requests.await(5, TimeUnit.SECONDS));
client.getRequestListeners().remove(requestListener);
}
@Test
public void test_Redirect_ThenBasicAuthentication() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_Redirect_ThenBasicAuthentication(Scenario scenario) throws Exception
{
startBasic(new AbstractHandler()
startBasic(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
if (request.getRequestURI().endsWith("/redirect"))
response.sendRedirect(URIUtil.newURI(scheme, request.getServerName(), request.getServerPort(), "/secure", null));
response.sendRedirect(URIUtil.newURI(scenario.getScheme(), request.getServerName(), request.getServerPort(), "/secure", null));
}
});
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, "basic", "basic"));
final CountDownLatch requests = new CountDownLatch(3);
@ -287,20 +295,21 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
client.getRequestListeners().add(requestListener);
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/redirect")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertTrue(requests.await(5, TimeUnit.SECONDS));
client.getRequestListeners().remove(requestListener);
}
@Test
public void test_BasicAuthentication_WithAuthenticationRemoved() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BasicAuthentication_WithAuthenticationRemoved(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
startBasic(scenario, new EmptyServerHandler());
final AtomicReference<CountDownLatch> requests = new AtomicReference<>(new CountDownLatch(2));
Request.Listener.Adapter requestListener = new Request.Listener.Adapter()
@ -314,57 +323,59 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
client.getRequestListeners().add(requestListener);
AuthenticationStore authenticationStore = client.getAuthenticationStore();
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic");
authenticationStore.addAuthentication(authentication);
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertTrue(requests.get().await(5, TimeUnit.SECONDS));
authenticationStore.removeAuthentication(authentication);
requests.set(new CountDownLatch(1));
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertTrue(requests.get().await(5, TimeUnit.SECONDS));
Authentication.Result result = authenticationStore.findAuthenticationResult(request.getURI());
Assert.assertNotNull(result);
assertNotNull(result);
authenticationStore.removeAuthenticationResult(result);
requests.set(new CountDownLatch(1));
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(401, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
assertNotNull(response);
assertEquals(401, response.getStatus());
assertTrue(requests.get().await(5, TimeUnit.SECONDS));
}
@Test
public void test_BasicAuthentication_WithWrongPassword() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BasicAuthentication_WithWrongPassword(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
startBasic(scenario, new EmptyServerHandler());
AuthenticationStore authenticationStore = client.getAuthenticationStore();
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "wrong");
authenticationStore.addAuthentication(authentication);
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure");
ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(401, response.getStatus());
assertNotNull(response);
assertEquals(401, response.getStatus());
}
@Test
public void test_Authentication_ThrowsException() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_Authentication_ThrowsException(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
startBasic(scenario, new EmptyServerHandler());
// Request without Authentication would cause a 401,
// but the client will throw an exception trying to
@ -387,7 +398,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/secure")
.timeout(5, TimeUnit.SECONDS)
.send(new Response.CompleteListener()
@ -395,22 +406,23 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
Assert.assertEquals(cause, result.getFailure().getMessage());
assertTrue(result.isFailed());
assertEquals(cause, result.getFailure().getMessage());
latch.countDown();
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void test_PreemptedAuthentication() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_PreemptedAuthentication(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
startBasic(scenario, new EmptyServerHandler());
AuthenticationStore authenticationStore = client.getAuthenticationStore();
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
authenticationStore.addAuthenticationResult(new BasicAuthentication.BasicResult(uri, "basic", "basic"));
AtomicInteger requests = new AtomicInteger();
@ -424,22 +436,23 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/secure")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(1, requests.get());
assertEquals(200, response.getStatus());
assertEquals(1, requests.get());
}
@Test
public void test_NonReproducibleContent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_NonReproducibleContent(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler());
startBasic(scenario, new EmptyServerHandler());
AuthenticationStore authenticationStore = client.getAuthenticationStore();
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic");
authenticationStore.addAuthentication(authentication);
@ -464,14 +477,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
content.close();
Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
@Test
public void test_RequestFailsAfterResponse() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_RequestFailsAfterResponse(Scenario scenario) throws Exception
{
startBasic(new EmptyServerHandler()
startBasic(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request,
@ -507,7 +521,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
});
AuthenticationStore authenticationStore = client.getAuthenticationStore();
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort());
BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic");
authenticationStore.addAuthentication(authentication);
@ -546,7 +560,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
});
CountDownLatch resultLatch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/secure")
.content(content)
.onResponseSuccess(r->authLatch.countDown())
@ -556,7 +570,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
resultLatch.countDown();
});
Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
private static class GeneratingContentProvider implements ContentProvider
@ -615,121 +629,130 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
};
}
}
@Test
public void testTestHeaderInfoParsing() {
AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client);
HeaderInfo headerInfo = aph.getHeaderInfo("Digest realm=\"thermostat\", qop=\"auth\", nonce=\"1523430383\"").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfo.getParameter("qop").equals("auth"));
Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfo.getParameter("qop").equals("auth"));
assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
headerInfo = aph.getHeaderInfo("Digest qop=\"auth\", realm=\"thermostat\", nonce=\"1523430383\"").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfo.getParameter("qop").equals("auth"));
Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfo.getParameter("qop").equals("auth"));
assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
headerInfo = aph.getHeaderInfo("Digest qop=\"auth\", nonce=\"1523430383\", realm=\"thermostat\"").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfo.getParameter("qop").equals("auth"));
Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfo.getParameter("qop").equals("auth"));
assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
headerInfo = aph.getHeaderInfo("Digest qop=\"auth\", nonce=\"1523430383\"").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfo.getParameter("qop").equals("auth"));
Assert.assertTrue(headerInfo.getParameter("realm") == null);
Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfo.getParameter("qop").equals("auth"));
assertTrue(headerInfo.getParameter("realm") == null);
assertTrue(headerInfo.getParameter("nonce").equals("1523430383"));
// test multiple authentications
List<HeaderInfo> headerInfoList = aph.getHeaderInfo("Digest qop=\"auth\", realm=\"thermostat\", nonce=\"1523430383\", "
+ "Digest realm=\"thermostat2\", qop=\"auth2\", nonce=\"4522530354\", "
+ "Digest qop=\"auth3\", nonce=\"9523570528\", realm=\"thermostat3\", "
+ "Digest qop=\"auth4\", nonce=\"3526435321\"");
Assert.assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(0).getParameter("qop").equals("auth"));
Assert.assertTrue(headerInfoList.get(0).getParameter("realm").equals("thermostat"));
Assert.assertTrue(headerInfoList.get(0).getParameter("nonce").equals("1523430383"));
Assert.assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(1).getParameter("qop").equals("auth2"));
Assert.assertTrue(headerInfoList.get(1).getParameter("realm").equals("thermostat2"));
Assert.assertTrue(headerInfoList.get(1).getParameter("nonce").equals("4522530354"));
Assert.assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3"));
Assert.assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3"));
Assert.assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528"));
Assert.assertTrue(headerInfoList.get(3).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(3).getParameter("qop").equals("auth4"));
Assert.assertTrue(headerInfoList.get(3).getParameter("realm") == null);
Assert.assertTrue(headerInfoList.get(3).getParameter("nonce").equals("3526435321"));
assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(0).getParameter("qop").equals("auth"));
assertTrue(headerInfoList.get(0).getParameter("realm").equals("thermostat"));
assertTrue(headerInfoList.get(0).getParameter("nonce").equals("1523430383"));
assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(1).getParameter("qop").equals("auth2"));
assertTrue(headerInfoList.get(1).getParameter("realm").equals("thermostat2"));
assertTrue(headerInfoList.get(1).getParameter("nonce").equals("4522530354"));
assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3"));
assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3"));
assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528"));
assertTrue(headerInfoList.get(3).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(3).getParameter("qop").equals("auth4"));
assertTrue(headerInfoList.get(3).getParameter("realm") == null);
assertTrue(headerInfoList.get(3).getParameter("nonce").equals("3526435321"));
List<HeaderInfo> headerInfos = aph.getHeaderInfo("Newauth realm=\"apps\", type=1, title=\"Login to \\\"apps\\\"\", Basic realm=\"simple\"");
Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Newauth"));
Assert.assertTrue(headerInfos.get(0).getParameter("realm").equals("apps"));
Assert.assertTrue(headerInfos.get(0).getParameter("type").equals("1"));
Assert.assertThat(headerInfos.get(0).getParameter("title"), Matchers.equalTo("Login to \"apps\""));
Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Basic"));
Assert.assertTrue(headerInfos.get(1).getParameter("realm").equals("simple"));
assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Newauth"));
assertTrue(headerInfos.get(0).getParameter("realm").equals("apps"));
assertTrue(headerInfos.get(0).getParameter("type").equals("1"));
assertEquals(headerInfos.get(0).getParameter("title"),"Login to \"apps\"");
assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Basic"));
assertTrue(headerInfos.get(1).getParameter("realm").equals("simple"));
}
@Test
public void testTestHeaderInfoParsingUnusualCases() {
AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client);
HeaderInfo headerInfo = aph.getHeaderInfo("Scheme").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme"));
Assert.assertTrue(headerInfo.getParameter("realm") == null);
assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme"));
assertTrue(headerInfo.getParameter("realm") == null);
List<HeaderInfo> headerInfos = aph.getHeaderInfo("Scheme1 , Scheme2 , Scheme3");
Assert.assertEquals(3, headerInfos.size());
Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme1"));
Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2"));
Assert.assertTrue(headerInfos.get(2).getType().equalsIgnoreCase("Scheme3"));
assertEquals(3, headerInfos.size());
assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme1"));
assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2"));
assertTrue(headerInfos.get(2).getType().equalsIgnoreCase("Scheme3"));
headerInfo = aph.getHeaderInfo("Scheme name=\"value\", other=\"value2\"").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme"));
Assert.assertTrue(headerInfo.getParameter("name").equals("value"));
Assert.assertTrue(headerInfo.getParameter("other").equals("value2"));
assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme"));
assertTrue(headerInfo.getParameter("name").equals("value"));
assertTrue(headerInfo.getParameter("other").equals("value2"));
headerInfo = aph.getHeaderInfo("Scheme name = value , other = \"value2\" ").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme"));
Assert.assertTrue(headerInfo.getParameter("name").equals("value"));
Assert.assertTrue(headerInfo.getParameter("other").equals("value2"));
assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme"));
assertTrue(headerInfo.getParameter("name").equals("value"));
assertTrue(headerInfo.getParameter("other").equals("value2"));
headerInfos = aph.getHeaderInfo(", , , , ,,,Scheme name=value, ,,Scheme2 name=value2,, ,,");
Assert.assertEquals(headerInfos.size(), 2);
Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme"));
Assert.assertTrue(headerInfos.get(0).getParameter("nAmE").equals("value"));
Assert.assertThat(headerInfos.get(1).getType(), Matchers.equalToIgnoringCase("Scheme2"));
Assert.assertTrue(headerInfos.get(1).getParameter("nAmE").equals("value2"));
assertEquals(headerInfos.size(), 2);
assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme"));
assertTrue(headerInfos.get(0).getParameter("nAmE").equals("value"));
assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2"));
headerInfos = aph.getHeaderInfo("Scheme name=value, Scheme2 name=value2");
assertEquals(headerInfos.size(), 2);
assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme"));
assertTrue(headerInfos.get(0).getParameter("nAmE").equals("value"));
assertThat(headerInfos.get(1).getType(), equalToIgnoringCase("Scheme2"));
assertTrue(headerInfos.get(1).getParameter("nAmE").equals("value2"));
headerInfos = aph.getHeaderInfo("Scheme , ,, ,, name=value, Scheme2 name=value2");
Assert.assertEquals(headerInfos.size(), 2);
Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme"));
Assert.assertTrue(headerInfos.get(0).getParameter("name").equals("value"));
Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2"));
Assert.assertTrue(headerInfos.get(1).getParameter("name").equals("value2"));
assertEquals(headerInfos.size(), 2);
assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme"));
assertTrue(headerInfos.get(0).getParameter("name").equals("value"));
assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2"));
assertTrue(headerInfos.get(1).getParameter("name").equals("value2"));
//Negotiate with base64 Content
headerInfo = aph.getHeaderInfo("Negotiate TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw==").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Negotiate"));
Assert.assertTrue(headerInfo.getBase64().equals("TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw=="));
assertTrue(headerInfo.getType().equalsIgnoreCase("Negotiate"));
assertTrue(headerInfo.getBase64().equals("TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw=="));
headerInfos = aph.getHeaderInfo("Negotiate TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw==, "
+ "Negotiate YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi=");
Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Negotiate"));
Assert.assertTrue(headerInfos.get(0).getBase64().equals("TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw=="));
Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Negotiate"));
Assert.assertTrue(headerInfos.get(1).getBase64().equals("YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi="));
assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Negotiate"));
assertTrue(headerInfos.get(0).getBase64().equals("TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw=="));
assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Negotiate"));
assertTrue(headerInfos.get(1).getBase64().equals("YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi="));
}
@ -741,10 +764,10 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
HeaderInfo headerInfo;
headerInfo = aph.getHeaderInfo("Digest realm=\"=the=rmo=stat=\", qop=\"=a=u=t=h=\", nonce=\"=1523430383=\"").get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfo.getParameter("qop").equals("=a=u=t=h="));
Assert.assertTrue(headerInfo.getParameter("realm").equals("=the=rmo=stat="));
Assert.assertTrue(headerInfo.getParameter("nonce").equals("=1523430383="));
assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfo.getParameter("qop").equals("=a=u=t=h="));
assertTrue(headerInfo.getParameter("realm").equals("=the=rmo=stat="));
assertTrue(headerInfo.getParameter("nonce").equals("=1523430383="));
// test multiple authentications
@ -752,20 +775,20 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
+ "Digest realm=\"=thermostat2\", qop=\"=auth2\", nonce=\"=4522530354\", "
+ "Digest qop=\"auth3=\", nonce=\"9523570528=\", realm=\"thermostat3=\", ");
Assert.assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(0).getParameter("qop").equals("=au=th="));
Assert.assertTrue(headerInfoList.get(0).getParameter("realm").equals("=ther=mostat="));
Assert.assertTrue(headerInfoList.get(0).getParameter("nonce").equals("=152343=0383="));
assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(0).getParameter("qop").equals("=au=th="));
assertTrue(headerInfoList.get(0).getParameter("realm").equals("=ther=mostat="));
assertTrue(headerInfoList.get(0).getParameter("nonce").equals("=152343=0383="));
Assert.assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(1).getParameter("qop").equals("=auth2"));
Assert.assertTrue(headerInfoList.get(1).getParameter("realm").equals("=thermostat2"));
Assert.assertTrue(headerInfoList.get(1).getParameter("nonce").equals("=4522530354"));
assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(1).getParameter("qop").equals("=auth2"));
assertTrue(headerInfoList.get(1).getParameter("realm").equals("=thermostat2"));
assertTrue(headerInfoList.get(1).getParameter("nonce").equals("=4522530354"));
Assert.assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3="));
Assert.assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3="));
Assert.assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528="));
assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3="));
assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3="));
assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528="));
}
@Test
@ -773,17 +796,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
{
AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client);
List<HeaderInfo> headerInfoList = aph.getHeaderInfo("Digest param=\",f \"");
Assert.assertEquals(1, headerInfoList.size());
assertEquals(1, headerInfoList.size());
headerInfoList = aph.getHeaderInfo("Digest realm=\"thermostat\", qop=\",Digest realm=hello\", nonce=\"1523430383=\"");
Assert.assertEquals(1, headerInfoList.size());
assertEquals(1, headerInfoList.size());
HeaderInfo headerInfo = headerInfoList.get(0);
Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
Assert.assertTrue(headerInfo.getParameter("qop").equals(",Digest realm=hello"));
Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
Assert.assertThat(headerInfo.getParameter("nonce"), Matchers.is("1523430383="));
assertTrue(headerInfo.getType().equalsIgnoreCase("Digest"));
assertTrue(headerInfo.getParameter("qop").equals(",Digest realm=hello"));
assertTrue(headerInfo.getParameter("realm").equals("thermostat"));
assertEquals(headerInfo.getParameter("nonce"), "1523430383=");
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -34,20 +37,14 @@ import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class HttpClientChunkedContentTest
{
@Rule
public final TestTracker tracker = new TestTracker();
private HttpClient client;
private void startClient() throws Exception
@ -59,7 +56,7 @@ public class HttpClientChunkedContentTest
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
if (client != null)
@ -113,7 +110,7 @@ public class HttpClientChunkedContentTest
Result result = resultRef.get();
assertTrue(result.isSucceeded());
Response response = result.getResponse();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
}
}
@ -181,7 +178,7 @@ public class HttpClientChunkedContentTest
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Result result = resultRef.get();
assertTrue(result.isSucceeded());
Assert.assertEquals(200, result.getResponse().getStatus());
assertEquals(200, result.getResponse().getStatus());
// Issue another request to be sure the connection is sane.
Request request = client.newRequest("localhost", server.getLocalPort())
@ -193,7 +190,7 @@ public class HttpClientChunkedContentTest
output.write(response.getBytes(StandardCharsets.UTF_8));
output.flush();
Assert.assertEquals(200, listener.get(5, TimeUnit.SECONDS).getStatus());
assertEquals(200, listener.get(5, TimeUnit.SECONDS).getStatus());
}
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
@ -45,9 +48,9 @@ import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public class HttpClientCustomProxyTest
{
@ -72,7 +75,7 @@ public class HttpClientCustomProxyTest
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
if (client != null)
@ -108,7 +111,7 @@ public class HttpClientCustomProxyTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response.getStatus());
assertEquals(status, response.getStatus());
}
private class CAFEBABEProxy extends ProxyConfiguration.Proxy
@ -182,8 +185,8 @@ public class HttpClientCustomProxyTest
{
ByteBuffer buffer = BufferUtil.allocate(4);
int filled = getEndPoint().fill(buffer);
Assert.assertEquals(4, filled);
Assert.assertArrayEquals(CAFE_BABE, buffer.array());
assertEquals(4, filled);
assertArrayEquals(CAFE_BABE, buffer.array());
// We are good, upgrade the connection
getEndPoint().upgrade(connectionFactory.newConnection(getEndPoint(), context));
@ -239,8 +242,8 @@ public class HttpClientCustomProxyTest
{
ByteBuffer buffer = BufferUtil.allocate(4);
int filled = getEndPoint().fill(buffer);
Assert.assertEquals(4, filled);
Assert.assertArrayEquals(CAFE_BABE, buffer.array());
assertEquals(4, filled);
assertArrayEquals(CAFE_BABE, buffer.array());
getEndPoint().write(this, buffer);
}
catch (Throwable x)

View File

@ -18,6 +18,11 @@
package org.eclipse.jetty.client;
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.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -30,57 +35,53 @@ import org.eclipse.jetty.client.http.HttpDestinationOverHTTP;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTest
{
public HttpClientExplicitConnectionTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testExplicitConnection(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
start(scenario, new EmptyServerHandler());
@Test
public void testExplicitConnection() throws Exception
{
start(new EmptyServerHandler());
Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort());
Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
FuturePromise<Connection> futureConnection = new FuturePromise<>();
destination.newConnection(futureConnection);
try (Connection connection = futureConnection.get(5, TimeUnit.SECONDS))
{
Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme);
Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scenario.getScheme());
FutureResponseListener listener = new FutureResponseListener(request);
connection.send(request, listener);
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
HttpDestinationOverHTTP httpDestination = (HttpDestinationOverHTTP)destination;
DuplexConnectionPool connectionPool = (DuplexConnectionPool)httpDestination.getConnectionPool();
Assert.assertTrue(connectionPool.getActiveConnections().isEmpty());
Assert.assertTrue(connectionPool.getIdleConnections().isEmpty());
assertTrue(connectionPool.getActiveConnections().isEmpty());
assertTrue(connectionPool.getIdleConnections().isEmpty());
}
}
@Test
public void testExplicitConnectionIsClosedOnRemoteClose() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testExplicitConnectionIsClosedOnRemoteClose(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort());
Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
FuturePromise<Connection> futureConnection = new FuturePromise<>();
destination.newConnection(futureConnection);
Connection connection = futureConnection.get(5, TimeUnit.SECONDS);
Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme);
Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scenario.getScheme());
FutureResponseListener listener = new FutureResponseListener(request);
connection.send(request, listener);
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
// Wait some time to have the client is an idle state.
TimeUnit.SECONDS.sleep(1);
@ -91,33 +92,34 @@ public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTe
TimeUnit.SECONDS.sleep(1);
HttpConnectionOverHTTP httpConnection = (HttpConnectionOverHTTP)connection;
Assert.assertFalse(httpConnection.getEndPoint().isOpen());
assertFalse(httpConnection.getEndPoint().isOpen());
HttpDestinationOverHTTP httpDestination = (HttpDestinationOverHTTP)destination;
DuplexConnectionPool connectionPool = (DuplexConnectionPool)httpDestination.getConnectionPool();
Assert.assertTrue(connectionPool.getActiveConnections().isEmpty());
Assert.assertTrue(connectionPool.getIdleConnections().isEmpty());
assertTrue(connectionPool.getActiveConnections().isEmpty());
assertTrue(connectionPool.getIdleConnections().isEmpty());
}
@Test
public void testExplicitConnectionResponseListeners() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testExplicitConnectionResponseListeners(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort());
Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
FuturePromise<Connection> futureConnection = new FuturePromise<>();
destination.newConnection(futureConnection);
Connection connection = futureConnection.get(5, TimeUnit.SECONDS);
CountDownLatch responseLatch = new CountDownLatch(1);
Request request = client.newRequest(destination.getHost(), destination.getPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseSuccess(response -> responseLatch.countDown());
FutureResponseListener listener = new FutureResponseListener(request);
connection.send(request, listener);
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
assertEquals(HttpStatus.OK_200, response.getStatus());
assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
}
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
@ -35,9 +39,9 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public class HttpClientFailureTest
{
@ -56,7 +60,7 @@ public class HttpClientFailureTest
server.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
if (server != null)
@ -83,23 +87,17 @@ public class HttpClientFailureTest
}, null);
client.start();
try
{
assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.onRequestHeaders(request -> connectionRef.get().getEndPoint().close())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
// Expected.
}
});
DuplexConnectionPool connectionPool = (DuplexConnectionPool)connectionRef.get().getHttpDestination().getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
@ -137,7 +135,7 @@ public class HttpClientFailureTest
completeLatch.countDown();
});
Assert.assertTrue(commitLatch.await(5, TimeUnit.SECONDS));
assertTrue(commitLatch.await(5, TimeUnit.SECONDS));
final CountDownLatch contentLatch = new CountDownLatch(1);
content.offer(ByteBuffer.allocate(1024), new Callback()
{
@ -148,14 +146,14 @@ public class HttpClientFailureTest
}
});
Assert.assertTrue(commitLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(commitLatch.await(5, TimeUnit.SECONDS));
assertTrue(contentLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
DuplexConnectionPool connectionPool = (DuplexConnectionPool)connectionRef.get().getHttpDestination().getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
/*
@Test
@ -217,7 +215,7 @@ public class HttpClientFailureTest
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
@ -248,7 +246,7 @@ public class HttpClientFailureTest
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
*/
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
@ -34,22 +38,17 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientGZIPTest extends AbstractHttpClientServerTest
{
public HttpClientGZIPTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Test
public void testGZIPContentEncoding() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testGZIPContentEncoding(Scenario scenario) throws Exception
{
final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -63,19 +62,20 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(data, response.getContent());
}
@Test
public void testGZIPContentOneByteAtATime() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testGZIPContentOneByteAtATime(Scenario scenario) throws Exception
{
final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -100,18 +100,19 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(data, response.getContent());
}
@Test
public void testGZIPContentSentTwiceInOneWrite() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testGZIPContentSentTwiceInOneWrite(Scenario scenario) throws Exception
{
final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -134,34 +135,36 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
byte[] expected = Arrays.copyOf(data, 2 * data.length);
System.arraycopy(data, 0, expected, data.length, data.length);
Assert.assertArrayEquals(expected, response.getContent());
assertArrayEquals(expected, response.getContent());
}
@Test
public void testGZIPContentFragmentedBeforeTrailer() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testGZIPContentFragmentedBeforeTrailer(Scenario scenario) throws Exception
{
// There are 8 trailer bytes to gzip encoding.
testGZIPContentFragmented(9);
testGZIPContentFragmented(scenario, 9);
}
@Test
public void testGZIPContentFragmentedAtTrailer() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testGZIPContentFragmentedAtTrailer(Scenario scenario) throws Exception
{
// There are 8 trailer bytes to gzip encoding.
testGZIPContentFragmented(1);
testGZIPContentFragmented(scenario, 1);
}
private void testGZIPContentFragmented(final int fragment) throws Exception
private void testGZIPContentFragmented(Scenario scenario, final int fragment) throws Exception
{
final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -190,17 +193,18 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(data, response.getContent());
}
@Test
public void testGZIPContentCorrupted() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testGZIPContentCorrupted(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -214,14 +218,14 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send(result ->
{
if (result.isFailed())
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
private static void sleep(long ms) throws IOException

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@ -36,24 +38,18 @@ import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientProxyTest extends AbstractHttpClientServerTest
{
public HttpClientProxyTest(SslContextFactory sslContextFactory)
{
// Avoid TLS otherwise CONNECT requests are sent instead of proxied requests
super(null);
}
@Test
public void testProxiedRequest() throws Exception
@ParameterizedTest
@ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests
public void testProxiedRequest(Scenario scenario) throws Exception
{
final String serverHost = "server";
final int status = HttpStatus.NO_CONTENT_204;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -73,15 +69,16 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
client.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort));
ContentResponse response = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response.getStatus());
assertEquals(status, response.getStatus());
}
@Test
public void testProxyAuthentication() throws Exception
@ParameterizedTest
@ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests
public void testProxyAuthentication(Scenario scenario) throws Exception
{
final String user = "foo";
final String password = "bar";
@ -89,7 +86,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
final String serverHost = "server";
final String realm = "test_realm";
final int status = HttpStatus.NO_CONTENT_204;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -120,15 +117,15 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
ContentResponse response1 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
// No Authentication available => 407
Assert.assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus());
assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus());
// Add authentication...
URI uri = URI.create(scheme + "://" + proxyHost + ":" + proxyPort);
URI uri = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort);
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, user, password));
final AtomicInteger requests = new AtomicInteger();
client.getRequestListeners().add(new Request.Listener.Adapter()
@ -141,36 +138,37 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
});
// ...and perform the request again => 407 + 204
ContentResponse response2 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response2.getStatus());
Assert.assertEquals(2, requests.get());
assertEquals(status, response2.getStatus());
assertEquals(2, requests.get());
// Now the authentication result is cached => 204
requests.set(0);
ContentResponse response3 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response3.getStatus());
Assert.assertEquals(1, requests.get());
assertEquals(status, response3.getStatus());
assertEquals(1, requests.get());
}
@Test
public void testProxyAuthenticationWithRedirect() throws Exception
@ParameterizedTest
@ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests
public void testProxyAuthenticationWithRedirect(Scenario scenario) throws Exception
{
String user = "foo";
String password = "bar";
String credentials = B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
String proxyHost = "localhost";
String serverHost = "server";
int serverPort = HttpScheme.HTTP.is(scheme) ? 80 : 443;
int serverPort = HttpScheme.HTTP.is(scenario.getScheme()) ? 80 : 443;
String realm = "test_realm";
int status = HttpStatus.NO_CONTENT_204;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -193,7 +191,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
if (credentials.equals(attempt))
{
// Change also the host, to verify that proxy authentication works in this case too.
response.sendRedirect(scheme + "://127.0.0.1:" + serverPort + "/server");
response.sendRedirect(scenario.getScheme() + "://127.0.0.1:" + serverPort + "/server");
}
}
}
@ -213,16 +211,16 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
ContentResponse response1 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/proxy")
.timeout(5, TimeUnit.SECONDS)
.send();
// No Authentication available => 407.
Assert.assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus());
assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus());
// Add authentication...
URI uri = URI.create(scheme + "://" + proxyHost + ":" + proxyPort);
URI uri = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort);
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, user, password));
final AtomicInteger requests = new AtomicInteger();
client.getRequestListeners().add(new Request.Listener.Adapter()
@ -235,33 +233,34 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
});
// ...and perform the request again => 407 + 302 + 204.
ContentResponse response2 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/proxy")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response2.getStatus());
Assert.assertEquals(3, requests.get());
assertEquals(status, response2.getStatus());
assertEquals(3, requests.get());
// Now the authentication result is cached => 204.
requests.set(0);
ContentResponse response3 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/server")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response3.getStatus());
Assert.assertEquals(1, requests.get());
assertEquals(status, response3.getStatus());
assertEquals(1, requests.get());
}
@Test
public void testProxyAuthenticationWithServerAuthentication() throws Exception
@ParameterizedTest
@ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests
public void testProxyAuthenticationWithServerAuthentication(Scenario scenario) throws Exception
{
String proxyRealm = "proxyRealm";
String serverRealm = "serverRealm";
int status = HttpStatus.NO_CONTENT_204;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -293,9 +292,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
int proxyPort = connector.getLocalPort();
String serverHost = "server";
int serverPort = proxyPort + 1;
URI proxyURI = URI.create(scheme + "://" + proxyHost + ":" + proxyPort);
URI proxyURI = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort);
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(proxyURI, proxyRealm, "proxyUser", "proxyPassword"));
URI serverURI = URI.create(scheme + "://" + serverHost + ":" + serverPort);
URI serverURI = URI.create(scenario.getScheme() + "://" + serverHost + ":" + serverPort);
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(serverURI, serverRealm, "serverUser", "serverPassword"));
client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
final AtomicInteger requests = new AtomicInteger();
@ -309,31 +308,32 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
});
// Make a request, expect 407 + 401 + 204.
ContentResponse response1 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response1.getStatus());
Assert.assertEquals(3, requests.get());
assertEquals(status, response1.getStatus());
assertEquals(3, requests.get());
// Make again the request, authentication is cached, expect 204.
requests.set(0);
ContentResponse response2 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response2.getStatus());
Assert.assertEquals(1, requests.get());
assertEquals(status, response2.getStatus());
assertEquals(1, requests.get());
}
@Test
public void testProxyAuthenticationWithExplicitAuthorizationHeader() throws Exception
@ParameterizedTest
@ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests
public void testProxyAuthenticationWithExplicitAuthorizationHeader(Scenario scenario) throws Exception
{
String proxyRealm = "proxyRealm";
String serverRealm = "serverRealm";
int status = HttpStatus.NO_CONTENT_204;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -365,7 +365,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
int proxyPort = connector.getLocalPort();
String serverHost = "server";
int serverPort = proxyPort + 1;
URI proxyURI = URI.create(scheme + "://" + proxyHost + ":" + proxyPort);
URI proxyURI = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort);
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(proxyURI, proxyRealm, "proxyUser", "proxyPassword"));
client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
final AtomicInteger requests = new AtomicInteger();
@ -379,23 +379,23 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest
});
// Make a request, expect 407 + 204.
ContentResponse response1 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.AUTHORIZATION, "Basic foobar")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response1.getStatus());
Assert.assertEquals(2, requests.get());
assertEquals(status, response1.getStatus());
assertEquals(2, requests.get());
// Make again the request, authentication is cached, expect 204.
requests.set(0);
ContentResponse response2 = client.newRequest(serverHost, serverPort)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.AUTHORIZATION, "Basic foobar")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(status, response2.getStatus());
Assert.assertEquals(1, requests.get());
assertEquals(status, response2.getStatus());
assertEquals(1, requests.get());
}
}

View File

@ -18,6 +18,14 @@
package org.eclipse.jetty.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
@ -42,229 +50,226 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientRedirectTest extends AbstractHttpClientServerTest
{
public HttpClientRedirectTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_303(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void test_303() throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void test_303_302() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_303_302(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/302/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void test_303_302_OnDifferentDestinations() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_303_302_OnDifferentDestinations(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/127.0.0.1/302/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void test_301() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_301(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.HEAD)
.path("/301/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void test_301_WithWrongMethod() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_301_WithWrongMethod(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.DELETE)
.path("/301/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
HttpResponseException xx = (HttpResponseException)x.getCause();
Response response = xx.getResponse();
Assert.assertNotNull(response);
Assert.assertEquals(301, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
});
HttpResponseException xx = (HttpResponseException)x.getCause();
Response response = xx.getResponse();
assertNotNull(response);
assertEquals(301, response.getStatus());
assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void test_307_WithRequestContent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_307_WithRequestContent(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6, 7};
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.path("/307/localhost/done")
.content(new ByteBufferContentProvider(ByteBuffer.wrap(data)))
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
Assert.assertArrayEquals(data, response.getContent());
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertArrayEquals(data, response.getContent());
}
@Test
public void testMaxRedirections() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testMaxRedirections(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
client.setMaxRedirects(1);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/302/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
HttpResponseException xx = (HttpResponseException)x.getCause();
Response response = xx.getResponse();
Assert.assertNotNull(response);
Assert.assertEquals(302, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
});
HttpResponseException xx = (HttpResponseException)x.getCause();
Response response = xx.getResponse();
assertNotNull(response);
assertEquals(302, response.getStatus());
assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void test_303_WithConnectionClose_WithBigRequest() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_303_WithConnectionClose_WithBigRequest(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/done?close=true")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void testDontFollowRedirects() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testDontFollowRedirects(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.followRedirects(false)
.path("/303/localhost/done?close=true")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(303, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(303, response.getStatus());
assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void testRelativeLocation() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRelativeLocation(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/done?relative=true")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void testAbsoluteURIPathWithSpaces() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbsoluteURIPathWithSpaces(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/a+space?decode=true")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void testRelativeURIPathWithSpaces() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRelativeURIPathWithSpaces(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/a+space?relative=true&decode=true")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
}
@Test
public void testRedirectWithWrongScheme() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRedirectWithWrongScheme(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -277,149 +282,164 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/path")
.timeout(5, TimeUnit.SECONDS)
.send(result ->
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
@Ignore
public void testRedirectFailed() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
@Disabled
public void testRedirectFailed(Scenario scenario) throws Exception
{
// TODO this test is failing with timout after an ISP upgrade?? DNS dependent?
start(new RedirectHandler());
start(scenario, new RedirectHandler());
try
{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/doesNotExist/done")
.timeout(5, TimeUnit.SECONDS)
.send();
}
catch (ExecutionException x)
{
Assert.assertThat(x.getCause(), Matchers.instanceOf(UnresolvedAddressException.class));
assertThat(x.getCause(), Matchers.instanceOf(UnresolvedAddressException.class));
}
}
@Test
public void test_HEAD_301() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_HEAD_301(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.MOVED_PERMANENTLY_301);
testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.MOVED_PERMANENTLY_301);
}
@Test
public void test_POST_301() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_POST_301(Scenario scenario) throws Exception
{
testGETRedirect(HttpMethod.POST, HttpStatus.MOVED_PERMANENTLY_301);
testGETRedirect(scenario, HttpMethod.POST, HttpStatus.MOVED_PERMANENTLY_301);
}
@Test
public void test_PUT_301() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_PUT_301(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.PUT, HttpStatus.MOVED_PERMANENTLY_301);
testSameMethodRedirect(scenario, HttpMethod.PUT, HttpStatus.MOVED_PERMANENTLY_301);
}
@Test
public void test_HEAD_302() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_HEAD_302(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.FOUND_302);
testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.FOUND_302);
}
@Test
public void test_POST_302() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_POST_302(Scenario scenario) throws Exception
{
testGETRedirect(HttpMethod.POST, HttpStatus.FOUND_302);
testGETRedirect(scenario, HttpMethod.POST, HttpStatus.FOUND_302);
}
@Test
public void test_PUT_302() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_PUT_302(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.PUT, HttpStatus.FOUND_302);
testSameMethodRedirect(scenario, HttpMethod.PUT, HttpStatus.FOUND_302);
}
@Test
public void test_HEAD_303() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_HEAD_303(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.SEE_OTHER_303);
testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.SEE_OTHER_303);
}
@Test
public void test_POST_303() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_POST_303(Scenario scenario) throws Exception
{
testGETRedirect(HttpMethod.POST, HttpStatus.SEE_OTHER_303);
testGETRedirect(scenario, HttpMethod.POST, HttpStatus.SEE_OTHER_303);
}
@Test
public void test_PUT_303() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_PUT_303(Scenario scenario) throws Exception
{
testGETRedirect(HttpMethod.PUT, HttpStatus.SEE_OTHER_303);
testGETRedirect(scenario, HttpMethod.PUT, HttpStatus.SEE_OTHER_303);
}
@Test
public void test_HEAD_307() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_HEAD_307(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.TEMPORARY_REDIRECT_307);
testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.TEMPORARY_REDIRECT_307);
}
@Test
public void test_POST_307() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_POST_307(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.POST, HttpStatus.TEMPORARY_REDIRECT_307);
testSameMethodRedirect(scenario, HttpMethod.POST, HttpStatus.TEMPORARY_REDIRECT_307);
}
@Test
public void test_PUT_307() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_PUT_307(Scenario scenario) throws Exception
{
testSameMethodRedirect(HttpMethod.PUT, HttpStatus.TEMPORARY_REDIRECT_307);
testSameMethodRedirect(scenario, HttpMethod.PUT, HttpStatus.TEMPORARY_REDIRECT_307);
}
@Test
public void testHttpRedirector() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testHttpRedirector(Scenario scenario) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
final HttpRedirector redirector = new HttpRedirector(client);
org.eclipse.jetty.client.api.Request request1 = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/303/localhost/302/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.followRedirects(false);
ContentResponse response1 = request1.send();
Assert.assertEquals(303, response1.getStatus());
Assert.assertTrue(redirector.isRedirect(response1));
assertEquals(303, response1.getStatus());
assertTrue(redirector.isRedirect(response1));
Result result = redirector.redirect(request1, response1);
org.eclipse.jetty.client.api.Request request2 = result.getRequest();
Response response2 = result.getResponse();
Assert.assertEquals(302, response2.getStatus());
Assert.assertTrue(redirector.isRedirect(response2));
assertEquals(302, response2.getStatus());
assertTrue(redirector.isRedirect(response2));
final CountDownLatch latch = new CountDownLatch(1);
redirector.redirect(request2, response2, r ->
{
Response response3 = r.getResponse();
Assert.assertEquals(200, response3.getStatus());
Assert.assertFalse(redirector.isRedirect(response3));
assertEquals(200, response3.getStatus());
assertFalse(redirector.isRedirect(response3));
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testRedirectWithCorruptedBody() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRedirectWithCorruptedBody(Scenario scenario) throws Exception
{
byte[] bytes = "ok".getBytes(StandardCharsets.UTF_8);
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -428,7 +448,7 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
if (target.startsWith("/redirect"))
{
response.setStatus(HttpStatus.SEE_OTHER_303);
response.setHeader(HttpHeader.LOCATION.asString(), scheme + "://localhost:" + connector.getLocalPort() + "/ok");
response.setHeader(HttpHeader.LOCATION.asString(), scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/ok");
// Say that we send gzipped content, but actually don't.
response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
response.getOutputStream().write("redirect".getBytes(StandardCharsets.UTF_8));
@ -442,28 +462,28 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/redirect")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(bytes, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(bytes, response.getContent());
}
private void testSameMethodRedirect(final HttpMethod method, int redirectCode) throws Exception
private void testSameMethodRedirect(final Scenario scenario, final HttpMethod method, int redirectCode) throws Exception
{
testMethodRedirect(method, method, redirectCode);
testMethodRedirect(scenario, method, method, redirectCode);
}
private void testGETRedirect(final HttpMethod method, int redirectCode) throws Exception
private void testGETRedirect(final Scenario scenario, final HttpMethod method, int redirectCode) throws Exception
{
testMethodRedirect(method, HttpMethod.GET, redirectCode);
testMethodRedirect(scenario, method, HttpMethod.GET, redirectCode);
}
private void testMethodRedirect(final HttpMethod requestMethod, final HttpMethod redirectMethod, int redirectCode) throws Exception
private void testMethodRedirect(final Scenario scenario, final HttpMethod requestMethod, final HttpMethod redirectMethod, int redirectCode) throws Exception
{
start(new RedirectHandler());
start(scenario, new RedirectHandler());
final AtomicInteger passes = new AtomicInteger();
client.getRequestListeners().add(new org.eclipse.jetty.client.api.Request.Listener.Adapter()
@ -490,13 +510,13 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(requestMethod)
.path("/" + redirectCode + "/localhost/done")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
private class RedirectHandler extends AbstractHandler

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.ConnectException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -25,25 +29,20 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
/**
* Verifies that synchronization performed from outside HttpClient does not cause deadlocks
*/
public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest
{
public HttpClientSynchronizationTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testSynchronizationOnException(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testSynchronizationOnException() throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
int port = connector.getLocalPort();
server.stop();
@ -52,7 +51,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest
for (int i = 0; i < count; ++i)
{
Request request = client.newRequest("localhost", port)
.scheme(scheme);
.scheme(scenario.getScheme());
synchronized (this)
{
@ -63,7 +62,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest
{
synchronized (HttpClientSynchronizationTest.this)
{
Assert.assertThat(failure, Matchers.instanceOf(ConnectException.class));
assertThat(failure, Matchers.instanceOf(ConnectException.class));
latch.countDown();
}
}
@ -71,20 +70,21 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest
}
}
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testSynchronizationOnComplete() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testSynchronizationOnComplete(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
int count = 10;
final CountDownLatch latch = new CountDownLatch(count);
for (int i = 0; i < count; ++i)
{
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme);
.scheme(scenario.getScheme());
synchronized (this)
{
@ -95,7 +95,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest
{
synchronized (HttpClientSynchronizationTest.this)
{
Assert.assertFalse(result.isFailed());
assertFalse(result.isFailed());
latch.countDown();
}
}
@ -103,6 +103,6 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest
}
}
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
}

View File

@ -18,6 +18,15 @@
package org.eclipse.jetty.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
@ -49,10 +58,11 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.ExecutorThreadPool;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
public class HttpClientTLSTest
{
@ -91,7 +101,7 @@ public class HttpClientTLSTest
return sslContextFactory;
}
@After
@AfterEach
public void dispose() throws Exception
{
if (client != null)
@ -131,21 +141,15 @@ public class HttpClientTLSTest
}
});
try
{
assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
// Expected.
}
});
Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
@Test
@ -179,21 +183,15 @@ public class HttpClientTLSTest
}
});
try
{
assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
// Expected.
}
});
Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
@Test
@ -228,29 +226,23 @@ public class HttpClientTLSTest
}
});
try
{
assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
// Expected.
}
});
Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
// In JDK 11, a mismatch on the client does not generate any bytes towards
// the server, while in TLS 1.2 the client sends to the server the close_notify.
@DisabledOnJre( JRE.JAVA_11 )
@Test
public void testMismatchBetweenTLSProtocolAndTLSCiphersOnClient() throws Exception
{
// In JDK 11, a mismatch on the client does not generate any bytes towards
// the server, while in TLS 1.2 the client sends to the server the close_notify.
Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11));
SslContextFactory serverTLSFactory = createSslContextFactory();
startServer(serverTLSFactory, new EmptyServerHandler());
@ -281,21 +273,15 @@ public class HttpClientTLSTest
}
});
try
{
assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(HttpScheme.HTTPS.asString())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
// Expected.
}
});
Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
@Test
@ -328,17 +314,17 @@ public class HttpClientTLSTest
});
ContentResponse response = client.GET("https://localhost:" + connector.getLocalPort());
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
// Excluded because of a bug in JDK 11+27 where session resumption does not work.
@DisabledOnJre( JRE.JAVA_11 )
@Test
public void testHandshakeSucceededWithSessionResumption() throws Exception
{
// Excluded because of a bug in JDK 11+27 where session resumption does not work.
Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11));
SslContextFactory serverTLSFactory = createSslContextFactory();
startServer(serverTLSFactory, new EmptyServerHandler());
@ -372,10 +358,10 @@ public class HttpClientTLSTest
.header(HttpHeader.CONNECTION, "close")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertNotNull(serverSession.get());
Assert.assertNotNull(clientSession.get());
assertNotNull(serverSession.get());
assertNotNull(clientSession.get());
connector.removeBean(connector.getBean(SslHandshakeListener.class));
client.removeBean(client.getBean(SslHandshakeListener.class));
@ -408,17 +394,17 @@ public class HttpClientTLSTest
.header(HttpHeader.CONNECTION, "close")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
assertTrue(serverLatch.await(1, TimeUnit.SECONDS));
assertTrue(clientLatch.await(1, TimeUnit.SECONDS));
}
// Excluded because of a bug in JDK 11+27 where session resumption does not work.
@DisabledOnJre( JRE.JAVA_11 )
@Test
public void testClientRawCloseDoesNotInvalidateSession() throws Exception
{
// Excluded because of a bug in JDK 11+27 where session resumption does not work.
Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11));
SslContextFactory serverTLSFactory = createSslContextFactory();
startServer(serverTLSFactory, new EmptyServerHandler());
@ -438,7 +424,7 @@ public class HttpClientTLSTest
handshakeLatch1.countDown();
});
sslSocket.startHandshake();
Assert.assertTrue(handshakeLatch1.await(5, TimeUnit.SECONDS));
assertTrue(handshakeLatch1.await(5, TimeUnit.SECONDS));
// In TLS 1.3 the server sends a NewSessionTicket post-handshake message
// to enable session resumption and without a read, the message is not processed.
@ -465,9 +451,9 @@ public class HttpClientTLSTest
handshakeLatch2.countDown();
});
sslSocket.startHandshake();
Assert.assertTrue(handshakeLatch2.await(5, TimeUnit.SECONDS));
assertTrue(handshakeLatch2.await(5, TimeUnit.SECONDS));
Assert.assertArrayEquals(session1.get(), session2.get());
assertArrayEquals(session1.get(), session2.get());
sslSocket.close();
}
@ -499,7 +485,7 @@ public class HttpClientTLSTest
.scheme(HttpScheme.HTTPS.asString())
.send(result ->
{
Assert.assertThat(result.getResponseFailure(), Matchers.instanceOf(SSLException.class));
assertThat(result.getResponseFailure(), instanceOf(SSLException.class));
latch.countDown();
});
@ -538,7 +524,7 @@ public class HttpClientTLSTest
// the socket in the try-with-resources block end.
}
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
}
}

View File

@ -18,7 +18,12 @@
package org.eclipse.jetty.client;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
@ -47,54 +52,47 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpClientURITest extends AbstractHttpClientServerTest
{
@Rule
public ExpectedException expectedException = ExpectedException.none();
public HttpClientURITest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testIPv6Host(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testIPv6Host() throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "::1";
Request request = client.newRequest(host, connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS);
Assert.assertEquals(host, request.getHost());
assertEquals(host, request.getHost());
StringBuilder uri = new StringBuilder();
URIUtil.appendSchemeHostPort(uri, scheme, host, connector.getLocalPort());
Assert.assertEquals(uri.toString(), request.getURI().toString());
URIUtil.appendSchemeHostPort(uri, scenario.getScheme(), host, connector.getLocalPort());
assertEquals(uri.toString(), request.getURI().toString());
Assert.assertEquals(HttpStatus.OK_200, request.send().getStatus());
assertEquals(HttpStatus.OK_200, request.send().getStatus());
}
@Test
public void testIDNHost() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testIDNHost(Scenario scenario) throws Exception
{
startClient();
expectedException.expect(IllegalArgumentException.class);
client.newRequest(scheme + "://пример.рф"); // example.com-like host in IDN domain
startClient(scenario);
assertThrows(IllegalArgumentException.class, ()-> {
client.newRequest(scenario.getScheme() + "://пример.рф"); // example.com-like host in IDN domain
});
}
@Test
public void testIDNRedirect() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testIDNRedirect(Scenario scenario) throws Exception
{
// Internationalized Domain Name.
// String exampleHost = scheme + "://пример.рф";
String exampleHost = scheme + "://\uD0BF\uD180\uD0B8\uD0BC\uD0B5\uD180.\uD180\uD184";
String exampleHost = scenario.getScheme() + "://\uD0BF\uD180\uD0B8\uD0BC\uD0B5\uD180.\uD180\uD184";
String incorrectlyDecoded = new String(exampleHost.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
// Simple server that only parses clear-text HTTP/1.1.
@ -103,7 +101,7 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
try
{
startClient();
startClient(scenario);
ContentResponse response = client.newRequest("localhost", server.getLocalPort())
.timeout(5, TimeUnit.SECONDS)
@ -111,14 +109,15 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
.send();
HttpField location = response.getHeaders().getField(HttpHeader.LOCATION);
Assert.assertEquals(incorrectlyDecoded, location.getValue());
assertEquals(incorrectlyDecoded, location.getValue());
expectedException.expect(ExecutionException.class);
expectedException.expectCause(instanceOf(IllegalArgumentException.class));
client.newRequest("localhost", server.getLocalPort())
.timeout(5, TimeUnit.SECONDS)
.followRedirects(true)
.send();
ExecutionException x = assertThrows(ExecutionException.class, ()-> {
client.newRequest("localhost", server.getLocalPort())
.timeout(5, TimeUnit.SECONDS)
.followRedirects(true)
.send();
});
assertThat(x.getCause(), instanceOf(IllegalArgumentException.class));
}
finally
{
@ -126,111 +125,115 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
}
}
@Test
public void testPath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testPath(Scenario scenario) throws Exception
{
final String path = "/path";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
assertEquals(path, request.getRequestURI());
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(path);
Assert.assertEquals(path, request.getPath());
Assert.assertNull(request.getQuery());
assertEquals(path, request.getPath());
assertNull(request.getQuery());
Fields params = request.getParams();
Assert.assertEquals(0, params.getSize());
Assert.assertTrue(request.getURI().toString().endsWith(path));
assertEquals(0, params.getSize());
assertTrue(request.getURI().toString().endsWith(path));
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testPathWithQuery() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testPathWithQuery(Scenario scenario) throws Exception
{
String name = "a";
String value = "1";
final String query = name + "=" + value;
final String path = "/path";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
Assert.assertEquals(query, request.getQueryString());
assertEquals(path, request.getRequestURI());
assertEquals(query, request.getQueryString());
}
});
String pathQuery = path + "?" + query;
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(pathQuery);
Assert.assertEquals(path, request.getPath());
Assert.assertEquals(query, request.getQuery());
Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
assertEquals(path, request.getPath());
assertEquals(query, request.getQuery());
assertTrue(request.getURI().toString().endsWith(pathQuery));
Fields params = request.getParams();
Assert.assertEquals(1, params.getSize());
Assert.assertEquals(value, params.get(name).getValue());
assertEquals(1, params.getSize());
assertEquals(value, params.get(name).getValue());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testPathWithParam() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testPathWithParam(Scenario scenario) throws Exception
{
String name = "a";
String value = "1";
final String query = name + "=" + value;
final String path = "/path";
String pathQuery = path + "?" + query;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
Assert.assertEquals(query, request.getQueryString());
assertEquals(path, request.getRequestURI());
assertEquals(query, request.getQueryString());
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(path)
.param(name, value);
Assert.assertEquals(path, request.getPath());
Assert.assertEquals(query, request.getQuery());
Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
assertEquals(path, request.getPath());
assertEquals(query, request.getQuery());
assertTrue(request.getURI().toString().endsWith(pathQuery));
Fields params = request.getParams();
Assert.assertEquals(1, params.getSize());
Assert.assertEquals(value, params.get(name).getValue());
assertEquals(1, params.getSize());
assertEquals(value, params.get(name).getValue());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testPathWithQueryAndParam() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testPathWithQueryAndParam(Scenario scenario) throws Exception
{
String name1 = "a";
String value1 = "1";
@ -239,38 +242,39 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
final String query = name1 + "=" + value1 + "&" + name2 + "=" + value2;
final String path = "/path";
String pathQuery = path + "?" + query;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
Assert.assertEquals(query, request.getQueryString());
assertEquals(path, request.getRequestURI());
assertEquals(query, request.getQueryString());
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(path + "?" + name1 + "=" + value1)
.param(name2, value2);
Assert.assertEquals(path, request.getPath());
Assert.assertEquals(query, request.getQuery());
Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
assertEquals(path, request.getPath());
assertEquals(query, request.getQuery());
assertTrue(request.getURI().toString().endsWith(pathQuery));
Fields params = request.getParams();
Assert.assertEquals(2, params.getSize());
Assert.assertEquals(value1, params.get(name1).getValue());
Assert.assertEquals(value2, params.get(name2).getValue());
assertEquals(2, params.getSize());
assertEquals(value1, params.get(name1).getValue());
assertEquals(value2, params.get(name2).getValue());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testPathWithQueryAndParamValueEncoded() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testPathWithQueryAndParamValueEncoded(Scenario scenario) throws Exception
{
final String name1 = "a";
final String value1 = "\u20AC";
@ -281,189 +285,195 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
final String query = name1 + "=" + encodedValue1 + "&" + name2 + "=" + encodedValue2;
final String path = "/path";
String pathQuery = path + "?" + query;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
Assert.assertEquals(query, request.getQueryString());
Assert.assertEquals(value1, request.getParameter(name1));
Assert.assertEquals(value2, request.getParameter(name2));
assertEquals(path, request.getRequestURI());
assertEquals(query, request.getQueryString());
assertEquals(value1, request.getParameter(name1));
assertEquals(value2, request.getParameter(name2));
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(path + "?" + name1 + "=" + encodedValue1)
.param(name2, value2);
Assert.assertEquals(path, request.getPath());
Assert.assertEquals(query, request.getQuery());
Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
assertEquals(path, request.getPath());
assertEquals(query, request.getQuery());
assertTrue(request.getURI().toString().endsWith(pathQuery));
Fields params = request.getParams();
Assert.assertEquals(2, params.getSize());
Assert.assertEquals(value1, params.get(name1).getValue());
Assert.assertEquals(value2, params.get(name2).getValue());
assertEquals(2, params.getSize());
assertEquals(value1, params.get(name1).getValue());
assertEquals(value2, params.get(name2).getValue());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testNoParameterNameNoParameterValue() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testNoParameterNameNoParameterValue(Scenario scenario) throws Exception
{
final String path = "/path";
final String query = "="; // Bogus query
String pathQuery = path + "?" + query;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
Assert.assertEquals(query, request.getQueryString());
assertEquals(path, request.getRequestURI());
assertEquals(query, request.getQueryString());
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(pathQuery);
Assert.assertEquals(path, request.getPath());
Assert.assertEquals(query, request.getQuery());
Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
assertEquals(path, request.getPath());
assertEquals(query, request.getQuery());
assertTrue(request.getURI().toString().endsWith(pathQuery));
Fields params = request.getParams();
Assert.assertEquals(0, params.getSize());
assertEquals(0, params.getSize());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testNoParameterNameWithParameterValue() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testNoParameterNameWithParameterValue(Scenario scenario) throws Exception
{
final String path = "/path";
final String query = "=1"; // Bogus query
String pathQuery = path + "?" + query;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(path, request.getRequestURI());
Assert.assertEquals(query, request.getQueryString());
assertEquals(path, request.getRequestURI());
assertEquals(query, request.getQueryString());
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.path(pathQuery);
Assert.assertEquals(path, request.getPath());
Assert.assertEquals(query, request.getQuery());
Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
assertEquals(path, request.getPath());
assertEquals(query, request.getQuery());
assertTrue(request.getURI().toString().endsWith(pathQuery));
Fields params = request.getParams();
Assert.assertEquals(0, params.getSize());
assertEquals(0, params.getSize());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testCaseSensitiveParameterName() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testCaseSensitiveParameterName(Scenario scenario) throws Exception
{
final String name1 = "a";
final String name2 = "A";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(name1, request.getParameter(name1));
Assert.assertEquals(name2, request.getParameter(name2));
assertEquals(name1, request.getParameter(name1));
assertEquals(name2, request.getParameter(name2));
}
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/path?" + name1 + "=" + name1)
.param(name2, name2)
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testRawQueryIsPreservedInURI() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRawQueryIsPreservedInURI(Scenario scenario) throws Exception
{
final String name = "a";
final String rawValue = "Hello%20World";
final String rawQuery = name + "=" + rawValue;
final String value = "Hello World";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(rawQuery, request.getQueryString());
Assert.assertEquals(value, request.getParameter(name));
assertEquals(rawQuery, request.getQueryString());
assertEquals(value, request.getParameter(name));
}
});
String uri = scheme + "://localhost:" + connector.getLocalPort() + "/path?" + rawQuery;
String uri = scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/path?" + rawQuery;
Request request = client.newRequest(uri)
.timeout(5, TimeUnit.SECONDS);
Assert.assertEquals(rawQuery, request.getQuery());
assertEquals(rawQuery, request.getQuery());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testRawQueryIsPreservedInPath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRawQueryIsPreservedInPath(Scenario scenario) throws Exception
{
final String name = "a";
final String rawValue = "Hello%20World";
final String rawQuery = name + "=" + rawValue;
final String value = "Hello World";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(rawQuery, request.getQueryString());
Assert.assertEquals(value, request.getParameter(name));
assertEquals(rawQuery, request.getQueryString());
assertEquals(value, request.getParameter(name));
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/path?" + rawQuery)
.timeout(5, TimeUnit.SECONDS);
Assert.assertEquals(rawQuery, request.getQuery());
assertEquals(rawQuery, request.getQuery());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testRawQueryIsPreservedWithParam() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRawQueryIsPreservedWithParam(Scenario scenario) throws Exception
{
final String name1 = "a";
final String name2 = "b";
@ -473,34 +483,35 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
final String value2 = "alfa omega";
final String encodedQuery2 = name2 + "=" + URLEncoder.encode(value2, "UTF-8");
final String query = rawQuery1 + "&" + encodedQuery2;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals(query, request.getQueryString());
Assert.assertEquals(value1, request.getParameter(name1));
Assert.assertEquals(value2, request.getParameter(name2));
assertEquals(query, request.getQueryString());
assertEquals(value1, request.getParameter(name1));
assertEquals(value2, request.getParameter(name2));
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/path?" + rawQuery1)
.param(name2, value2)
.timeout(5, TimeUnit.SECONDS);
Assert.assertEquals(query, request.getQuery());
assertEquals(query, request.getQuery());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testSchemeIsCaseInsensitive() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testSchemeIsCaseInsensitive(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -510,17 +521,18 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme.toUpperCase(Locale.ENGLISH))
.scheme(scenario.getScheme().toUpperCase(Locale.ENGLISH))
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testHostIsCaseInsensitive() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testHostIsCaseInsensitive(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -530,42 +542,43 @@ public class HttpClientURITest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("LOCALHOST", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
public void testAsteriskFormTarget() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAsteriskFormTarget(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals("*", target);
Assert.assertEquals("*", request.getPathInfo());
assertEquals("*", target);
assertEquals("*", request.getPathInfo());
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.method(HttpMethod.OPTIONS)
.scheme(scheme)
.scheme(scenario.getScheme())
.path("*")
.timeout(5, TimeUnit.SECONDS);
Assert.assertEquals("*", request.getPath());
Assert.assertNull(request.getQuery());
assertEquals("*", request.getPath());
assertNull(request.getQuery());
Fields params = request.getParams();
Assert.assertEquals(0, params.getSize());
Assert.assertNull(request.getURI());
assertEquals(0, params.getSize());
assertNull(request.getURI());
ContentResponse response = request.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
private static class IDNRedirectServer implements Runnable

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
@ -43,8 +46,8 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HttpClientUploadDuringServerShutdown
{
@ -216,7 +219,7 @@ public class HttpClientUploadDuringServerShutdown
// Create one connection.
client.newRequest("localhost", connector.getLocalPort()).send();
Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS));
assertTrue(serverLatch.await(5, TimeUnit.SECONDS));
afterSetup.set(true);
Thread.sleep(1000);
@ -228,7 +231,7 @@ public class HttpClientUploadDuringServerShutdown
// Wait for close() so that the connection that
// is being closed is used to send the request.
Assert.assertTrue(sendLatch.await(5, TimeUnit.SECONDS));
assertTrue(sendLatch.await(5, TimeUnit.SECONDS));
final CountDownLatch completeLatch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
@ -247,12 +250,12 @@ public class HttpClientUploadDuringServerShutdown
})
.send(result -> completeLatch.countDown());
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination("http", "localhost", connector.getLocalPort());
DuplexConnectionPool pool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, pool.getConnectionCount());
Assert.assertEquals(0, pool.getIdleConnections().size());
Assert.assertEquals(0, pool.getActiveConnections().size());
assertEquals(0, pool.getConnectionCount());
assertEquals(0, pool.getIdleConnections().size());
assertEquals(0, pool.getActiveConnections().size());
}
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
@ -41,52 +45,48 @@ import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
{
public HttpConnectionLifecycleTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Override
public void start(Handler handler) throws Exception
public void start(Scenario scenario, Handler handler) throws Exception
{
super.start(handler);
super.start(scenario, handler);
client.setStrictEventOrdering(false);
}
@Test
public void test_SuccessfulRequest_ReturnsConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SuccessfulRequest_ReturnsConnection(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
final CountDownLatch headersLatch = new CountDownLatch(1);
final CountDownLatch successLatch = new CountDownLatch(3);
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.onRequestSuccess(request -> successLatch.countDown())
.onResponseHeaders(response ->
{
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(1, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(1, activeConnections.size());
headersLatch.countDown();
})
.send(new Response.Listener.Adapter()
@ -100,37 +100,38 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Override
public void onComplete(Result result)
{
Assert.assertFalse(result.isFailed());
assertFalse(result.isFailed());
successLatch.countDown();
}
});
Assert.assertTrue(headersLatch.await(30, TimeUnit.SECONDS));
Assert.assertTrue(successLatch.await(30, TimeUnit.SECONDS));
assertTrue(headersLatch.await(30, TimeUnit.SECONDS));
assertTrue(successLatch.await(30, TimeUnit.SECONDS));
Assert.assertEquals(1, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(1, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Test
public void test_FailedRequest_RemovesConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_FailedRequest_RemovesConnection(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
final CountDownLatch beginLatch = new CountDownLatch(1);
final CountDownLatch failureLatch = new CountDownLatch(2);
client.newRequest(host, port).scheme(scheme).listener(new Request.Listener.Adapter()
client.newRequest(host, port).scheme(scenario.getScheme()).listener(new Request.Listener.Adapter()
{
@Override
public void onBegin(Request request)
@ -149,39 +150,40 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertTrue(result.isFailed());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
failureLatch.countDown();
}
});
Assert.assertTrue(beginLatch.await(30, TimeUnit.SECONDS));
Assert.assertTrue(failureLatch.await(30, TimeUnit.SECONDS));
assertTrue(beginLatch.await(30, TimeUnit.SECONDS));
assertTrue(failureLatch.await(30, TimeUnit.SECONDS));
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Test
public void test_BadRequest_RemovesConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BadRequest_RemovesConnection(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Queue<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
final CountDownLatch successLatch = new CountDownLatch(3);
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.listener(new Request.Listener.Adapter()
{
@Override
@ -202,7 +204,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Override
public void onSuccess(Response response)
{
Assert.assertEquals(400, response.getStatus());
assertEquals(400, response.getStatus());
// 400 response also come with a Connection: close,
// so the connection is closed and removed
successLatch.countDown();
@ -211,38 +213,40 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Override
public void onComplete(Result result)
{
Assert.assertFalse(result.isFailed());
assertFalse(result.isFailed());
successLatch.countDown();
}
});
Assert.assertTrue(successLatch.await(30, TimeUnit.SECONDS));
assertTrue(successLatch.await(30, TimeUnit.SECONDS));
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Slow
@Test
public void test_BadRequest_WithSlowRequest_RemovesConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
@Tag("Slow")
@DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review
public void test_BadRequest_WithSlowRequest_RemovesConnection(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
final long delay = 1000;
final CountDownLatch successLatch = new CountDownLatch(3);
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.listener(new Request.Listener.Adapter()
{
@Override
@ -276,7 +280,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Override
public void onSuccess(Response response)
{
Assert.assertEquals(400, response.getStatus());
assertEquals(400, response.getStatus());
// 400 response also come with a Connection: close,
// so the connection is closed and removed
successLatch.countDown();
@ -285,55 +289,57 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Override
public void onComplete(Result result)
{
Assert.assertFalse(result.isFailed());
assertFalse(result.isFailed());
successLatch.countDown();
}
});
Assert.assertTrue(successLatch.await(delay * 30, TimeUnit.MILLISECONDS));
assertTrue(successLatch.await(delay * 30, TimeUnit.MILLISECONDS));
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Test
public void test_ConnectionFailure_RemovesConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_ConnectionFailure_RemovesConnection(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
server.stop();
final CountDownLatch failureLatch = new CountDownLatch(2);
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.onRequestFailure((request, failure) -> failureLatch.countDown())
.send(result ->
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
failureLatch.countDown();
});
Assert.assertTrue(failureLatch.await(30, TimeUnit.SECONDS));
assertTrue(failureLatch.await(30, TimeUnit.SECONDS));
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Test
public void test_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_ResponseWithConnectionCloseHeader_RemovesConnection(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -345,42 +351,43 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.send(new Response.Listener.Adapter()
{
@Override
public void onComplete(Result result)
{
Assert.assertFalse(result.isFailed());
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertFalse(result.isFailed());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
latch.countDown();
}
});
Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
assertTrue(latch.await(30, TimeUnit.SECONDS));
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Test
public void test_BigRequestContent_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_BigRequestContent_ResponseWithConnectionCloseHeader_RemovesConnection(Scenario scenario) throws Exception
{
try (StacklessLogging stackless = new StacklessLogging(HttpConnection.class))
try (StacklessLogging ignore = new StacklessLogging(HttpConnection.class))
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -393,14 +400,14 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
Log.getLogger(HttpConnection.class).info("Expecting java.lang.IllegalStateException: HttpParser{s=CLOSED,...");
@ -408,81 +415,84 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
ByteBuffer buffer = ByteBuffer.allocate(16 * 1024 * 1024);
Arrays.fill(buffer.array(),(byte)'x');
client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.content(new ByteBufferContentProvider(buffer))
.send(new Response.Listener.Adapter()
{
@Override
public void onComplete(Result result)
{
Assert.assertEquals(1, latch.getCount());
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(1, latch.getCount());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
latch.countDown();
}
});
Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
assertTrue(latch.await(30, TimeUnit.SECONDS));
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
server.stop();
}
}
@Slow
@Test
public void test_IdleConnection_IsClosed_OnRemoteClose() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
@Tag("Slow")
@DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review
public void test_IdleConnection_IsClosed_OnRemoteClose(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(30, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
connector.stop();
// Give the connection some time to process the remote close
TimeUnit.SECONDS.sleep(1);
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
@Test
public void testConnectionForHTTP10ResponseIsRemoved() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testConnectionForHTTP10ResponseIsRemoved(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port);
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
final Collection<Connection> idleConnections = connectionPool.getIdleConnections();
Assert.assertEquals(0, idleConnections.size());
assertEquals(0, idleConnections.size());
final Collection<Connection> activeConnections = connectionPool.getActiveConnections();
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, activeConnections.size());
client.setStrictEventOrdering(false);
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseBegin(response1 ->
{
// Simulate a HTTP 1.0 response has been received.
@ -490,9 +500,9 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
})
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
Assert.assertEquals(0, idleConnections.size());
Assert.assertEquals(0, activeConnections.size());
assertEquals(0, idleConnections.size());
assertEquals(0, activeConnections.size());
}
}

View File

@ -18,6 +18,13 @@
package org.eclipse.jetty.client;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
@ -37,26 +44,20 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpCookieTest extends AbstractHttpClientServerTest
{
private static final Cookie[] EMPTY_COOKIES = new Cookie[0];
public HttpCookieTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Test
public void test_CookieIsStored() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_CookieIsStored(Scenario scenario) throws Exception
{
final String name = "foo";
final String value = "bar";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -68,52 +69,54 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
String path = "/path";
String uri = scheme + "://" + host + ":" + port + path;
String uri = scenario.getScheme() + "://" + host + ":" + port + path;
Response response = client.GET(uri);
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
List<HttpCookie> cookies = client.getCookieStore().get(URI.create(uri));
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
assertNotNull(cookies);
assertEquals(1, cookies.size());
HttpCookie cookie = cookies.get(0);
Assert.assertEquals(name, cookie.getName());
Assert.assertEquals(value, cookie.getValue());
assertEquals(name, cookie.getName());
assertEquals(value, cookie.getValue());
}
@Test
public void test_CookieIsSent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_CookieIsSent(Scenario scenario) throws Exception
{
final String name = "foo";
final String value = "bar";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
Cookie[] cookies = request.getCookies();
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.length);
assertNotNull(cookies);
assertEquals(1, cookies.length);
Cookie cookie = cookies[0];
Assert.assertEquals(name, cookie.getName());
Assert.assertEquals(value, cookie.getValue());
assertEquals(name, cookie.getName());
assertEquals(value, cookie.getValue());
}
});
String host = "localhost";
int port = connector.getLocalPort();
String path = "/path";
String uri = scheme + "://" + host + ":" + port;
String uri = scenario.getScheme() + "://" + host + ":" + port;
HttpCookie cookie = new HttpCookie(name, value);
client.getCookieStore().add(URI.create(uri), cookie);
Response response = client.GET(scheme + "://" + host + ":" + port + path);
Assert.assertEquals(200, response.getStatus());
Response response = client.GET(scenario.getScheme() + "://" + host + ":" + port + path);
assertEquals(200, response.getStatus());
}
@Test
public void test_CookieWithoutValue() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_CookieWithoutValue(Scenario scenario) throws Exception
{
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -123,46 +126,48 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(client.getCookieStore().getCookies().isEmpty());
assertEquals(200, response.getStatus());
assertTrue(client.getCookieStore().getCookies().isEmpty());
}
@Test
public void test_PerRequestCookieIsSent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_PerRequestCookieIsSent(Scenario scenario) throws Exception
{
final String name = "foo";
final String value = "bar";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
Cookie[] cookies = request.getCookies();
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.length);
assertNotNull(cookies);
assertEquals(1, cookies.length);
Cookie cookie = cookies[0];
Assert.assertEquals(name, cookie.getName());
Assert.assertEquals(value, cookie.getValue());
assertEquals(name, cookie.getName());
assertEquals(value, cookie.getValue());
}
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.cookie(new HttpCookie(name, value))
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void test_SetCookieWithoutPath_RequestURIWithOneSegment() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SetCookieWithoutPath_RequestURIWithOneSegment(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue = "1";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -181,43 +186,44 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
case "/":
case "/foo":
case "/foo/bar":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue, cookie.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/bar").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_SetCookieWithoutPath_RequestURIWithTwoSegments() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SetCookieWithoutPath_RequestURIWithTwoSegments(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue = "1";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -236,48 +242,49 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
case "/":
case "/foo":
case "/foobar":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo/":
case "/foo/bar":
case "/foo/bar/baz":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue, cookie.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo/bar")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar", "/foo/bar/baz").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_SetCookieWithLongerPath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SetCookieWithLongerPath(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue = "1";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -297,47 +304,48 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
case "/":
case "/foo":
case "/foo/barbaz":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo/bar":
case "/foo/bar/":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue, cookie.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/", "/foo/barbaz").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_SetCookieWithShorterPath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SetCookieWithShorterPath(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue = "1";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -356,49 +364,50 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
{
case "/":
case "/foobar":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo":
case "/foo/":
case "/foo/bar":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue, cookie.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo/bar")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_TwoSetCookieWithSameNameSamePath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_TwoSetCookieWithSameNameSamePath(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue1 = "1";
String cookieValue2 = "2";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -419,48 +428,49 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
switch (target)
{
case "/":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo":
case "/foo/bar":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue2, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue2, cookie.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/bar").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_TwoSetCookieWithSameNameDifferentPath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_TwoSetCookieWithSameNameDifferentPath(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue1 = "1";
String cookieValue2 = "2";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -481,55 +491,56 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
switch (target)
{
case "/":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo":
case "/foo/bar":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie1 = cookies[0];
Assert.assertEquals(target, cookieName, cookie1.getName());
Assert.assertEquals(target, cookieValue1, cookie1.getValue());
assertEquals(cookieName, cookie1.getName(), target);
assertEquals(cookieValue1, cookie1.getValue(), target);
break;
case "/bar":
case "/bar/foo":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie2 = cookies[0];
Assert.assertEquals(target, cookieName, cookie2.getName());
Assert.assertEquals(target, cookieValue2, cookie2.getValue());
assertEquals(cookieName, cookie2.getName(), target);
assertEquals(cookieValue2, cookie2.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/bar", "/bar", "/bar/foo").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_TwoSetCookieWithSameNamePath1PrefixOfPath2() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_TwoSetCookieWithSameNamePath1PrefixOfPath2(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue1 = "1";
String cookieValue2 = "2";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -550,57 +561,58 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
switch (target)
{
case "/":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue1, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue1, cookie.getValue(), target);
break;
case "/foo/bar":
Assert.assertEquals(target, 2, cookies.length);
assertEquals(2, cookies.length, target);
Cookie cookie1 = cookies[0];
Cookie cookie2 = cookies[1];
Assert.assertEquals(target, cookieName, cookie1.getName());
Assert.assertEquals(target, cookieName, cookie2.getName());
assertEquals(cookieName, cookie1.getName(), target);
assertEquals(cookieName, cookie2.getName(), target);
Set<String> values = new HashSet<>();
values.add(cookie1.getValue());
values.add(cookie2.getValue());
Assert.assertThat(target, values, Matchers.containsInAnyOrder(cookieValue1, cookieValue2));
assertThat(target, values, containsInAnyOrder(cookieValue1, cookieValue2));
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/bar").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}
@Test
public void test_CookiePathWithTrailingSlash() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_CookiePathWithTrailingSlash(Scenario scenario) throws Exception
{
String headerName = "X-Request";
String cookieName = "a";
String cookieValue = "1";
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -620,37 +632,37 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
case "/":
case "/foo":
case "/foobar":
Assert.assertEquals(target, 0, cookies.length);
assertEquals(0, cookies.length, target);
break;
case "/foo/":
case "/foo/bar":
Assert.assertEquals(target, 1, cookies.length);
assertEquals(1, cookies.length, target);
Cookie cookie = cookies[0];
Assert.assertEquals(target, cookieName, cookie.getName());
Assert.assertEquals(target, cookieValue, cookie.getValue());
assertEquals(cookieName, cookie.getName(), target);
assertEquals(cookieValue, cookie.getValue(), target);
break;
default:
Assert.fail();
fail("Unrecognized Target: " + target);
}
}
}
});
ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/foo/bar")
.header(headerName, "0")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar").forEach(path ->
{
ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path(path)
.header(headerName, "1")
.timeout(5, TimeUnit.SECONDS));
Assert.assertEquals(HttpStatus.OK_200, r.getStatus());
assertEquals(HttpStatus.OK_200, r.getStatus());
});
}

View File

@ -18,6 +18,12 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
@ -38,57 +44,50 @@ import org.eclipse.jetty.client.util.ByteBufferContentProvider;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpRequestAbortTest extends AbstractHttpClientServerTest
{
public HttpRequestAbortTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortBeforeQueued(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testAbortBeforeQueued() throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
Exception failure = new Exception("oops");
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(5, TimeUnit.SECONDS);
request.abort(failure);
request.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertSame(failure, x.getCause());
// Make sure the pool is in a sane state.
HttpDestination destination = (HttpDestination)client.getDestination(scheme, "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(1, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(1, connectionPool.getIdleConnections().size());
}
});
assertSame(failure, x.getCause());
// Make sure the pool is in a sane state.
HttpDestination destination = (HttpDestination)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
assertEquals(1, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(1, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortOnQueued() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnQueued(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean begin = new AtomicBoolean();
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.listener(new Request.Listener.Adapter()
{
@Override
@ -106,36 +105,34 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
})
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
Assert.assertFalse(begin.get());
}
});
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, x.getCause());
assertFalse(begin.get());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortOnBegin() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnBegin(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch committed = new CountDownLatch(1);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.listener(new Request.Listener.Adapter()
{
@Override
@ -153,36 +150,33 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
})
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
Assert.assertFalse(committed.await(1, TimeUnit.SECONDS));
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, x.getCause());
assertFalse(committed.await(1, TimeUnit.SECONDS));
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortOnHeaders() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnHeaders(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch committed = new CountDownLatch(1);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.listener(new Request.Listener.Adapter()
{
@Override
@ -200,27 +194,24 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
})
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
Assert.assertFalse(committed.await(1, TimeUnit.SECONDS));
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, x.getCause());
assertFalse(committed.await(1, TimeUnit.SECONDS));
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortOnCommit() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnCommit(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
// Test can behave in 2 ways:
// A) the request is failed before the response arrived
@ -229,10 +220,9 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onRequestCommit(request ->
{
aborted.set(request.abort(cause));
@ -240,27 +230,24 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
})
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, x.getCause());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortOnCommitWithContent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnCommitWithContent(Scenario scenario) throws Exception
{
final AtomicReference<IOException> failure = new AtomicReference<>();
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -282,10 +269,10 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onRequestCommit(request ->
{
aborted.set(request.abort(cause));
@ -301,30 +288,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
})
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, x.getCause());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortOnContent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnContent(Scenario scenario) throws Exception
{
try (StacklessLogging suppressor = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class))
try (StacklessLogging ignore = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class))
{
CountDownLatch serverLatch = new CountDownLatch(1);
start(new EmptyServerHandler()
start(scenario, new EmptyServerHandler()
{
@Override
protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -344,10 +328,9 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onRequestContent((request, content) ->
{
aborted.set(request.abort(cause));
@ -363,30 +346,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
})
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, x.getCause());
Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS));
assertTrue(serverLatch.await(5, TimeUnit.SECONDS));
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
}
@Test(expected = InterruptedException.class)
public void testInterrupt() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testInterrupt(Scenario scenario) throws Exception
{
final long delay = 1000;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -406,7 +386,7 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
Request request = client.newRequest("localhost", connector.getLocalPort())
.timeout(3 * delay, TimeUnit.MILLISECONDS)
.scheme(scheme);
.scheme(scenario.getScheme());
final Thread thread = Thread.currentThread();
new Thread(() ->
@ -422,14 +402,15 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
}
}).start();
request.send();
assertThrows(InterruptedException.class, ()->request.send());
}
@Test
public void testAbortLongPoll() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortLongPoll(Scenario scenario) throws Exception
{
final long delay = 1000;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -449,7 +430,7 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
final Request request = client.newRequest("localhost", connector.getLocalPort())
.timeout(3 * delay, TimeUnit.MILLISECONDS)
.scheme(scheme);
.scheme(scenario.getScheme());
final Throwable cause = new Exception();
final AtomicBoolean aborted = new AtomicBoolean();
@ -474,23 +455,24 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
assertSame(cause, x.getCause());
}
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort());
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnections().size());
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getActiveConnections().size());
assertEquals(0, connectionPool.getIdleConnections().size());
}
@Test
public void testAbortLongPollAsync() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortLongPollAsync(Scenario scenario) throws Exception
{
final long delay = 1000;
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -511,12 +493,12 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
final Throwable cause = new Exception();
final CountDownLatch latch = new CountDownLatch(1);
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.timeout(3 * delay, TimeUnit.MILLISECONDS);
request.send(result ->
{
Assert.assertTrue(result.isFailed());
Assert.assertSame(cause, result.getFailure());
assertTrue(result.isFailed());
assertSame(cause, result.getFailure());
latch.countDown();
});
@ -524,13 +506,14 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
request.abort(cause);
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortConversation() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortConversation(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -565,20 +548,15 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
}
});
try
{
ExecutionException e = assertThrows(ExecutionException.class,()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/redirect")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
Assert.assertSame(cause, x.getCause());
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
if (aborted.get())
assertSame(cause, e.getCause());
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
@ -32,42 +35,38 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.util.DeferredContentProvider;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpResponseAbortTest extends AbstractHttpClientServerTest
{
public HttpResponseAbortTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnBegin(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testAbortOnBegin() throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseBegin(response -> response.abort(new Exception()))
.send(result ->
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortOnHeader() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnHeader(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseHeader((response, field) ->
{
response.abort(new Exception());
@ -75,33 +74,35 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest
})
.send(result ->
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortOnHeaders() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnHeaders(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseHeaders(response -> response.abort(new Exception()))
.send(result ->
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortOnContent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnContent(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -124,20 +125,21 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseContent((response, content) -> response.abort(new Exception()))
.send(result ->
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
latch.countDown();
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortOnContentBeforeRequestTermination() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnContentBeforeRequestTermination(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -162,7 +164,7 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest
final AtomicInteger completes = new AtomicInteger();
final CountDownLatch completeLatch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.content(contentProvider)
.onResponseContent((response, content) ->
{
@ -181,14 +183,14 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest
.send(result ->
{
completes.incrementAndGet();
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
completeLatch.countDown();
});
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
// Wait to be sure that the complete event is only notified once.
Thread.sleep(1000);
Assert.assertEquals(1, completes.get());
assertEquals(1, completes.get());
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
@ -34,9 +36,8 @@ import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTest
{
@ -46,18 +47,14 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
private final AtomicBoolean failureWasAsync = new AtomicBoolean();
private final AtomicBoolean completeWasSync = new AtomicBoolean();
public HttpResponseConcurrentAbortTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnBegin(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testAbortOnBegin() throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseBegin(new Response.BeginListener()
{
@Override
@ -67,19 +64,20 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
}
})
.send(new TestResponseListener());
Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(failureWasAsync.get());
Assert.assertTrue(completeWasSync.get());
assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureWasAsync.get());
assertTrue(completeWasSync.get());
}
@Test
public void testAbortOnHeader() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnHeader(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseHeader(new Response.HeaderListener()
{
@Override
@ -90,19 +88,20 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
}
})
.send(new TestResponseListener());
Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(failureWasAsync.get());
Assert.assertTrue(completeWasSync.get());
assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureWasAsync.get());
assertTrue(completeWasSync.get());
}
@Test
public void testAbortOnHeaders() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnHeaders(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseHeaders(new Response.HeadersListener()
{
@Override
@ -112,16 +111,17 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
}
})
.send(new TestResponseListener());
Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(failureWasAsync.get());
Assert.assertTrue(completeWasSync.get());
assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureWasAsync.get());
assertTrue(completeWasSync.get());
}
@Test
public void testAbortOnContent() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testAbortOnContent(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -134,7 +134,7 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
});
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.onResponseContent(new Response.ContentListener()
{
@Override
@ -144,10 +144,10 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
}
})
.send(new TestResponseListener());
Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(failureWasAsync.get());
Assert.assertTrue(completeWasSync.get());
assertTrue(callbackLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureWasAsync.get());
assertTrue(completeWasSync.get());
}
private void abort(final Response response)
@ -192,7 +192,7 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
completeLatch.countDown();
}
}

View File

@ -18,20 +18,24 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class InsufficientThreadsDetectionTest
{
@Test(expected = IllegalStateException.class)
public void testInsufficientThreads() throws Exception
@Test
public void testInsufficientThreads()
{
QueuedThreadPool clientThreads = new QueuedThreadPool(1);
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP(1), null);
httpClient.setExecutor(clientThreads);
httpClient.start();
assertThrows(IllegalStateException.class, ()->{
httpClient.start();
});
}
@Test
@ -42,17 +46,11 @@ public class InsufficientThreadsDetectionTest
httpClient1.setExecutor(clientThreads);
httpClient1.start();
try
{
assertThrows(IllegalStateException.class, ()->{
// Share the same thread pool with another instance.
HttpClient httpClient2 = new HttpClient(new HttpClientTransportOverHTTP(1), null);
httpClient2.setExecutor(clientThreads);
httpClient2.start();
Assert.fail();
}
catch (IllegalStateException expected)
{
// Expected.
}
});
}
}

View File

@ -18,12 +18,13 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.http.HttpStatus;
@ -35,39 +36,30 @@ import org.eclipse.jetty.util.SocketAddressResolver;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class LivelockTest
{
@Parameterized.Parameters(name = "server={0}, client={1}")
public static List<Object[]> data()
public static Stream<Arguments> modes()
{
List<Object[]> data = new ArrayList<>();
// Server-live-lock, Client-live-lock
data.add(new Object[] { true, true });
data.add(new Object[] { true, false });
data.add(new Object[] { false, true });
data.add(new Object[] { false, false });
return data;
return Stream.of(
// Server-live-lock, Client-live-lock
Arguments.of(true, true),
Arguments.of(true, false),
Arguments.of(false, true),
Arguments.of(false, false)
);
}
@Parameterized.Parameter(0)
public boolean serverLiveLock;
@Parameterized.Parameter(1)
public boolean clientLiveLock;
private Server server;
private ServerConnector connector;
private HttpClient client;
@Before
@BeforeEach
public void before() throws Exception
{
Handler handler = new EmptyServerHandler();
@ -80,7 +72,7 @@ public class LivelockTest
server.start();
}
@After
@AfterEach
public void after() throws Exception
{
if (client != null)
@ -89,8 +81,9 @@ public class LivelockTest
server.stop();
}
@Test
public void testLivelock() throws Exception
@ParameterizedTest(name = "{index} ==> serverLiveLock={0}, clientLiveLock={1}")
@MethodSource("modes")
public void testLivelock(boolean serverLiveLock, boolean clientLiveLock) throws Exception
{
// This test applies a moderate connect/request load (5/s) over 5 seconds,
// with a connect timeout of 1000, so any delayed connects will be detected.
@ -147,7 +140,7 @@ public class LivelockTest
});
sleep(pause);
}
Assert.assertTrue(latch.await(2 * pause * count, TimeUnit.MILLISECONDS));
assertTrue(latch.await(2 * pause * count, TimeUnit.MILLISECONDS));
// Exit the livelocks.
busy.set(false);

View File

@ -18,8 +18,11 @@
package org.eclipse.jetty.client;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class ProxyConfigurationTest
{
@ -27,7 +30,7 @@ public class ProxyConfigurationTest
public void testProxyMatchesWithoutIncludesWithoutExcludes() throws Exception
{
HttpProxy proxy = new HttpProxy("host", 0);
Assert.assertTrue(proxy.matches(new Origin("http", "any", 0)));
assertTrue(proxy.matches(new Origin("http", "any", 0)));
}
@Test
@ -36,9 +39,9 @@ public class ProxyConfigurationTest
HttpProxy proxy = new HttpProxy("host", 0);
proxy.getExcludedAddresses().add("1.2.3.4:5");
Assert.assertTrue(proxy.matches(new Origin("http", "any", 0)));
Assert.assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0)));
Assert.assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5)));
assertTrue(proxy.matches(new Origin("http", "any", 0)));
assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0)));
assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5)));
}
@Test
@ -47,9 +50,9 @@ public class ProxyConfigurationTest
HttpProxy proxy = new HttpProxy("host", 0);
proxy.getIncludedAddresses().add("1.2.3.4:5");
Assert.assertFalse(proxy.matches(new Origin("http", "any", 0)));
Assert.assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 0)));
Assert.assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 5)));
assertFalse(proxy.matches(new Origin("http", "any", 0)));
assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 0)));
assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 5)));
}
@Test
@ -59,9 +62,9 @@ public class ProxyConfigurationTest
proxy.getIncludedAddresses().add("1.2.3.4");
proxy.getExcludedAddresses().add("1.2.3.4:5");
Assert.assertFalse(proxy.matches(new Origin("http", "any", 0)));
Assert.assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0)));
Assert.assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5)));
assertFalse(proxy.matches(new Origin("http", "any", 0)));
assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0)));
assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5)));
}
@Test
@ -71,8 +74,8 @@ public class ProxyConfigurationTest
proxy.getIncludedAddresses().add("[1::2:3:4]");
proxy.getExcludedAddresses().add("[1::2:3:4]:5");
Assert.assertFalse(proxy.matches(new Origin("http", "any", 0)));
Assert.assertTrue(proxy.matches(new Origin("http", "1::2:3:4", 0)));
Assert.assertFalse(proxy.matches(new Origin("http", "1::2:3:4", 5)));
assertFalse(proxy.matches(new Origin("http", "any", 0)));
assertTrue(proxy.matches(new Origin("http", "[1::2:3:4]", 0)));
assertFalse(proxy.matches(new Origin("http", "[1::2:3:4]", 5)));
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -31,17 +33,13 @@ import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.client.http.HttpDestinationOverHTTP;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public class ServerConnectionCloseTest
{
@Rule
public final TestTracker tracker = new TestTracker();
private HttpClient client;
private void startClient() throws Exception
@ -53,7 +51,7 @@ public class ServerConnectionCloseTest
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
if (client != null)
@ -145,7 +143,7 @@ public class ServerConnectionCloseTest
socket.shutdownOutput();
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
// Give some time to process the connection.
Thread.sleep(1000);
@ -153,9 +151,9 @@ public class ServerConnectionCloseTest
// Connection should have been removed from pool.
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination("http", "localhost", port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getIdleConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnectionCount());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getIdleConnectionCount());
assertEquals(0, connectionPool.getActiveConnectionCount());
}
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
@ -26,17 +29,17 @@ import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class Socks4ProxyTest
{
private ServerSocketChannel server;
private HttpClient client;
@Before
@BeforeEach
public void prepare() throws Exception
{
server = ServerSocketChannel.open();
@ -46,7 +49,7 @@ public class Socks4ProxyTest
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
client.stop();
@ -84,24 +87,24 @@ public class Socks4ProxyTest
int socks4MessageLength = 9;
ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength);
int read = channel.read(buffer);
Assert.assertEquals(socks4MessageLength, read);
Assert.assertEquals(4, buffer.get(0) & 0xFF);
Assert.assertEquals(1, buffer.get(1) & 0xFF);
Assert.assertEquals(serverPort, buffer.getShort(2) & 0xFFFF);
Assert.assertEquals(ip1, buffer.get(4) & 0xFF);
Assert.assertEquals(ip2, buffer.get(5) & 0xFF);
Assert.assertEquals(ip3, buffer.get(6) & 0xFF);
Assert.assertEquals(ip4, buffer.get(7) & 0xFF);
Assert.assertEquals(0, buffer.get(8) & 0xFF);
assertEquals(socks4MessageLength, read);
assertEquals(4, buffer.get(0) & 0xFF);
assertEquals(1, buffer.get(1) & 0xFF);
assertEquals(serverPort, buffer.getShort(2) & 0xFFFF);
assertEquals(ip1, buffer.get(4) & 0xFF);
assertEquals(ip2, buffer.get(5) & 0xFF);
assertEquals(ip3, buffer.get(6) & 0xFF);
assertEquals(ip4, buffer.get(7) & 0xFF);
assertEquals(0, buffer.get(8) & 0xFF);
// Socks4 response.
channel.write(ByteBuffer.wrap(new byte[]{0, 0x5A, 0, 0, 0, 0, 0, 0}));
buffer = ByteBuffer.allocate(method.length() + 1 + path.length());
read = channel.read(buffer);
Assert.assertEquals(buffer.capacity(), read);
assertEquals(buffer.capacity(), read);
buffer.flip();
Assert.assertEquals(method + " " + path, StandardCharsets.UTF_8.decode(buffer).toString());
assertEquals(method + " " + path, StandardCharsets.UTF_8.decode(buffer).toString());
// Response
String response = "" +
@ -111,7 +114,7 @@ public class Socks4ProxyTest
"\r\n";
channel.write(ByteBuffer.wrap(response.getBytes("UTF-8")));
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
}
@ -143,7 +146,7 @@ public class Socks4ProxyTest
int socks4MessageLength = 9;
ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength);
int read = channel.read(buffer);
Assert.assertEquals(socks4MessageLength, read);
assertEquals(socks4MessageLength, read);
// Socks4 response, with split bytes.
byte[] chunk1 = new byte[]{0, 0x5A, 0};
@ -157,9 +160,9 @@ public class Socks4ProxyTest
buffer = ByteBuffer.allocate(method.length());
read = channel.read(buffer);
Assert.assertEquals(buffer.capacity(), read);
assertEquals(buffer.capacity(), read);
buffer.flip();
Assert.assertEquals(method, StandardCharsets.UTF_8.decode(buffer).toString());
assertEquals(method, StandardCharsets.UTF_8.decode(buffer).toString());
// Response
String response = "" +
@ -169,7 +172,7 @@ public class Socks4ProxyTest
"\r\n";
channel.write(ByteBuffer.wrap(response.getBytes("UTF-8")));
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -34,34 +36,15 @@ import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.client.http.HttpDestinationOverHTTP;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
@RunWith(Parameterized.class)
public class TLSServerConnectionCloseTest
{
@Parameterized.Parameters(name = "CloseMode: {0}")
public static Object[] parameters()
{
return new Object[]{CloseMode.NONE, CloseMode.CLOSE, CloseMode.ABRUPT};
}
@Rule
public final TestTracker tracker = new TestTracker();
private HttpClient client;
private final CloseMode closeMode;
public TLSServerConnectionCloseTest(CloseMode closeMode)
{
this.closeMode = closeMode;
}
private void startClient() throws Exception
{
@ -77,32 +60,35 @@ public class TLSServerConnectionCloseTest
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
if (client != null)
client.stop();
}
@Test
public void testServerSendsConnectionCloseWithoutContent() throws Exception
@ParameterizedTest
@EnumSource(CloseMode.class)
public void testServerSendsConnectionCloseWithoutContent(CloseMode closeMode) throws Exception
{
testServerSendsConnectionClose(false, "");
testServerSendsConnectionClose(closeMode, false, "");
}
@Test
public void testServerSendsConnectionCloseWithContent() throws Exception
@ParameterizedTest
@EnumSource(CloseMode.class)
public void testServerSendsConnectionCloseWithContent(CloseMode closeMode) throws Exception
{
testServerSendsConnectionClose(false, "data");
testServerSendsConnectionClose(closeMode, false, "data");
}
@Test
public void testServerSendsConnectionCloseWithChunkedContent() throws Exception
@ParameterizedTest
@EnumSource(CloseMode.class)
public void testServerSendsConnectionCloseWithChunkedContent(CloseMode closeMode) throws Exception
{
testServerSendsConnectionClose(true, "data");
testServerSendsConnectionClose(closeMode, true, "data");
}
private void testServerSendsConnectionClose(boolean chunked, String content) throws Exception
private void testServerSendsConnectionClose(final CloseMode closeMode, boolean chunked, String content) throws Exception
{
try (ServerSocket server = new ServerSocket(0))
{
@ -176,7 +162,7 @@ public class TLSServerConnectionCloseTest
}
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
// Give some time to process the connection.
Thread.sleep(1000);
@ -184,9 +170,9 @@ public class TLSServerConnectionCloseTest
// Connection should have been removed from pool.
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination("http", "localhost", port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getConnectionCount());
Assert.assertEquals(0, connectionPool.getIdleConnectionCount());
Assert.assertEquals(0, connectionPool.getActiveConnectionCount());
assertEquals(0, connectionPool.getConnectionCount());
assertEquals(0, connectionPool.getIdleConnectionCount());
assertEquals(0, connectionPool.getActiveConnectionCount());
}
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -35,50 +37,46 @@ import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
{
public ValidatingConnectionPoolTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Override
protected void startClient() throws Exception
protected void startClient(final Scenario scenario) throws Exception
{
long timeout = 1000;
HttpClientTransportOverHTTP transport = new HttpClientTransportOverHTTP(1);
transport.setConnectionPoolFactory(destination ->
new ValidatingConnectionPool(destination, destination.getHttpClient().getMaxConnectionsPerDestination(), destination, destination.getHttpClient().getScheduler(), timeout));
startClient(transport);
startClient(scenario, transport);
}
@Test
public void testRequestAfterValidation() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testRequestAfterValidation(Scenario scenario) throws Exception
{
start(new EmptyServerHandler());
start(scenario, new EmptyServerHandler());
client.setMaxConnectionsPerDestination(1);
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
// The second request should be sent after the validating timeout.
response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testServerClosesConnectionAfterRedirectWithoutConnectionCloseHeader() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testServerClosesConnectionAfterRedirectWithoutConnectionCloseHeader(Scenario scenario) throws Exception
{
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -88,7 +86,7 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
{
response.setStatus(HttpStatus.TEMPORARY_REDIRECT_307);
response.setContentLength(0);
response.setHeader(HttpHeader.LOCATION.asString(), scheme + "://localhost:" + connector.getLocalPort() + "/");
response.setHeader(HttpHeader.LOCATION.asString(), scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/");
response.flushBuffer();
baseRequest.getHttpChannel().getEndPoint().shutdownOutput();
}
@ -102,16 +100,17 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/redirect")
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithConnectionCloseHeader() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithConnectionCloseHeader(Scenario scenario) throws Exception
{
testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(new AbstractHandler()
testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -124,10 +123,11 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
});
}
@Test
public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithoutConnectionCloseHeader() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithoutConnectionCloseHeader(Scenario scenario) throws Exception
{
testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(new AbstractHandler()
testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(scenario, new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
@ -141,14 +141,14 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
});
}
private void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(Handler handler) throws Exception
private void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(final Scenario scenario, Handler handler) throws Exception
{
start(handler);
start(scenario, handler);
client.setMaxConnectionsPerDestination(1);
final CountDownLatch latch = new CountDownLatch(1);
Request request1 = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/one")
.onRequestBegin(r ->
{
@ -165,7 +165,7 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
request1.send(listener1);
Request request2 = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.path("/two");
FutureResponseListener listener2 = new FutureResponseListener(request2);
request2.send(listener2);
@ -175,9 +175,9 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest
latch.countDown();
ContentResponse response1 = listener1.get(5, TimeUnit.SECONDS);
Assert.assertEquals(200, response1.getStatus());
assertEquals(200, response1.getStatus());
ContentResponse response2 = listener2.get(5, TimeUnit.SECONDS);
Assert.assertEquals(200, response2.getStatus());
assertEquals(200, response2.getStatus());
}
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
@ -41,11 +45,11 @@ import org.eclipse.jetty.client.util.OutputStreamContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.util.FuturePromise;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled
public class Usage
{
@Test
@ -58,7 +62,7 @@ public class Usage
ContentResponse response = client.GET("http://localhost:8080/foo");
// Verify response status code
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
// Access headers
response.getHeaders().get("Content-Length");
@ -83,7 +87,7 @@ public class Usage
.timeout(20, TimeUnit.SECONDS);
ContentResponse response = request.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -110,10 +114,10 @@ public class Usage
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
Response response = responseRef.get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
@Test
@ -141,7 +145,7 @@ public class Usage
{
}
}).send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -163,8 +167,8 @@ public class Usage
// Wait for the response on the listener
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
}
@ -177,7 +181,7 @@ public class Usage
// One liner to upload files
Response response = client.newRequest("localhost", 8080).file(Paths.get("file_to_upload.txt")).send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -192,7 +196,7 @@ public class Usage
// Send a request for the cookie's domain
Response response = client.newRequest("host", 8080).send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -209,7 +213,7 @@ public class Usage
// One liner to send the request
ContentResponse response = client.newRequest(uri).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -227,7 +231,7 @@ public class Usage
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -277,7 +281,7 @@ public class Usage
.content(new InputStreamContentProvider(input))
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
@ -296,7 +300,7 @@ public class Usage
@Override
public void onComplete(Result result)
{
Assert.assertEquals(200, result.getResponse().getStatus());
assertEquals(200, result.getResponse().getStatus());
}
});

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client.http;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
@ -35,29 +38,20 @@ import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
{
public HttpDestinationOverHTTPTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_FirstAcquire_WithEmptyQueue(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
start(scenario, new EmptyServerHandler());
@Before
public void init() throws Exception
{
start(new EmptyServerHandler());
}
@Test
public void test_FirstAcquire_WithEmptyQueue() throws Exception
{
try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())))
try(HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())))
{
destination.start();
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
@ -67,14 +61,17 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
// There are no queued requests, so the newly created connection will be idle
connection = pollIdleConnection(connectionPool, 5, TimeUnit.SECONDS);
}
Assert.assertNotNull(connection);
assertNotNull(connection);
}
}
@Test
public void test_SecondAcquire_AfterFirstAcquire_WithEmptyQueue_ReturnsSameConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SecondAcquire_AfterFirstAcquire_WithEmptyQueue_ReturnsSameConnection(Scenario scenario) throws Exception
{
try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())))
start(scenario, new EmptyServerHandler());
try(HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())))
{
destination.start();
@ -84,21 +81,23 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
{
// There are no queued requests, so the newly created connection will be idle
connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS);
Assert.assertNotNull(connection1);
assertNotNull(connection1);
Connection connection2 = connectionPool.acquire();
Assert.assertSame(connection1, connection2);
assertSame(connection1, connection2);
}
}
}
@Test
public void test_SecondAcquire_ConcurrentWithFirstAcquire_WithEmptyQueue_CreatesTwoConnections() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_SecondAcquire_ConcurrentWithFirstAcquire_WithEmptyQueue_CreatesTwoConnections(Scenario scenario) throws Exception
{
CountDownLatch idleLatch = new CountDownLatch(1);
CountDownLatch latch = new CountDownLatch(1);
start(scenario, new EmptyServerHandler());
try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))
final CountDownLatch idleLatch = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(1);
HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))
{
@Override
protected ConnectionPool newConnectionPool(HttpClient client)
@ -121,37 +120,40 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
}
};
}
})
};
{
destination.start();
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
Connection connection1 = connectionPool.acquire();
// Make sure we entered idleCreated().
Assert.assertTrue(idleLatch.await(5, TimeUnit.SECONDS));
assertTrue(idleLatch.await(5, TimeUnit.SECONDS));
// There are no available existing connections, so acquire()
// returns null because we delayed idleCreated() above
Assert.assertNull(connection1);
assertNull(connection1);
// Second attempt also returns null because we delayed idleCreated() above.
Connection connection2 = connectionPool.acquire();
Assert.assertNull(connection2);
assertNull(connection2);
latch.countDown();
// There must be 2 idle connections.
Connection connection = pollIdleConnection(connectionPool, 5, TimeUnit.SECONDS);
Assert.assertNotNull(connection);
assertNotNull(connection);
connection = pollIdleConnection(connectionPool, 5, TimeUnit.SECONDS);
Assert.assertNotNull(connection);
assertNotNull(connection);
}
}
@Test
public void test_Acquire_Process_Release_Acquire_ReturnsSameConnection() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_Acquire_Process_Release_Acquire_ReturnsSameConnection(Scenario scenario) throws Exception
{
try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())))
start(scenario, new EmptyServerHandler());
try(HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())))
{
destination.start();
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
@ -159,22 +161,25 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
if (connection1 == null)
{
connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS);
Assert.assertNotNull(connection1);
assertNotNull(connection1);
// Acquire the connection to make it active.
Assert.assertSame("From idle", connection1, connectionPool.acquire());
assertSame(connection1, connectionPool.acquire(),"From idle");
}
destination.process(connection1);
destination.release(connection1);
Connection connection2 = connectionPool.acquire();
Assert.assertSame("After release", connection1, connection2);
assertSame(connection1, connection2,"After release");
}
}
@Test
public void test_IdleConnection_IdleTimeout() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_IdleConnection_IdleTimeout(Scenario scenario) throws Exception
{
start(scenario, new EmptyServerHandler());
long idleTimeout = 1000;
client.setIdleTimeout(idleTimeout);
@ -187,19 +192,22 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
{
connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS);
Assert.assertNotNull(connection1);
assertNotNull(connection1);
TimeUnit.MILLISECONDS.sleep(2 * idleTimeout);
connection1 = connectionPool.getIdleConnections().poll();
Assert.assertNull(connection1);
assertNull(connection1);
}
}
}
@Test
public void test_Request_Failed_If_MaxRequestsQueuedPerDestination_Exceeded() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void test_Request_Failed_If_MaxRequestsQueuedPerDestination_Exceeded(Scenario scenario) throws Exception
{
start(scenario, new EmptyServerHandler());
String scheme = scenario.getScheme();
int maxQueued = 1;
client.setMaxRequestsQueuedPerDestination(maxQueued);
client.setMaxConnectionsPerDestination(1);
@ -208,7 +216,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
// Send another request that is sent immediately
CountDownLatch successLatch = new CountDownLatch(1);
@ -224,8 +232,8 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
.path("/two")
.send(result ->
{
Assert.assertTrue(result.isFailed());
Assert.assertThat(result.getRequestFailure(), Matchers.instanceOf(RejectedExecutionException.class));
assertTrue(result.isFailed());
assertThat(result.getRequestFailure(), Matchers.instanceOf(RejectedExecutionException.class));
failureLatch.countDown();
});
})
@ -235,54 +243,60 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
successLatch.countDown();
});
Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureLatch.await(5, TimeUnit.SECONDS));
assertTrue(successLatch.await(5, TimeUnit.SECONDS));
}
@Test
public void testDestinationIsRemoved() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testDestinationIsRemoved(Scenario scenario) throws Exception
{
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
Destination destinationBefore = client.getDestination(scheme, host, port);
Destination destinationBefore = client.getDestination(scenario.getScheme(), host, port);
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString())
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
Destination destinationAfter = client.getDestination(scheme, host, port);
Assert.assertSame(destinationBefore, destinationAfter);
Destination destinationAfter = client.getDestination(scenario.getScheme(), host, port);
assertSame(destinationBefore, destinationAfter);
client.setRemoveIdleDestinations(true);
response = client.newRequest(host, port)
.scheme(scheme)
.scheme(scenario.getScheme())
.header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString())
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
destinationAfter = client.getDestination(scheme, host, port);
Assert.assertNotSame(destinationBefore, destinationAfter);
destinationAfter = client.getDestination(scenario.getScheme(), host, port);
assertNotSame(destinationBefore, destinationAfter);
}
@Test
public void testDestinationIsRemovedAfterConnectionError() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testDestinationIsRemovedAfterConnectionError(Scenario scenario) throws Exception
{
start(scenario, new EmptyServerHandler());
String host = "localhost";
int port = connector.getLocalPort();
client.setRemoveIdleDestinations(true);
Assert.assertTrue("Destinations of a fresh client must be empty", client.getDestinations().isEmpty());
assertTrue(client.getDestinations().isEmpty(), "Destinations of a fresh client must be empty");
server.stop();
Request request = client.newRequest(host, port).scheme(this.scheme);
Request request = client.newRequest(host, port).scheme(scenario.getScheme());
try
{
request.send();
Assert.fail("Request to a closed port must fail");
fail("Request to a closed port must fail");
}
catch (Exception expected)
{
@ -293,7 +307,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest
{
Thread.sleep(10);
}
Assert.assertTrue("Destination must be removed after connection error", client.getDestinations().isEmpty());
assertTrue(client.getDestinations().isEmpty(), "Destination must be removed after connection error");
}
private Connection pollIdleConnection(DuplexConnectionPool connectionPool, long time, TimeUnit unit) throws InterruptedException

View File

@ -18,14 +18,22 @@
package org.eclipse.jetty.client.http;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.EOFException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
@ -39,42 +47,29 @@ import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.Promise;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class HttpReceiverOverHTTPTest
{
@Rule
public final TestTracker tracker = new TestTracker();
@Parameterized.Parameter(0)
public HttpCompliance compliance;
private HttpClient client;
private HttpDestinationOverHTTP destination;
private ByteArrayEndPoint endPoint;
private HttpConnectionOverHTTP connection;
@Parameterized.Parameters
public static Collection<Object[]> parameters() throws Exception
public static Stream<Arguments> complianceModes() throws Exception
{
return Arrays.asList(
new Object[] { HttpCompliance.LEGACY },
new Object[] { HttpCompliance.RFC2616_LEGACY },
new Object[] { HttpCompliance.RFC7230_LEGACY }
);
return Stream.of(
HttpCompliance.LEGACY,
HttpCompliance.RFC2616_LEGACY,
HttpCompliance.RFC7230_LEGACY
).map(Arguments::of);
}
@Before
public void init() throws Exception
public void init(HttpCompliance compliance) throws Exception
{
client = new HttpClient();
client.setHttpCompliance(compliance);
@ -86,7 +81,7 @@ public class HttpReceiverOverHTTPTest
endPoint.setConnection(connection);
}
@After
@AfterEach
public void destroy() throws Exception
{
client.stop();
@ -98,15 +93,17 @@ public class HttpReceiverOverHTTPTest
FutureResponseListener listener = new FutureResponseListener(request);
HttpExchange exchange = new HttpExchange(destination, request, Collections.<Response.ResponseListener>singletonList(listener));
boolean associated = connection.getHttpChannel().associate(exchange);
Assert.assertTrue(associated);
assertTrue(associated);
exchange.requestComplete(null);
exchange.terminateRequest();
return exchange;
}
@Test
public void test_Receive_NoResponseContent() throws Exception
@ParameterizedTest
@MethodSource("complianceModes")
public void test_Receive_NoResponseContent(HttpCompliance compliance) throws Exception
{
init(compliance);
endPoint.addInput("" +
"HTTP/1.1 200 OK\r\n" +
"Content-length: 0\r\n" +
@ -116,19 +113,21 @@ public class HttpReceiverOverHTTPTest
connection.getHttpChannel().receive();
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("OK", response.getReason());
Assert.assertSame(HttpVersion.HTTP_1_1, response.getVersion());
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals("OK", response.getReason());
assertSame(HttpVersion.HTTP_1_1, response.getVersion());
HttpFields headers = response.getHeaders();
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("0", headers.get(HttpHeader.CONTENT_LENGTH));
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("0", headers.get(HttpHeader.CONTENT_LENGTH));
}
@Test
public void test_Receive_ResponseContent() throws Exception
@ParameterizedTest
@MethodSource("complianceModes")
public void test_Receive_ResponseContent(HttpCompliance compliance) throws Exception
{
init(compliance);
String content = "0123456789ABCDEF";
endPoint.addInput("" +
"HTTP/1.1 200 OK\r\n" +
@ -140,21 +139,23 @@ public class HttpReceiverOverHTTPTest
connection.getHttpChannel().receive();
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("OK", response.getReason());
Assert.assertSame(HttpVersion.HTTP_1_1, response.getVersion());
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals("OK", response.getReason());
assertSame(HttpVersion.HTTP_1_1, response.getVersion());
HttpFields headers = response.getHeaders();
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals(String.valueOf(content.length()), headers.get(HttpHeader.CONTENT_LENGTH));
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals(String.valueOf(content.length()), headers.get(HttpHeader.CONTENT_LENGTH));
String received = listener.getContentAsString(StandardCharsets.UTF_8);
Assert.assertEquals(content, received);
assertEquals(content, received);
}
@Test
public void test_Receive_ResponseContent_EarlyEOF() throws Exception
@ParameterizedTest
@MethodSource("complianceModes")
public void test_Receive_ResponseContent_EarlyEOF(HttpCompliance compliance) throws Exception
{
init(compliance);
String content1 = "0123456789";
String content2 = "ABCDEF";
endPoint.addInput("" +
@ -168,20 +169,15 @@ public class HttpReceiverOverHTTPTest
endPoint.addInputEOF();
connection.getHttpChannel().receive();
try
{
listener.get(5, TimeUnit.SECONDS);
Assert.fail();
}
catch (ExecutionException e)
{
Assert.assertTrue(e.getCause() instanceof EOFException);
}
ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS));
assertThat(e.getCause(), instanceOf(EOFException.class));
}
@Test
public void test_Receive_ResponseContent_IdleTimeout() throws Exception
@ParameterizedTest
@MethodSource("complianceModes")
public void test_Receive_ResponseContent_IdleTimeout(HttpCompliance compliance) throws Exception
{
init(compliance);
endPoint.addInput("" +
"HTTP/1.1 200 OK\r\n" +
"Content-length: 1\r\n" +
@ -194,20 +190,15 @@ public class HttpReceiverOverHTTPTest
Thread.sleep(100);
connection.onIdleExpired();
try
{
listener.get(5, TimeUnit.SECONDS);
Assert.fail();
}
catch (ExecutionException e)
{
Assert.assertTrue(e.getCause() instanceof TimeoutException);
}
ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS));
assertThat(e.getCause(), instanceOf(TimeoutException.class));
}
@Test
public void test_Receive_BadResponse() throws Exception
@ParameterizedTest
@MethodSource("complianceModes")
public void test_Receive_BadResponse(HttpCompliance compliance) throws Exception
{
init(compliance);
endPoint.addInput("" +
"HTTP/1.1 200 OK\r\n" +
"Content-length: A\r\n" +
@ -216,20 +207,15 @@ public class HttpReceiverOverHTTPTest
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
connection.getHttpChannel().receive();
try
{
listener.get(5, TimeUnit.SECONDS);
Assert.fail();
}
catch (ExecutionException e)
{
Assert.assertTrue(e.getCause() instanceof HttpResponseException);
}
ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS));
assertThat(e.getCause(), instanceOf(HttpResponseException.class));
}
@Test
public void test_FillInterested_RacingWith_BufferRelease() throws Exception
@ParameterizedTest
@MethodSource("complianceModes")
public void test_FillInterested_RacingWith_BufferRelease(HttpCompliance compliance) throws Exception
{
init(compliance);
connection = new HttpConnectionOverHTTP(endPoint, destination, new Promise.Adapter<>())
{
@Override
@ -247,7 +233,7 @@ public class HttpReceiverOverHTTPTest
{
// Verify that the buffer has been released
// before fillInterested() is called.
Assert.assertNull(getResponseBuffer());
assertNull(getResponseBuffer());
// Fill the endpoint so receive is called again.
endPoint.addInput("X");
super.fillInterested();
@ -270,7 +256,7 @@ public class HttpReceiverOverHTTPTest
connection.getHttpChannel().receive();
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.client.http;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
@ -33,31 +36,26 @@ import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.ByteBufferContentProvider;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.Promise;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
public class HttpSenderOverHTTPTest
{
@Rule
public final TestTracker tracker = new TestTracker();
private HttpClient client;
@Before
@BeforeEach
public void init() throws Exception
{
client = new HttpClient();
client.start();
}
@After
@AfterEach
public void destroy() throws Exception
{
client.stop();
@ -90,14 +88,14 @@ public class HttpSenderOverHTTPTest
connection.send(request, null);
String requestString = endPoint.takeOutputString();
Assert.assertTrue(requestString.startsWith("GET "));
Assert.assertTrue(requestString.endsWith("\r\n\r\n"));
Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
assertTrue(requestString.startsWith("GET "));
assertTrue(requestString.endsWith("\r\n\r\n"));
assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
assertTrue(successLatch.await(5, TimeUnit.SECONDS));
}
@Slow
@Test
@DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review
public void test_Send_NoRequestContent_IncompleteFlush() throws Exception
{
ByteArrayEndPoint endPoint = new ByteArrayEndPoint("", 16);
@ -121,8 +119,8 @@ public class HttpSenderOverHTTPTest
}
String requestString = builder.toString();
Assert.assertTrue(requestString.startsWith("GET "));
Assert.assertTrue(requestString.endsWith("\r\n\r\n"));
assertTrue(requestString.startsWith("GET "));
assertTrue(requestString.endsWith("\r\n\r\n"));
}
@Test
@ -149,12 +147,12 @@ public class HttpSenderOverHTTPTest
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
failureLatch.countDown();
}
});
Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureLatch.await(5, TimeUnit.SECONDS));
}
@Test
@ -179,7 +177,7 @@ public class HttpSenderOverHTTPTest
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
assertTrue(result.isFailed());
failureLatch.countDown();
}
});
@ -190,7 +188,7 @@ public class HttpSenderOverHTTPTest
// although it will fail because we shut down the output
endPoint.takeOutputString();
Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS));
assertTrue(failureLatch.await(5, TimeUnit.SECONDS));
}
@Test
@ -222,10 +220,10 @@ public class HttpSenderOverHTTPTest
connection.send(request, null);
String requestString = endPoint.takeOutputString();
Assert.assertTrue(requestString.startsWith("GET "));
Assert.assertTrue(requestString.endsWith("\r\n\r\n" + content));
Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
assertTrue(requestString.startsWith("GET "));
assertTrue(requestString.endsWith("\r\n\r\n" + content));
assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
assertTrue(successLatch.await(5, TimeUnit.SECONDS));
}
@Test
@ -258,10 +256,10 @@ public class HttpSenderOverHTTPTest
connection.send(request, null);
String requestString = endPoint.takeOutputString();
Assert.assertTrue(requestString.startsWith("GET "));
Assert.assertThat(requestString,Matchers.endsWith("\r\n\r\n" + content1 + content2));
Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
assertTrue(requestString.startsWith("GET "));
assertThat(requestString,Matchers.endsWith("\r\n\r\n" + content1 + content2));
assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
assertTrue(successLatch.await(5, TimeUnit.SECONDS));
}
@Test
@ -301,12 +299,12 @@ public class HttpSenderOverHTTPTest
connection.send(request, null);
String requestString = endPoint.takeOutputString();
Assert.assertTrue(requestString.startsWith("GET "));
assertTrue(requestString.startsWith("GET "));
String content = Integer.toHexString(content1.length()).toUpperCase(Locale.ENGLISH) + "\r\n" + content1 + "\r\n";
content += Integer.toHexString(content2.length()).toUpperCase(Locale.ENGLISH) + "\r\n" + content2 + "\r\n";
content += "0\r\n\r\n";
Assert.assertTrue(requestString.endsWith("\r\n\r\n" + content));
Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
assertTrue(requestString.endsWith("\r\n\r\n" + content));
assertTrue(headersLatch.await(5, TimeUnit.SECONDS));
assertTrue(successLatch.await(5, TimeUnit.SECONDS));
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client.jmx;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.Set;
@ -28,8 +30,8 @@ import javax.management.ObjectName;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HttpClientJMXTest
{
@ -51,16 +53,16 @@ public class HttpClientJMXTest
String domain = HttpClient.class.getPackage().getName();
ObjectName pattern = new ObjectName(domain + ":type=" + HttpClient.class.getSimpleName().toLowerCase(Locale.ENGLISH) + ",*");
Set<ObjectName> objectNames = mbeanServer.queryNames(pattern, null);
Assert.assertEquals(1, objectNames.size());
assertEquals(1, objectNames.size());
ObjectName objectName = objectNames.iterator().next();
Assert.assertEquals(name, objectName.getKeyProperty("context"));
assertEquals(name, objectName.getKeyProperty("context"));
// Verify that the context is inherited by the descendant components.
domain = SelectorManager.class.getPackage().getName();
pattern = new ObjectName(domain + ":*");
objectNames = mbeanServer.queryNames(pattern, null);
for (ObjectName oName : objectNames)
Assert.assertEquals(name, oName.getKeyProperty("context"));
assertEquals(name, oName.getKeyProperty("context"));
}
finally
{

View File

@ -18,6 +18,11 @@
package org.eclipse.jetty.client.ssl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.security.cert.Certificate;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -37,9 +42,9 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
/**
* In order to work, client authentication needs a certificate
@ -85,7 +90,7 @@ public class NeedWantClientAuthTest
return sslContextFactory;
}
@After
@AfterEach
public void dispose() throws Exception
{
if (client != null)
@ -108,7 +113,7 @@ public class NeedWantClientAuthTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
@Test
@ -127,8 +132,8 @@ public class NeedWantClientAuthTest
{
SSLSession session = event.getSSLEngine().getSession();
Certificate[] clientCerts = session.getPeerCertificates();
Assert.assertNotNull(clientCerts);
Assert.assertThat(clientCerts.length, Matchers.greaterThan(0));
assertNotNull(clientCerts);
assertThat(clientCerts.length, Matchers.greaterThan(0));
handshakeLatch.countDown();
}
catch (Throwable x)
@ -147,8 +152,8 @@ public class NeedWantClientAuthTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
assertEquals(HttpStatus.OK_200, response.getStatus());
assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
}
@Test
@ -180,7 +185,7 @@ public class NeedWantClientAuthTest
@Override
public void handshakeFailed(Event event, Throwable failure)
{
Assert.assertThat(failure, Matchers.instanceOf(SSLHandshakeException.class));
assertThat(failure, Matchers.instanceOf(SSLHandshakeException.class));
handshakeLatch.countDown();
}
});
@ -198,8 +203,8 @@ public class NeedWantClientAuthTest
}
});
Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
@ -218,8 +223,8 @@ public class NeedWantClientAuthTest
{
SSLSession session = event.getSSLEngine().getSession();
Certificate[] clientCerts = session.getPeerCertificates();
Assert.assertNotNull(clientCerts);
Assert.assertThat(clientCerts.length, Matchers.greaterThan(0));
assertNotNull(clientCerts);
assertThat(clientCerts.length, Matchers.greaterThan(0));
handshakeLatch.countDown();
}
catch (Throwable x)
@ -238,7 +243,7 @@ public class NeedWantClientAuthTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
assertEquals(HttpStatus.OK_200, response.getStatus());
assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
}
}

View File

@ -18,6 +18,12 @@
package org.eclipse.jetty.client.ssl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
@ -44,12 +50,13 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.JavaVersion;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
public class SslBytesClientTest extends SslBytesTest
{
@ -59,12 +66,11 @@ public class SslBytesClientTest extends SslBytesTest
private SSLServerSocket acceptor;
private SimpleProxy proxy;
@Before
// This whole test is very specific to how TLS < 1.3 works.
@DisabledOnJre( JRE.JAVA_11 )
@BeforeEach
public void init() throws Exception
{
// This whole test is very specific to how TLS < 1.3 works.
Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11));
threadPool = Executors.newCachedThreadPool();
sslContextFactory = new SslContextFactory(true);
@ -85,7 +91,7 @@ public class SslBytesClientTest extends SslBytesTest
logger.info(":{} <==> :{}", proxy.getPort(), serverPort);
}
@After
@AfterEach
public void destroy() throws Exception
{
if (acceptor != null)
@ -105,7 +111,7 @@ public class SslBytesClientTest extends SslBytesTest
FutureResponseListener listener = new FutureResponseListener(request);
request.scheme(HttpScheme.HTTPS.asString()).send(listener);
Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
try (SSLSocket server = (SSLSocket)acceptor.accept())
{
@ -119,46 +125,46 @@ public class SslBytesClientTest extends SslBytesTest
// Client Hello
TLSRecord record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToServer(record);
// Server Hello + Certificate + Server Done
record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToClient(record);
// Client Key Exchange
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToServer(record);
// Change Cipher Spec
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
proxy.flushToServer(record);
// Client Done
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToServer(record);
// Change Cipher Spec
record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
proxy.flushToClient(record);
// Server Done
record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToClient(record);
Assert.assertNull(handshake.get(5, TimeUnit.SECONDS));
assertNull(handshake.get(5, TimeUnit.SECONDS));
SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow();
// Read request
BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream(), StandardCharsets.UTF_8));
String line = reader.readLine();
Assert.assertTrue(line.startsWith("GET"));
assertTrue(line.startsWith("GET"));
while (line.length() > 0)
line = reader.readLine();
@ -168,10 +174,10 @@ public class SslBytesClientTest extends SslBytesTest
"Content-Length: 0\r\n" +
"\r\n").getBytes(StandardCharsets.UTF_8));
output.flush();
Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
}
@ -182,7 +188,7 @@ public class SslBytesClientTest extends SslBytesTest
FutureResponseListener listener = new FutureResponseListener(request);
request.scheme(HttpScheme.HTTPS.asString()).send(listener);
Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
try (SSLSocket server = (SSLSocket)acceptor.accept())
{
@ -195,13 +201,13 @@ public class SslBytesClientTest extends SslBytesTest
});
SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow();
Assert.assertNull(handshake.get(5, TimeUnit.SECONDS));
assertNull(handshake.get(5, TimeUnit.SECONDS));
// Read request
InputStream serverInput = server.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(serverInput, StandardCharsets.UTF_8));
String line = reader.readLine();
Assert.assertTrue(line.startsWith("GET"));
assertTrue(line.startsWith("GET"));
while (line.length() > 0)
line = reader.readLine();
@ -219,7 +225,7 @@ public class SslBytesClientTest extends SslBytesTest
"\r\n" +
content1).getBytes(StandardCharsets.UTF_8));
serverOutput.flush();
Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
// Renegotiate
Future<Object> renegotiation = threadPool.submit(() ->
@ -230,62 +236,54 @@ public class SslBytesClientTest extends SslBytesTest
// Renegotiation Handshake
TLSRecord record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToClient(record);
// Renegotiation Handshake
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToServer(record);
// Trigger a read to have the server write the final renegotiation steps
server.setSoTimeout(100);
try
{
serverInput.read();
Assert.fail();
}
catch (SocketTimeoutException x)
{
// Expected
}
assertThrows(SocketTimeoutException.class, ()->serverInput.read());
// Renegotiation Handshake
record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToClient(record);
// Renegotiation Change Cipher
record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
proxy.flushToClient(record);
// Renegotiation Handshake
record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToClient(record);
// Renegotiation Change Cipher
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType());
proxy.flushToServer(record);
// Renegotiation Handshake
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToServer(record);
Assert.assertNull(renegotiation.get(5, TimeUnit.SECONDS));
assertNull(renegotiation.get(5, TimeUnit.SECONDS));
// Complete the response
automaticProxyFlow = proxy.startAutomaticFlow();
serverOutput.write(data2);
serverOutput.flush();
Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
Assert.assertEquals(data1.length + data2.length, response.getContent().length);
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(data1.length + data2.length, response.getContent().length);
}
}
@ -298,7 +296,7 @@ public class SslBytesClientTest extends SslBytesTest
FutureResponseListener listener = new FutureResponseListener(request);
request.scheme(HttpScheme.HTTPS.asString()).send(listener);
Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS));
try (SSLSocket server = (SSLSocket)acceptor.accept())
{
@ -311,13 +309,13 @@ public class SslBytesClientTest extends SslBytesTest
});
SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow();
Assert.assertNull(handshake.get(5, TimeUnit.SECONDS));
assertNull(handshake.get(5, TimeUnit.SECONDS));
// Read request
InputStream serverInput = server.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(serverInput, StandardCharsets.UTF_8));
String line = reader.readLine();
Assert.assertTrue(line.startsWith("GET"));
assertTrue(line.startsWith("GET"));
while (line.length() > 0)
line = reader.readLine();
@ -335,7 +333,7 @@ public class SslBytesClientTest extends SslBytesTest
"\r\n" +
content1).getBytes(StandardCharsets.UTF_8));
serverOutput.flush();
Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS));
// Renegotiate
threadPool.submit(() ->
@ -346,14 +344,14 @@ public class SslBytesClientTest extends SslBytesTest
// Renegotiation Handshake
TLSRecord record = proxy.readFromServer();
Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
assertEquals(TLSRecord.Type.HANDSHAKE, record.getType());
proxy.flushToClient(record);
// Client sends close alert.
record = proxy.readFromClient();
Assert.assertEquals(TLSRecord.Type.ALERT, record.getType());
assertEquals(TLSRecord.Type.ALERT, record.getType());
record = proxy.readFromClient();
Assert.assertNull(record);
assertNull(record);
}
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client.ssl;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
@ -33,17 +35,12 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.Assert;
import org.junit.Rule;
public abstract class SslBytesTest
{
@Rule
public TestTracker tracker = new TestTracker();
protected final Logger logger = Log.getLogger(getClass());
public static class TLSRecord
@ -340,7 +337,7 @@ public abstract class SslBytesTest
logger.debug("Automatic flow C <-- S finished");
}
});
Assert.assertTrue(startLatch.await(5, TimeUnit.SECONDS));
assertTrue(startLatch.await(5, TimeUnit.SECONDS));
return new SslBytesServerTest.SimpleProxy.AutomaticFlow(stopLatch, clientToServer, serverToClient);
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.client.ssl;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.nio.ByteBuffer;
@ -34,8 +36,8 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class SslConnectionTest
{
@ -81,14 +83,6 @@ public class SslConnectionTest
// We want SSLHandshakeException to be thrown instead, because it is
// handled better (it is an IOException) by the Connection code that
// reads from the EndPoint.
try
{
sslEndPoint.fill(BufferUtil.EMPTY_BUFFER);
Assert.fail();
}
catch (SSLHandshakeException x)
{
// Expected.
}
assertThrows(SSLHandshakeException.class, ()->sslEndPoint.fill(BufferUtil.EMPTY_BUFFER));
}
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client.util;
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 java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.NoSuchElementException;
@ -29,22 +33,21 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.util.Callback;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DeferredContentProviderTest
{
private ExecutorService executor;
@Before
@BeforeEach
public void prepare() throws Exception
{
executor = Executors.newCachedThreadPool();
}
@After
@AfterEach
public void dispose() throws Exception
{
executor.shutdownNow();
@ -65,7 +68,7 @@ public class DeferredContentProviderTest
}
});
Assert.assertTrue(await(task, 5, TimeUnit.SECONDS));
assertTrue(await(task, 5, TimeUnit.SECONDS));
}
@Test
@ -87,14 +90,14 @@ public class DeferredContentProviderTest
});
// Wait until flush() blocks.
Assert.assertFalse(await(task, 1, TimeUnit.SECONDS));
assertFalse(await(task, 1, TimeUnit.SECONDS));
// Consume the content and succeed the callback.
iterator.next();
((Callback)iterator).succeeded();
// Flush should return.
Assert.assertTrue(await(task, 5, TimeUnit.SECONDS));
assertTrue(await(task, 5, TimeUnit.SECONDS));
}
@Test
@ -115,7 +118,7 @@ public class DeferredContentProviderTest
});
// Wait until flush() blocks.
Assert.assertTrue(await(task, 5, TimeUnit.SECONDS));
assertTrue(await(task, 5, TimeUnit.SECONDS));
}
@Test
@ -126,19 +129,11 @@ public class DeferredContentProviderTest
provider.close();
Assert.assertFalse(iterator.hasNext());
assertFalse(iterator.hasNext());
try
{
iterator.next();
Assert.fail();
}
catch (NoSuchElementException x)
{
// Expected
}
assertThrows(NoSuchElementException.class, ()->iterator.next());
Assert.assertFalse(iterator.hasNext());
assertFalse(iterator.hasNext());
}
private boolean await(Future<?> task, long time, TimeUnit unit) throws Exception

View File

@ -18,6 +18,11 @@
package org.eclipse.jetty.client.util;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@ -26,8 +31,8 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class InputStreamContentProviderTest
{
@ -54,20 +59,13 @@ public class InputStreamContentProviderTest
InputStreamContentProvider provider = new InputStreamContentProvider(stream);
Iterator<ByteBuffer> iterator = provider.iterator();
Assert.assertNotNull(iterator);
Assert.assertFalse(iterator.hasNext());
assertNotNull(iterator);
assertFalse(iterator.hasNext());
try
{
iterator.next();
Assert.fail();
}
catch (NoSuchElementException expected)
{
}
assertThrows(NoSuchElementException.class, () -> iterator.next());
Assert.assertFalse(iterator.hasNext());
Assert.assertTrue(closed.get());
assertFalse(iterator.hasNext());
assertTrue(closed.get());
}
@Test
@ -87,23 +85,16 @@ public class InputStreamContentProviderTest
InputStreamContentProvider provider = new InputStreamContentProvider(stream);
Iterator<ByteBuffer> iterator = provider.iterator();
Assert.assertNotNull(iterator);
assertNotNull(iterator);
ByteBuffer buffer = iterator.next();
Assert.assertNotNull(buffer);
assertNotNull(buffer);
try
{
iterator.next();
Assert.fail();
}
catch (NoSuchElementException expected)
{
}
assertThrows(NoSuchElementException.class, ()->iterator.next());
Assert.assertFalse(iterator.hasNext());
Assert.assertTrue(closed.get());
assertFalse(iterator.hasNext());
assertTrue(closed.get());
}
@Test
@ -129,19 +120,12 @@ public class InputStreamContentProviderTest
InputStreamContentProvider provider = new InputStreamContentProvider(stream);
Iterator<ByteBuffer> iterator = provider.iterator();
Assert.assertNotNull(iterator);
assertNotNull(iterator);
try
{
iterator.next();
Assert.fail();
}
catch (NoSuchElementException expected)
{
}
assertThrows(NoSuchElementException.class, ()->iterator.next());
Assert.assertFalse(iterator.hasNext());
Assert.assertTrue(closed.get());
assertFalse(iterator.hasNext());
assertTrue(closed.get());
}
@Test
@ -167,19 +151,12 @@ public class InputStreamContentProviderTest
InputStreamContentProvider provider = new InputStreamContentProvider(stream);
Iterator<ByteBuffer> iterator = provider.iterator();
Assert.assertNotNull(iterator);
Assert.assertTrue(iterator.hasNext());
assertNotNull(iterator);
assertTrue(iterator.hasNext());
try
{
iterator.next();
Assert.fail();
}
catch (NoSuchElementException expected)
{
}
assertThrows(NoSuchElementException.class, ()->iterator.next());
Assert.assertFalse(iterator.hasNext());
Assert.assertTrue(closed.get());
assertFalse(iterator.hasNext());
assertTrue(closed.get());
}
}

View File

@ -18,6 +18,12 @@
package org.eclipse.jetty.client.util;
import static org.eclipse.jetty.toolchain.test.StackUtils.supply;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -51,56 +57,52 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
{
public MultiPartContentProviderTest(SslContextFactory sslContextFactory)
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testEmptyMultiPart(Scenario scenario) throws Exception
{
super(sslContextFactory);
}
@Test
public void testEmptyMultiPart() throws Exception
{
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
Assert.assertEquals(0, parts.size());
assertEquals(0, parts.size());
}
});
MultiPartContentProvider multiPart = new MultiPartContentProvider();
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testSimpleField() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testSimpleField(Scenario scenario) throws Exception
{
String name = "field";
String value = "value";
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
Assert.assertEquals(1, parts.size());
assertEquals(1, parts.size());
Part part = parts.iterator().next();
Assert.assertEquals(name, part.getName());
Assert.assertEquals(value, IO.toString(part.getInputStream()));
assertEquals(name, part.getName());
assertEquals(value, IO.toString(part.getInputStream()));
}
});
@ -108,35 +110,36 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.addFieldPart(name, new StringContentProvider(value), null);
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testFieldWithOverridenContentType() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFieldWithOverridenContentType(Scenario scenario) throws Exception
{
String name = "field";
String value = "\u00e8";
Charset encoding = StandardCharsets.ISO_8859_1;
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
Assert.assertEquals(1, parts.size());
assertEquals(1, parts.size());
Part part = parts.iterator().next();
Assert.assertEquals(name, part.getName());
assertEquals(name, part.getName());
String contentType = part.getContentType();
Assert.assertNotNull(contentType);
assertNotNull(contentType);
int equal = contentType.lastIndexOf('=');
Charset charset = Charset.forName(contentType.substring(equal + 1));
Assert.assertEquals(encoding, charset);
Assert.assertEquals(value, IO.toString(part.getInputStream(), charset));
assertEquals(encoding, charset);
assertEquals(value, IO.toString(part.getInputStream(), charset));
}
});
@ -147,30 +150,31 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.addFieldPart(name, content, fields);
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testFieldDeferred() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFieldDeferred(Scenario scenario) throws Exception
{
String name = "field";
byte[] data = "Hello, World".getBytes(StandardCharsets.US_ASCII);
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
Assert.assertEquals(1, parts.size());
assertEquals(1, parts.size());
Part part = parts.iterator().next();
Assert.assertEquals(name, part.getName());
Assert.assertEquals("text/plain", part.getContentType());
Assert.assertArrayEquals(data, IO.readBytes(part.getInputStream()));
assertEquals(name, part.getName());
assertEquals("text/plain", part.getContentType());
assertArrayEquals(data, IO.readBytes(part.getInputStream()));
}
});
@ -180,13 +184,13 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.close();
CountDownLatch responseLatch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send(result ->
{
Assert.assertTrue(String.valueOf(result.getFailure()), result.isSucceeded());
Assert.assertEquals(200, result.getResponse().getStatus());
assertTrue(result.isSucceeded(),supply(result.getFailure()));
assertEquals(200, result.getResponse().getStatus());
responseLatch.countDown();
});
@ -197,30 +201,31 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
content.offer(ByteBuffer.wrap(data));
content.close();
Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
}
@Test
public void testFileFromInputStream() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFileFromInputStream(Scenario scenario) throws Exception
{
String name = "file";
String fileName = "upload.png";
String contentType = "image/png";
byte[] data = new byte[512];
new Random().nextBytes(data);
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
Assert.assertEquals(1, parts.size());
assertEquals(1, parts.size());
Part part = parts.iterator().next();
Assert.assertEquals(name, part.getName());
Assert.assertEquals(contentType, part.getContentType());
Assert.assertEquals(fileName, part.getSubmittedFileName());
Assert.assertEquals(data.length, part.getSize());
Assert.assertArrayEquals(data, IO.readBytes(part.getInputStream()));
assertEquals(name, part.getName());
assertEquals(contentType, part.getContentType());
assertEquals(fileName, part.getSubmittedFileName());
assertEquals(data.length, part.getSize());
assertArrayEquals(data, IO.readBytes(part.getInputStream()));
}
});
@ -240,17 +245,18 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.addFilePart(name, fileName, content, fields);
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send();
Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
Assert.assertEquals(200, response.getStatus());
assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
assertEquals(200, response.getStatus());
}
@Test
public void testFileFromPath() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFileFromPath(Scenario scenario) throws Exception
{
// Prepare a file to upload.
String data = "multipart_test_\u20ac";
@ -264,19 +270,19 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
String name = "file";
String contentType = "text/plain; charset=" + encoding.name();
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
Assert.assertEquals(1, parts.size());
assertEquals(1, parts.size());
Part part = parts.iterator().next();
Assert.assertEquals(name, part.getName());
Assert.assertEquals(contentType, part.getContentType());
Assert.assertEquals(tmpPath.getFileName().toString(), part.getSubmittedFileName());
Assert.assertEquals(Files.size(tmpPath), part.getSize());
Assert.assertEquals(data, IO.toString(part.getInputStream(), encoding));
assertEquals(name, part.getName());
assertEquals(contentType, part.getContentType());
assertEquals(tmpPath.getFileName().toString(), part.getSubmittedFileName());
assertEquals(Files.size(tmpPath), part.getSize());
assertEquals(data, IO.toString(part.getInputStream(), encoding));
}
});
@ -286,18 +292,19 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.addFilePart(name, tmpPath.getFileName().toString(), content, null);
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
Files.delete(tmpPath);
}
@Test
public void testFieldWithFile() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFieldWithFile(Scenario scenario) throws Exception
{
// Prepare a file to upload.
byte[] data = new byte[1024];
@ -316,13 +323,13 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
String contentType = "text/plain;charset=" + encoding.name();
String headerName = "foo";
String headerValue = "bar";
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List<Part> parts = new ArrayList<>(request.getParts());
Assert.assertEquals(2, parts.size());
assertEquals(2, parts.size());
Part fieldPart = parts.get(0);
Part filePart = parts.get(1);
if (!field.equals(fieldPart.getName()))
@ -332,16 +339,16 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
fieldPart = swap;
}
Assert.assertEquals(field, fieldPart.getName());
Assert.assertEquals(contentType, fieldPart.getContentType());
Assert.assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding));
Assert.assertEquals(headerValue, fieldPart.getHeader(headerName));
assertEquals(field, fieldPart.getName());
assertEquals(contentType, fieldPart.getContentType());
assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding));
assertEquals(headerValue, fieldPart.getHeader(headerName));
Assert.assertEquals(fileField, filePart.getName());
Assert.assertEquals("application/octet-stream", filePart.getContentType());
Assert.assertEquals(tmpPath.getFileName().toString(), filePart.getSubmittedFileName());
Assert.assertEquals(Files.size(tmpPath), filePart.getSize());
Assert.assertArrayEquals(data, IO.readBytes(filePart.getInputStream()));
assertEquals(fileField, filePart.getName());
assertEquals("application/octet-stream", filePart.getContentType());
assertEquals(tmpPath.getFileName().toString(), filePart.getSubmittedFileName());
assertEquals(Files.size(tmpPath), filePart.getSize());
assertArrayEquals(data, IO.readBytes(filePart.getInputStream()));
}
});
@ -352,30 +359,31 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.addFilePart(fileField, tmpPath.getFileName().toString(), new PathContentProvider(tmpPath), null);
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
Files.delete(tmpPath);
}
@Test
public void testFieldDeferredAndFileDeferred() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFieldDeferredAndFileDeferred(Scenario scenario) throws Exception
{
String value = "text";
Charset encoding = StandardCharsets.US_ASCII;
byte[] fileData = new byte[1024];
new Random().nextBytes(fileData);
start(new AbstractMultiPartHandler()
start(scenario, new AbstractMultiPartHandler()
{
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List<Part> parts = new ArrayList<>(request.getParts());
Assert.assertEquals(2, parts.size());
assertEquals(2, parts.size());
Part fieldPart = parts.get(0);
Part filePart = parts.get(1);
if (!"field".equals(fieldPart.getName()))
@ -385,12 +393,12 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
fieldPart = swap;
}
Assert.assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding));
assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding));
Assert.assertEquals("file", filePart.getName());
Assert.assertEquals("application/octet-stream", filePart.getContentType());
Assert.assertEquals("fileName", filePart.getSubmittedFileName());
Assert.assertArrayEquals(fileData, IO.readBytes(filePart.getInputStream()));
assertEquals("file", filePart.getName());
assertEquals("application/octet-stream", filePart.getContentType());
assertEquals("fileName", filePart.getSubmittedFileName());
assertArrayEquals(fileData, IO.readBytes(filePart.getInputStream()));
}
});
@ -401,13 +409,13 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.addFilePart("file", "fileName", fileContent, null);
CountDownLatch responseLatch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(multiPart)
.send(result ->
{
Assert.assertTrue(String.valueOf(result.getFailure()), result.isSucceeded());
Assert.assertEquals(200, result.getResponse().getStatus());
assertTrue(result.isSucceeded(),supply(result.getFailure()));
assertEquals(200, result.getResponse().getStatus());
responseLatch.countDown();
});
@ -425,7 +433,7 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest
multiPart.close();
Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
}
private static abstract class AbstractMultiPartHandler extends AbstractHandler

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.client.util;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -34,20 +38,15 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class TypedContentProviderTest extends AbstractHttpClientServerTest
{
public TypedContentProviderTest(SslContextFactory sslContextFactory)
{
super(sslContextFactory);
}
@Test
public void testFormContentProvider() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFormContentProvider(Scenario scenario) throws Exception
{
final String name1 = "a";
final String value1 = "1";
@ -55,19 +54,19 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest
final String value2 = "2";
final String value3 = "\u20AC";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals("POST", request.getMethod());
Assert.assertEquals(MimeTypes.Type.FORM_ENCODED.asString(), request.getContentType());
Assert.assertEquals(value1, request.getParameter(name1));
assertEquals("POST", request.getMethod());
assertEquals(MimeTypes.Type.FORM_ENCODED.asString(), request.getContentType());
assertEquals(value1, request.getParameter(name1));
String[] values = request.getParameterValues(name2);
Assert.assertNotNull(values);
Assert.assertEquals(2, values.length);
Assert.assertThat(values, Matchers.arrayContainingInAnyOrder(value2, value3));
assertNotNull(values);
assertEquals(2, values.length);
assertThat(values, Matchers.arrayContainingInAnyOrder(value2, value3));
}
});
@ -75,13 +74,14 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest
fields.put(name1, value1);
fields.add(name2, value2);
fields.add(name2, value3);
ContentResponse response = client.FORM(scheme + "://localhost:" + connector.getLocalPort(), fields);
ContentResponse response = client.FORM(scenario.getScheme() + "://localhost:" + connector.getLocalPort(), fields);
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testFormContentProviderWithDifferentContentType() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testFormContentProviderWithDifferentContentType(Scenario scenario) throws Exception
{
final String name1 = "a";
final String value1 = "1";
@ -93,50 +93,51 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest
final String content = FormContentProvider.convert(fields);
final String contentType = "text/plain;charset=UTF-8";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals("POST", request.getMethod());
Assert.assertEquals(contentType, request.getContentType());
Assert.assertEquals(content, IO.toString(request.getInputStream()));
assertEquals("POST", request.getMethod());
assertEquals(contentType, request.getContentType());
assertEquals(content, IO.toString(request.getInputStream()));
}
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.method(HttpMethod.POST)
.content(new FormContentProvider(fields))
.header(HttpHeader.CONTENT_TYPE, contentType)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
@Test
public void testTypedContentProviderWithNoContentType() throws Exception
@ParameterizedTest
@ArgumentsSource(ScenarioProvider.class)
public void testTypedContentProviderWithNoContentType(Scenario scenario) throws Exception
{
final String content = "data";
start(new AbstractHandler()
start(scenario, new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
Assert.assertEquals("GET", request.getMethod());
Assert.assertNotNull(request.getContentType());
Assert.assertEquals(content, IO.toString(request.getInputStream()));
assertEquals("GET", request.getMethod());
assertNotNull(request.getContentType());
assertEquals(content, IO.toString(request.getInputStream()));
}
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.scheme(scenario.getScheme())
.content(new StringContentProvider(null, content, StandardCharsets.UTF_8))
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
}

View File

@ -18,11 +18,13 @@
package org.eclipse.jetty.deploy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jetty.deploy.graph.Node;
import org.junit.Assert;
/**
* Binds to all lifecycle nodes, and tracks the order of the lifecycle nodes for testing purposes.
@ -69,12 +71,12 @@ public class AppLifeCyclePathCollector implements AppLifeCycle.Binding
System.out.println(path.getName());
}
Assert.assertEquals(msg + " / count",expectedOrder.size(),actualOrder.size());
assertEquals(expectedOrder.size(),actualOrder.size(),msg + " / count");
}
for (int i = 0, n = expectedOrder.size(); i < n; i++)
{
Assert.assertEquals(msg + "[" + i + "]",expectedOrder.get(i),actualOrder.get(i).getName());
assertEquals(expectedOrder.get(i),actualOrder.get(i).getName(),msg + "[" + i + "]");
}
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.deploy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@ -26,18 +29,18 @@ import java.util.List;
import org.eclipse.jetty.deploy.graph.GraphOutputDot;
import org.eclipse.jetty.deploy.graph.Node;
import org.eclipse.jetty.deploy.graph.Path;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* Just an overly picky test case to validate the potential paths.
*/
@ExtendWith(WorkDirExtension.class)
public class AppLifeCycleTest
{
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
private void assertNoPath(String from, String to)
{
@ -50,7 +53,7 @@ public class AppLifeCycleTest
Node toNode = lifecycle.getNodeByName(to);
Path actual = lifecycle.getPath(fromNode,toNode);
String msg = "LifeCycle path from " + from + " to " + to;
Assert.assertNotNull(msg + " should never be null",actual);
assertNotNull(actual,msg + " should never be null");
if (expected.size() != actual.nodes())
{
@ -67,12 +70,12 @@ public class AppLifeCycleTest
System.out.println(path.getName());
}
Assert.assertEquals(msg + " / count",expected.size(),actual.nodes());
assertEquals(expected.size(),actual.nodes(),msg + " / count");
}
for (int i = 0, n = expected.size(); i < n; i++)
{
Assert.assertEquals(msg + "[" + i + "]",expected.get(i),actual.getNode(i).getName());
assertEquals(expected.get(i),actual.getNode(i).getName(),msg + "[" + i + "]");
}
}

View File

@ -27,7 +27,7 @@ import javax.management.ObjectName;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class DeploymentManagerLifeCyclePathTest
{

View File

@ -18,20 +18,23 @@
package org.eclipse.jetty.deploy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Collection;
import java.util.Set;
import org.eclipse.jetty.deploy.test.XmlConfiguredJetty;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WorkDirExtension.class)
public class DeploymentManagerTest
{
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
@Test
public void testReceiveApp() throws Exception
@ -53,13 +56,13 @@ public class DeploymentManagerTest
// Test app tracking
Collection<App> apps = depman.getApps();
Assert.assertNotNull("Should never be null",apps);
Assert.assertEquals("Expected App Count",1,apps.size());
assertNotNull(apps, "Should never be null");
assertEquals(1, apps.size(), "Expected App Count");
// Test app get
App actual = depman.getAppByOriginId("mock-foo-webapp-1.war");
Assert.assertNotNull("Should have gotten app (by id)",actual);
Assert.assertEquals("Should have gotten app (by id)","mock-foo-webapp-1.war",actual.getOriginId());
assertNotNull(actual, "Should have gotten app (by id)");
assertEquals("mock-foo-webapp-1.war", actual.getOriginId(), "Should have gotten app (by id)");
}
@Test
@ -70,12 +73,12 @@ public class DeploymentManagerTest
depman.addLifeCycleBinding(pathtracker);
Set<AppLifeCycle.Binding> allbindings = depman.getLifeCycle().getBindings();
Assert.assertNotNull("All Bindings should never be null",allbindings);
Assert.assertEquals("All Bindings.size",1,allbindings.size());
assertNotNull(allbindings, "All Bindings should never be null");
assertEquals(1, allbindings.size(), "All Bindings.size");
Set<AppLifeCycle.Binding> deploybindings = depman.getLifeCycle().getBindings("deploying");
Assert.assertNotNull("'deploying' Bindings should not be null",deploybindings);
Assert.assertEquals("'deploying' Bindings.size",1,deploybindings.size());
assertNotNull(deploybindings, "'deploying' Bindings should not be null");
assertEquals(1, deploybindings.size(), "'deploying' Bindings.size");
}
@Test
@ -84,7 +87,7 @@ public class DeploymentManagerTest
XmlConfiguredJetty jetty = null;
try
{
jetty = new XmlConfiguredJetty(testdir);
jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir());
jetty.addConfiguration("jetty.xml");
jetty.addConfiguration("jetty-http.xml");
jetty.addConfiguration("jetty-deploymgr-contexts.xml");

View File

@ -18,39 +18,39 @@
package org.eclipse.jetty.deploy.bindings;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.isIn;
import java.io.File;
import java.util.List;
import org.eclipse.jetty.deploy.providers.ScanningAppProvider;
import org.eclipse.jetty.deploy.test.XmlConfiguredJetty;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.PathAssert;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.io.File;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Tests {@link ScanningAppProvider} as it starts up for the first time.
*/
@ExtendWith(WorkDirExtension.class)
public class GlobalWebappConfigBindingTest
{
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
private static XmlConfiguredJetty jetty;
@Before
@BeforeEach
public void setupEnvironment() throws Exception
{
jetty = new XmlConfiguredJetty(testdir);
jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir());
jetty.addConfiguration("jetty.xml");
jetty.addConfiguration("jetty-http.xml");
@ -60,7 +60,7 @@ public class GlobalWebappConfigBindingTest
}
@After
@AfterEach
public void teardownEnvironment() throws Exception
{
// Stop jetty.
@ -81,15 +81,16 @@ public class GlobalWebappConfigBindingTest
jetty.start();
List<WebAppContext> contexts = jetty.getWebAppContexts();
Assert.assertThat("List of Contexts", contexts, hasSize(greaterThan(0)));
assertThat("List of Contexts", contexts, hasSize(greaterThan(0)));
WebAppContext context = contexts.get(0);
Assert.assertNotNull("Context should not be null",context);
assertNotNull(context, "Context should not be null");
String currentClasses[] = context.getServerClasses();
String addedClass = "org.eclipse.foo."; // What was added by the binding
Assert.assertThat("Current Server Classes",addedClass,isIn(currentClasses));
assertThat("Current Server Classes",addedClass,isIn(currentClasses));
// boolean jndiPackage = false;
@ -103,6 +104,6 @@ public class GlobalWebappConfigBindingTest
// }
// }
//
// Assert.assertFalse(jndiPackage);
// assertFalse(jndiPackage);
}
}

View File

@ -18,8 +18,10 @@
package org.eclipse.jetty.deploy.graph;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class GraphTest
{
@ -36,19 +38,19 @@ public class GraphTest
Path path = new Path();
Assert.assertEquals(0, path.nodes());
Assert.assertEquals(null,path.firstNode());
Assert.assertEquals(null,path.lastNode());
assertEquals(0, path.nodes());
assertEquals(null,path.firstNode());
assertEquals(null,path.lastNode());
path.add(new Edge(nodeA ,nodeB));
Assert.assertEquals(2,path.nodes());
Assert.assertEquals(nodeA,path.firstNode());
Assert.assertEquals(nodeB,path.lastNode());
assertEquals(2,path.nodes());
assertEquals(nodeA,path.firstNode());
assertEquals(nodeB,path.lastNode());
path.add(new Edge(nodeB ,nodeC));
Assert.assertEquals(3,path.nodes());
Assert.assertEquals(nodeA,path.firstNode());
Assert.assertEquals(nodeC,path.lastNode());
assertEquals(3,path.nodes());
assertEquals(nodeA,path.firstNode());
assertEquals(nodeC,path.lastNode());
}
@Test
@ -56,10 +58,10 @@ public class GraphTest
{
Graph graph = new Graph();
graph.addNode(nodeA);
Assert.assertEquals(1,graph.getNodes().size());
Assert.assertEquals(0,graph.getEdges().size());
assertEquals(1,graph.getNodes().size());
assertEquals(0,graph.getEdges().size());
Path path = graph.getPath(nodeA,nodeA);
Assert.assertEquals(0,path.nodes());
assertEquals(0,path.nodes());
}
@Test
@ -67,10 +69,10 @@ public class GraphTest
{
Graph graph = new Graph();
graph.addEdge(new Edge(nodeA,nodeB));
Assert.assertEquals(2,graph.getNodes().size());
Assert.assertEquals(1,graph.getEdges().size());
assertEquals(2,graph.getNodes().size());
assertEquals(1,graph.getEdges().size());
Path path = graph.getPath(nodeA,nodeB);
Assert.assertEquals(2,path.nodes());
assertEquals(2,path.nodes());
}
@Test
@ -80,14 +82,14 @@ public class GraphTest
graph.addEdge(new Edge(nodeA,nodeB));
graph.addEdge(new Edge(nodeA,nodeC));
graph.addEdge(new Edge(nodeB,nodeC));
Assert.assertEquals(3,graph.getNodes().size());
Assert.assertEquals(3,graph.getEdges().size());
assertEquals(3,graph.getNodes().size());
assertEquals(3,graph.getEdges().size());
Path path = graph.getPath(nodeA,nodeB);
Assert.assertEquals(2,path.nodes());
assertEquals(2,path.nodes());
path = graph.getPath(nodeA,nodeC);
Assert.assertEquals(2,path.nodes());
assertEquals(2,path.nodes());
path = graph.getPath(nodeB,nodeC);
Assert.assertEquals(2,path.nodes());
assertEquals(2,path.nodes());
}
@ -99,13 +101,13 @@ public class GraphTest
graph.addEdge(new Edge(nodeB,nodeC));
graph.addEdge(new Edge(nodeA,nodeD));
graph.addEdge(new Edge(nodeD,nodeC));
Assert.assertEquals(4,graph.getNodes().size());
Assert.assertEquals(4,graph.getEdges().size());
assertEquals(4,graph.getNodes().size());
assertEquals(4,graph.getEdges().size());
Path path = graph.getPath(nodeA,nodeC);
Assert.assertEquals(3,path.nodes());
assertEquals(3,path.nodes());
path = graph.getPath(nodeC,nodeA);
Assert.assertEquals(null,path);
assertEquals(null,path);
}
@ -117,19 +119,19 @@ public class GraphTest
graph.addEdge(new Edge(nodeB,nodeC));
graph.addEdge(new Edge(nodeC,nodeD));
graph.addEdge(new Edge(nodeD,nodeA));
Assert.assertEquals(4,graph.getNodes().size());
Assert.assertEquals(4,graph.getEdges().size());
assertEquals(4,graph.getNodes().size());
assertEquals(4,graph.getEdges().size());
Path path = graph.getPath(nodeA,nodeB);
Assert.assertEquals(2,path.nodes());
assertEquals(2,path.nodes());
path = graph.getPath(nodeA,nodeC);
Assert.assertEquals(3,path.nodes());
assertEquals(3,path.nodes());
path = graph.getPath(nodeA,nodeD);
Assert.assertEquals(4,path.nodes());
assertEquals(4,path.nodes());
graph.addNode(nodeE);
path = graph.getPath(nodeA,nodeE);
Assert.assertEquals(null,path);
assertEquals(null,path);
}

View File

@ -18,49 +18,47 @@
package org.eclipse.jetty.deploy.providers;
import static org.junit.jupiter.api.condition.OS.WINDOWS;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.deploy.AppProvider;
import org.eclipse.jetty.deploy.DeploymentManager;
import org.eclipse.jetty.deploy.test.XmlConfiguredJetty;
import org.eclipse.jetty.toolchain.test.OS;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.Scanner;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* Similar in scope to {@link ScanningAppProviderStartupTest}, except is concerned with the modification of existing
* deployed webapps due to incoming changes identified by the {@link ScanningAppProvider}.
*/
@ExtendWith(WorkDirExtension.class)
public class ScanningAppProviderRuntimeUpdatesTest
{
private static final Logger LOG = Log.getLogger(ScanningAppProviderRuntimeUpdatesTest.class);
@Rule
public TestTracker tracker = new TestTracker();
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
private static XmlConfiguredJetty jetty;
private final AtomicInteger _scans = new AtomicInteger();
private int _providers;
@Before
@BeforeEach
public void setupEnvironment() throws Exception
{
testdir.ensureEmpty();
Resource.setDefaultUseCaches(false);
jetty = new XmlConfiguredJetty(testdir);
jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir());
jetty.addConfiguration("jetty.xml");
jetty.addConfiguration("jetty-http.xml");
jetty.addConfiguration("jetty-deploymgr-contexts.xml");
@ -91,7 +89,7 @@ public class ScanningAppProviderRuntimeUpdatesTest
}
@After
@AfterEach
public void teardownEnvironment() throws Exception
{
// Stop jetty.
@ -160,14 +158,9 @@ public class ScanningAppProviderRuntimeUpdatesTest
* @throws Exception on test failure
*/
@Test
@DisabledOnOs(WINDOWS) // This test will not work on Windows as second war file would, not be written over the first one because of a file lock
public void testAfterStartupThenUpdateContext() throws Exception
{
// This test will not work on Windows as second war file would
// not be written over the first one because of a file lock
Assume.assumeTrue(!OS.IS_WINDOWS);
Assume.assumeTrue(!OS.IS_OSX); // build server has issues with finding itself apparently
jetty.copyWebapp("foo-webapp-1.war","foo.war");
jetty.copyWebapp("foo.xml","foo.xml");

View File

@ -19,25 +19,26 @@
package org.eclipse.jetty.deploy.providers;
import org.eclipse.jetty.deploy.test.XmlConfiguredJetty;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* Tests {@link ScanningAppProvider} as it starts up for the first time.
*/
@ExtendWith(WorkDirExtension.class)
public class ScanningAppProviderStartupTest
{
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
private static XmlConfiguredJetty jetty;
@Before
@BeforeEach
public void setupEnvironment() throws Exception
{
jetty = new XmlConfiguredJetty(testdir);
jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir());
jetty.addConfiguration("jetty.xml");
jetty.addConfiguration("jetty-http.xml");
jetty.addConfiguration("jetty-deploymgr-contexts.xml");
@ -53,7 +54,7 @@ public class ScanningAppProviderStartupTest
jetty.start();
}
@After
@AfterEach
public void teardownEnvironment() throws Exception
{
// Stop jetty.

View File

@ -18,8 +18,9 @@
package org.eclipse.jetty.deploy.providers;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.nio.file.FileSystemException;
@ -29,26 +30,26 @@ import java.util.Arrays;
import org.eclipse.jetty.deploy.test.XmlConfiguredJetty;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@Ignore("See issue #1200")
@Disabled("See issue #1200")
@ExtendWith(WorkDirExtension.class)
public class WebAppProviderTest
{
@Rule
public TestingDir testdir = new TestingDir();
public WorkDir testdir;
private static XmlConfiguredJetty jetty;
private boolean symlinkSupported = false;
@Before
@BeforeEach
public void setupEnvironment() throws Exception
{
jetty = new XmlConfiguredJetty(testdir);
jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir());
jetty.addConfiguration("jetty.xml");
jetty.addConfiguration("jetty-http.xml");
jetty.addConfiguration("jetty-deploy-wars.xml");
@ -77,7 +78,7 @@ public class WebAppProviderTest
jetty.start();
}
@After
@AfterEach
public void teardownEnvironment() throws Exception
{
// Stop jetty.
@ -97,7 +98,7 @@ public class WebAppProviderTest
assertDirNotExists("root of work directory",workDir,"jsp");
// Test for correct behaviour
assertTrue("Should have generated directory in work directory: " + workDir,hasJettyGeneratedPath(workDir,"foo.war"));
assertTrue(hasJettyGeneratedPath(workDir,"foo.war"),"Should have generated directory in work directory: " + workDir);
}
@Test
@ -107,15 +108,15 @@ public class WebAppProviderTest
// Check for path
File barLink = jetty.getJettyDir("webapps/bar.war");
assertTrue("bar.war link exists: " + barLink.toString(), barLink.exists());
assertTrue("bar.war link isFile: " + barLink.toString(), barLink.isFile());
assertTrue(barLink.exists(),"bar.war link exists: " + barLink.toString());
assertTrue(barLink.isFile(), "bar.war link isFile: " + barLink.toString());
// Check Server for expected Handlers
jetty.assertWebAppContextsExists("/bar", "/foo");
// Test for expected work/temp directory behaviour
File workDir = jetty.getJettyDir("workish");
assertTrue("Should have generated directory in work directory: " + workDir,hasJettyGeneratedPath(workDir,"bar.war"));
assertTrue(hasJettyGeneratedPath(workDir,"bar.war"),"Should have generated directory in work directory: " + workDir);
}
private static boolean hasJettyGeneratedPath(File basedir, String expectedWarFilename)
@ -139,6 +140,6 @@ public class WebAppProviderTest
public static void assertDirNotExists(String msg, File workDir, String subdir)
{
File dir = new File(workDir,subdir);
Assert.assertFalse("Should not have " + subdir + " in " + msg + " - " + workDir,dir.exists());
assertFalse(dir.exists(),"Should not have " + subdir + " in " + msg + " - " + workDir);
}
}

View File

@ -18,7 +18,12 @@
package org.eclipse.jetty.deploy.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
@ -31,6 +36,7 @@ import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -45,13 +51,12 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.PathAssert;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.junit.Assert;
/**
* Allows for setting up a Jetty server for testing based on XML configuration files.
@ -65,12 +70,12 @@ public class XmlConfiguredJetty
private String _scheme = HttpScheme.HTTP.asString();
private File _jettyHome;
public XmlConfiguredJetty(TestingDir testdir) throws IOException
public XmlConfiguredJetty(Path testdir) throws IOException
{
_xmlConfigurations = new ArrayList<>();
Properties properties = new Properties();
String jettyHomeBase = testdir.getPath().toString();
String jettyHomeBase = testdir.toString();
// Ensure we have a new (pristene) directory to work with.
int idx = 0;
_jettyHome = new File(jettyHomeBase + "#" + idx);
@ -156,7 +161,7 @@ public class XmlConfiguredJetty
{
System.err.println("WebAppContext should not exist:\n" + context);
}
Assert.assertEquals("Contexts.size",0,contexts.size());
assertEquals(0, contexts.size(), "Contexts.size");
}
}
@ -181,9 +186,8 @@ public class XmlConfiguredJetty
public void assertResponseContains(String path, String needle) throws IOException
{
// System.err.println("Issuing request to " + path);
String content = getResponse(path);
Assert.assertTrue("Content should contain <" + needle + ">, instead got <" + content + ">",content.contains(needle));
assertThat(content, containsString(needle));
}
public void assertWebAppContextsExists(String... expectedContextPaths)
@ -201,7 +205,7 @@ public class XmlConfiguredJetty
{
System.err.printf("%s ## %s%n",context.getContextPath(),context);
}
Assert.assertEquals("Contexts.size",expectedContextPaths.length,contexts.size());
assertEquals(expectedContextPaths.length, contexts.size(), "Contexts.size");
}
for (String expectedPath : expectedContextPaths)
@ -212,11 +216,11 @@ public class XmlConfiguredJetty
if (context.getContextPath().equals(expectedPath))
{
found = true;
Assert.assertThat("Context[" + context.getContextPath() + "].state", context.getState(), is("STARTED"));
assertThat("Context[" + context.getContextPath() + "].state", context.getState(), is("STARTED"));
break;
}
}
Assert.assertTrue("Did not find Expected Context Path " + expectedPath,found);
assertTrue(found,"Did not find Expected Context Path " + expectedPath);
}
}
@ -258,12 +262,11 @@ public class XmlConfiguredJetty
if (file.isDirectory() && file.getAbsolutePath().contains("target" + File.separator))
{
deleteContents(file);
Assert.assertTrue("Delete failed: " + file.getAbsolutePath(),file.delete());
assertTrue(file.delete(),"Delete failed: " + file.getAbsolutePath());
}
else
{
System.err.printf("Delete (file) %s%n",file);
Assert.assertTrue("Delete failed: " + file.getAbsolutePath(),file.delete());
assertTrue(file.delete(),"Delete failed: " + file.getAbsolutePath());
}
}
}
@ -358,7 +361,7 @@ public class XmlConfiguredJetty
throw new Exception("Load failed to configure a " + Server.class.getName());
}
Assert.assertEquals("Server load count",1,serverCount);
assertEquals(1, serverCount, "Server load count");
this._server = foundServer;
this._server.setStopTimeout(10);
@ -370,7 +373,7 @@ public class XmlConfiguredJetty
File contextFile = new File(destDir,name);
if (contextFile.exists())
{
Assert.assertTrue("Delete of Webapp file: " + contextFile.getAbsolutePath(),contextFile.delete());
assertTrue(contextFile.delete(),"Delete of Webapp file: " + contextFile.getAbsolutePath());
}
}
@ -386,7 +389,7 @@ public class XmlConfiguredJetty
public void start() throws Exception
{
Assert.assertNotNull("Server should not be null (failed load?)",_server);
assertNotNull(_server, "Server should not be null (failed load?)");
_server.start();
@ -403,7 +406,7 @@ public class XmlConfiguredJetty
}
}
Assert.assertTrue("Server Port is between 1 and 65535. Actually <" + _serverPort + ">",(1 <= this._serverPort) && (this._serverPort <= 65535));
assertTrue((1 <= this._serverPort) && (this._serverPort <= 65535),"Server Port is between 1 and 65535. Was actually <" + _serverPort + ">");
// Uncomment to have server start and continue to run (without exiting)
// System.err.printf("Listening to port %d%n",this.serverPort);

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.fcgi.generator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
@ -28,8 +31,8 @@ import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.MappedByteBufferPool;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class ClientGeneratorTest
{
@ -81,24 +84,24 @@ public class ClientGeneratorTest
@Override
public void onHeader(int request, HttpField field)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
switch (field.getName())
{
case shortShortName:
Assert.assertEquals(shortShortValue, field.getValue());
assertEquals(shortShortValue, field.getValue());
params.set(params.get() * primes[0]);
break;
case shortLongName:
Assert.assertEquals(shortLongValue, field.getValue());
assertEquals(shortLongValue, field.getValue());
params.set(params.get() * primes[1]);
break;
case longShortName:
Assert.assertEquals(longShortValue, field.getValue());
assertEquals(longShortValue, field.getValue());
params.set(params.get() * primes[2]);
break;
default:
Assert.assertEquals(longLongName, field.getName());
Assert.assertEquals(longLongValue, field.getValue());
assertEquals(longLongName, field.getName());
assertEquals(longLongValue, field.getValue());
params.set(params.get() * primes[3]);
break;
}
@ -107,7 +110,7 @@ public class ClientGeneratorTest
@Override
public void onHeaders(int request)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
params.set(params.get() * primes[4]);
}
});
@ -115,10 +118,10 @@ public class ClientGeneratorTest
for (ByteBuffer buffer : result.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
Assert.assertEquals(value, params.get());
assertEquals(value, params.get());
// Parse again byte by byte
params.set(1);
@ -127,10 +130,10 @@ public class ClientGeneratorTest
buffer.flip();
while (buffer.hasRemaining())
parser.parse(ByteBuffer.wrap(new byte[]{buffer.get()}));
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
Assert.assertEquals(value, params.get());
assertEquals(value, params.get());
}
@Test
@ -160,7 +163,7 @@ public class ClientGeneratorTest
@Override
public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
totalLength.addAndGet(buffer.remaining());
return false;
}
@ -168,15 +171,15 @@ public class ClientGeneratorTest
@Override
public void onEnd(int request)
{
Assert.assertEquals(id, request);
Assert.assertEquals(contentLength, totalLength.get());
assertEquals(id, request);
assertEquals(contentLength, totalLength.get());
}
});
for (ByteBuffer buffer : result.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
// Parse again one byte at a time
@ -185,7 +188,7 @@ public class ClientGeneratorTest
buffer.flip();
while (buffer.hasRemaining())
parser.parse(ByteBuffer.wrap(new byte[]{buffer.get()}));
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
}
}

View File

@ -18,6 +18,10 @@
package org.eclipse.jetty.fcgi.parser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@ -29,8 +33,8 @@ import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.MappedByteBufferPool;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class ClientParserTest
{
@ -64,19 +68,19 @@ public class ClientParserTest
@Override
public void onBegin(int request, int code, String reason)
{
Assert.assertEquals(statusCode, code);
Assert.assertEquals(statusMessage, reason);
assertEquals(statusCode, code);
assertEquals(statusMessage, reason);
params.set(params.get() * primes[0]);
}
@Override
public void onHeader(int request, HttpField field)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
switch (field.getName())
{
case contentTypeName:
Assert.assertEquals(contentTypeValue, field.getValue());
assertEquals(contentTypeValue, field.getValue());
params.set(params.get() * primes[1]);
break;
default:
@ -87,7 +91,7 @@ public class ClientParserTest
@Override
public void onHeaders(int request)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
params.set(params.get() * primes[2]);
}
});
@ -95,10 +99,10 @@ public class ClientParserTest
for (ByteBuffer buffer : result.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
Assert.assertEquals(value, params.get());
assertEquals(value, params.get());
}
@Test
@ -119,7 +123,7 @@ public class ClientParserTest
@Override
public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
verifier.addAndGet(2);
return false;
}
@ -127,7 +131,7 @@ public class ClientParserTest
@Override
public void onEnd(int request)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
verifier.addAndGet(3);
}
});
@ -135,15 +139,15 @@ public class ClientParserTest
for (ByteBuffer buffer : result1.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
for (ByteBuffer buffer : result2.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
Assert.assertEquals(3, verifier.get());
assertEquals(3, verifier.get());
}
@Test
@ -171,8 +175,8 @@ public class ClientParserTest
@Override
public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer)
{
Assert.assertEquals(id, request);
Assert.assertEquals(contentLength, buffer.remaining());
assertEquals(id, request);
assertEquals(contentLength, buffer.remaining());
verifier.addAndGet(2);
return false;
}
@ -180,7 +184,7 @@ public class ClientParserTest
@Override
public void onEnd(int request)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
verifier.addAndGet(3);
}
});
@ -188,15 +192,15 @@ public class ClientParserTest
for (ByteBuffer buffer : result1.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
for (ByteBuffer buffer : result2.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
Assert.assertEquals(5, verifier.get());
assertEquals(5, verifier.get());
}
@Test
@ -225,7 +229,7 @@ public class ClientParserTest
@Override
public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer)
{
Assert.assertEquals(id, request);
assertEquals(id, request);
totalLength.addAndGet(buffer.remaining());
return false;
}
@ -233,8 +237,8 @@ public class ClientParserTest
@Override
public void onEnd(int request)
{
Assert.assertEquals(id, request);
Assert.assertEquals(contentLength, totalLength.get());
assertEquals(id, request);
assertEquals(contentLength, totalLength.get());
verifier.set(true);
}
});
@ -242,14 +246,14 @@ public class ClientParserTest
for (ByteBuffer buffer : result1.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
for (ByteBuffer buffer : result2.getByteBuffers())
{
parser.parse(buffer);
Assert.assertFalse(buffer.hasRemaining());
assertFalse(buffer.hasRemaining());
}
Assert.assertTrue(verifier.get());
assertTrue(verifier.get());
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.fcgi.server;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.client.HttpClient;
@ -32,20 +34,14 @@ import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.LeakDetector;
import org.eclipse.jetty.util.ProcessorUtils;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Rule;
import static org.junit.Assert.assertThat;
import org.junit.jupiter.api.AfterEach;
public abstract class AbstractHttpClientServerTest
{
@Rule
public final TestTracker tracker = new TestTracker();
private LeakTrackingByteBufferPool serverBufferPool;
protected ByteBufferPool clientBufferPool;
private final AtomicLong connectionLeaks = new AtomicLong();
@ -88,7 +84,7 @@ public abstract class AbstractHttpClientServerTest
client.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
System.gc();

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.fcgi.server;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -27,14 +29,13 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.fcgi.client.http.HttpClientTransportOverFCGI;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class ExternalFastCGIServerTest
{
@Test
@Ignore("Relies on an external server")
@Disabled("Relies on an external server")
public void testExternalFastCGIServer() throws Exception
{
// Assume a FastCGI server is listening on localhost:9000
@ -47,7 +48,7 @@ public class ExternalFastCGIServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
Path responseFile = Paths.get(System.getProperty("java.io.tmpdir"), "fcgi_response.html");
Files.write(responseFile, response.getContent(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);

View File

@ -18,6 +18,14 @@
package org.eclipse.jetty.fcgi.server;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.EOFException;
import java.io.IOException;
import java.net.URI;
@ -49,11 +57,11 @@ import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.io.MappedByteBufferPool;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
public class HttpClientTest extends AbstractHttpClientServerTest
{
@ -65,8 +73,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
for (int i = 0; i < 2; ++i)
{
Response response = client.GET(scheme + "://localhost:" + connector.getLocalPort());
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
}
@ -90,10 +98,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest
for (int i = 0; i < maxConnections + 1; ++i)
{
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort());
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
byte[] content = response.getContent();
Assert.assertArrayEquals(data, content);
assertArrayEquals(data, content);
}
}
@ -120,10 +128,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest
FutureResponseListener listener = new FutureResponseListener(request, data.length);
request.send(listener);
ContentResponse response = listener.get(15, TimeUnit.SECONDS);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
byte[] content = response.getContent();
Assert.assertArrayEquals(data, content);
assertArrayEquals(data, content);
}
@Test
@ -141,7 +149,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String paramValue1 = request.getParameter(paramName1);
output.write(paramValue1.getBytes("UTF-8"));
String paramValue2 = request.getParameter(paramName2);
Assert.assertEquals("", paramValue2);
assertEquals("", paramValue2);
output.write("empty".getBytes("UTF-8"));
baseRequest.setHandled(true);
}
@ -152,10 +160,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String query = paramName1 + "=" + paramValue1 + "&" + paramName2;
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
String content = new String(response.getContent(), "UTF-8");
Assert.assertEquals(value1 + "empty", content);
assertEquals(value1 + "empty", content);
}
@Test
@ -188,10 +196,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String query = paramName1 + "=" + paramValue11 + "&" + paramName1 + "=" + paramValue12 + "&" + paramName2 + "=" + paramValue2;
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
String content = new String(response.getContent(), "UTF-8");
Assert.assertEquals(value11 + value12 + value2, content);
assertEquals(value11 + value12 + value2, content);
}
@Test
@ -220,9 +228,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(paramValue, new String(response.getContent(), "UTF-8"));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals(paramValue, new String(response.getContent(), "UTF-8"));
}
@Test
@ -252,9 +260,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(paramValue, new String(response.getContent(), "UTF-8"));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals(paramValue, new String(response.getContent(), "UTF-8"));
}
@Test
@ -284,9 +292,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(paramValue, new String(response.getContent(), "UTF-8"));
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals(paramValue, new String(response.getContent(), "UTF-8"));
}
@Test
@ -319,9 +327,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(content, response.getContent());
assertNotNull(response);
assertEquals(200, response.getStatus());
assertArrayEquals(content, response.getContent());
}
}
@ -347,8 +355,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
@Test
@ -364,18 +372,18 @@ public class HttpClientTest extends AbstractHttpClientServerTest
public void onContent(Request request, ByteBuffer buffer)
{
byte[] bytes = new byte[buffer.remaining()];
Assert.assertEquals(1, bytes.length);
assertEquals(1, bytes.length);
buffer.get(bytes);
Assert.assertEquals(bytes[0], progress.getAndIncrement());
assertEquals(bytes[0], progress.getAndIncrement());
}
})
.content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{2}, new byte[]{3}, new byte[]{4}))
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(5, progress.get());
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals(5, progress.get());
}
@Test
@ -405,12 +413,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(data, response.getContent());
}
@Slow
@Test
@DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review
public void testRequestIdleTimeout() throws Exception
{
final long idleTimeout = 1000;
@ -433,18 +441,13 @@ public class HttpClientTest extends AbstractHttpClientServerTest
final String host = "localhost";
final int port = connector.getLocalPort();
try
{
assertThrows(TimeoutException.class, ()->{
client.newRequest(host, port)
.scheme(scheme)
.idleTimeout(idleTimeout, TimeUnit.MILLISECONDS)
.timeout(3 * idleTimeout, TimeUnit.MILLISECONDS)
.send();
Assert.fail();
}
catch (TimeoutException expected)
{
}
});
// Make another request without specifying the idle timeout, should not fail
ContentResponse response = client.newRequest(host, port)
@ -452,8 +455,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(3 * idleTimeout, TimeUnit.MILLISECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
@Test
@ -479,19 +482,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest
connector.setIdleTimeout(idleTimeout);
try
{
ExecutionException x = assertThrows(ExecutionException.class, ()->{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.idleTimeout(4 * idleTimeout, TimeUnit.MILLISECONDS)
.timeout(3 * idleTimeout, TimeUnit.MILLISECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
Assert.assertTrue(x.getCause() instanceof EOFException);
}
});
assertThat(x.getCause(), instanceOf(EOFException.class));
connector.setIdleTimeout(5 * idleTimeout);
@ -502,8 +500,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(3 * idleTimeout, TimeUnit.MILLISECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
@Test
@ -516,8 +514,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
assertNotNull(response);
assertEquals(200, response.getStatus());
}
@Test
@ -542,9 +540,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(0, response.getContent().length);
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals(0, response.getContent().length);
// Perform a normal GET request to be sure the content is now read
response = client.newRequest("localhost", connector.getLocalPort())
@ -552,9 +550,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(length, response.getContent().length);
assertNotNull(response);
assertEquals(200, response.getStatus());
assertEquals(length, response.getContent().length);
}
@Test
@ -585,12 +583,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch.await(5, TimeUnit.SECONDS));
// Stop the client, the complete listener must be invoked.
client.stop();
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
}
@Test
@ -609,17 +607,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest
}
});
try (StacklessLogging stackless = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class))
try (StacklessLogging ignore = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class))
{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.timeout(60, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
{
// Expected.
assertThrows(ExecutionException.class, () -> {
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.timeout(60, TimeUnit.SECONDS)
.send();
});
}
}
@ -662,8 +657,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(data, response.getContent());
}
@Test
@ -706,34 +701,34 @@ public class HttpClientTest extends AbstractHttpClientServerTest
}
});
Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
Callback callback = callbackRef.get();
// Wait a while to be sure that the parsing does not proceed.
TimeUnit.MILLISECONDS.sleep(1000);
Assert.assertEquals(1, contentCount.get());
assertEquals(1, contentCount.get());
// Succeed the content callback to proceed with parsing.
callbackRef.set(null);
contentLatch.set(new CountDownLatch(1));
callback.succeeded();
Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
callback = callbackRef.get();
// Wait a while to be sure that the parsing does not proceed.
TimeUnit.MILLISECONDS.sleep(1000);
Assert.assertEquals(2, contentCount.get());
Assert.assertEquals(1, completeLatch.getCount());
assertEquals(2, contentCount.get());
assertEquals(1, completeLatch.getCount());
// Succeed the content callback to proceed with parsing.
callbackRef.set(null);
contentLatch.set(new CountDownLatch(1));
callback.succeeded();
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertEquals(2, contentCount.get());
assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
assertEquals(2, contentCount.get());
}
}

View File

@ -18,9 +18,15 @@
package org.eclipse.jetty.fcgi.server.proxy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@ -42,34 +48,28 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class FastCGIProxyServletTest
{
@Parameterized.Parameters
public static Object[] parameters()
public static Stream<Arguments> factories()
{
return new Object[]{true, false};
return Stream.of(
true, // send status 200
false // don't send status 200
).map(Arguments::of);
}
private final boolean sendStatus200;
private Server server;
private ServerConnector httpConnector;
private ServerConnector fcgiConnector;
private ServletContextHandler context;
private HttpClient client;
public FastCGIProxyServletTest(boolean sendStatus200)
{
this.sendStatus200 = sendStatus200;
}
public void prepare(HttpServlet servlet) throws Exception
public void prepare(boolean sendStatus200, HttpServlet servlet) throws Exception
{
QueuedThreadPool serverThreads = new QueuedThreadPool();
serverThreads.setName("server");
@ -110,42 +110,45 @@ public class FastCGIProxyServletTest
server.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
server.stop();
}
@Test
public void testGETWithSmallResponseContent() throws Exception
@ParameterizedTest(name="[{index}] sendStatus200={0}")
@MethodSource("factories")
public void testGETWithSmallResponseContent(boolean sendStatus200) throws Exception
{
testGETWithResponseContent(1024, 0);
testGETWithResponseContent(sendStatus200, 1024, 0);
}
@Test
public void testGETWithLargeResponseContent() throws Exception
@ParameterizedTest(name="[{index}] sendStatus200={0}")
@MethodSource("factories")
public void testGETWithLargeResponseContent(boolean sendStatus200) throws Exception
{
testGETWithResponseContent(16 * 1024 * 1024, 0);
testGETWithResponseContent(sendStatus200, 16 * 1024 * 1024, 0);
}
@Test
public void testGETWithLargeResponseContentWithSlowClient() throws Exception
@ParameterizedTest(name="[{index}] sendStatus200={0}")
@MethodSource("factories")
public void testGETWithLargeResponseContentWithSlowClient(boolean sendStatus200) throws Exception
{
testGETWithResponseContent(16 * 1024 * 1024, 1);
testGETWithResponseContent(sendStatus200, 16 * 1024 * 1024, 1);
}
private void testGETWithResponseContent(int length, final long delay) throws Exception
private void testGETWithResponseContent(boolean sendStatus200, int length, final long delay) throws Exception
{
final byte[] data = new byte[length];
new Random().nextBytes(data);
final String path = "/foo/index.php";
prepare(new HttpServlet()
prepare(sendStatus200, new HttpServlet()
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Assert.assertTrue(request.getRequestURI().endsWith(path));
assertTrue(request.getRequestURI().endsWith(path));
response.setContentLength(data.length);
response.getOutputStream().write(data);
}
@ -171,24 +174,25 @@ public class FastCGIProxyServletTest
ContentResponse response = listener.get(30, TimeUnit.SECONDS);
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
assertEquals(200, response.getStatus());
assertArrayEquals(data, response.getContent());
}
@Test
public void testURIRewrite() throws Exception
@ParameterizedTest(name="[{index}] sendStatus200={0}")
@MethodSource("factories")
public void testURIRewrite(boolean sendStatus200) throws Exception
{
String originalPath = "/original/index.php";
String originalQuery = "foo=bar";
String remotePath = "/remote/index.php";
prepare(new HttpServlet()
prepare(sendStatus200, new HttpServlet()
{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Assert.assertThat((String)request.getAttribute(FCGI.Headers.REQUEST_URI), Matchers.startsWith(originalPath));
Assert.assertEquals(originalQuery, request.getAttribute(FCGI.Headers.QUERY_STRING));
Assert.assertThat(request.getRequestURI(), Matchers.endsWith(remotePath));
assertThat((String)request.getAttribute(FCGI.Headers.REQUEST_URI), Matchers.startsWith(originalPath));
assertEquals(originalQuery, request.getAttribute(FCGI.Headers.QUERY_STRING));
assertThat(request.getRequestURI(), Matchers.endsWith(remotePath));
}
});
context.stop();
@ -216,6 +220,6 @@ public class FastCGIProxyServletTest
.path(remotePath)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(HttpStatus.OK_200, response.getStatus());
}
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.fcgi.server.proxy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.EnumSet;
@ -35,9 +38,8 @@ import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public class TryFilesFilterTest
{
@ -76,7 +78,7 @@ public class TryFilesFilterTest
server.start();
}
@After
@AfterEach
public void dispose() throws Exception
{
server.stop();
@ -91,10 +93,10 @@ public class TryFilesFilterTest
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
Assert.assertTrue("https".equalsIgnoreCase(req.getScheme()));
Assert.assertTrue(req.isSecure());
Assert.assertEquals(forwardPath, req.getRequestURI());
Assert.assertTrue(req.getQueryString().endsWith(path));
assertTrue("https".equalsIgnoreCase(req.getScheme()));
assertTrue(req.isSecure());
assertEquals(forwardPath, req.getRequestURI());
assertTrue(req.getQueryString().endsWith(path));
}
});
@ -103,6 +105,6 @@ public class TryFilesFilterTest
.path(path)
.send();
Assert.assertEquals(200, response.getStatus());
assertEquals(200, response.getStatus());
}
}

View File

@ -29,9 +29,9 @@ import org.eclipse.jetty.server.session.DefaultSessionCache;
import org.eclipse.jetty.server.session.SessionContext;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@ -41,7 +41,7 @@ import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public class TestHazelcastSessions
{
@ -101,7 +101,7 @@ public class TestHazelcastSessions
String contextPath = "/";
@Before
@BeforeEach
public void initialize()
throws Exception
{
@ -131,7 +131,7 @@ public class TestHazelcastSessions
server.start();
}
@After
@AfterEach
public void shutdown()
throws Exception
{

View File

@ -25,7 +25,7 @@ import org.eclipse.jetty.client.util.BasicAuthentication;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.OutputStream;
@ -45,7 +45,7 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.junit.Test;
import org.junit.jupiter.api.Test;

View File

@ -18,20 +18,16 @@
package org.eclipse.jetty.http;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(AdvancedRunner.class)
public class CookieCutterTest
{
private Cookie[] parseCookieHeaders(CookieCompliance compliance,String... headers)
@ -144,7 +140,7 @@ public class CookieCutterTest
* Example from RFC2965
*/
@Test
@Ignore("comma separation no longer supported by new RFC6265")
@Disabled("comma separation no longer supported by new RFC6265")
public void testRFC2965_CookieSpoofingExample()
{
String rawCookie = "$Version=\"1\"; session_id=\"1234\", " +

View File

@ -18,153 +18,140 @@
package org.eclipse.jetty.http;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.eclipse.jetty.http.CookieCompliance;
import org.eclipse.jetty.http.CookieCutter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* Tests of poor various name=value scenarios and expectations of results
* due to our efforts at being lenient with what we receive.
*/
@RunWith(Parameterized.class)
public class CookieCutter_LenientTest
{
@Parameterized.Parameters(name = "{0}")
public static List<String[]> data()
public static Stream<Arguments> data()
{
List<String[]> ret = new ArrayList<>();
// Simple test to verify behavior
ret.add(new String[]{"key=value", "key", "value"});
// Tests that conform to RFC2109
// RFC2109 - token values
// token = 1*<any CHAR except CTLs or tspecials>
// CHAR = <any US-ASCII character (octets 0 - 127)>
// CTL = <any US-ASCII control character
// (octets 0 - 31) and DEL (127)>
// SP = <US-ASCII SP, space (32)>
// HT = <US-ASCII HT, horizontal-tab (9)>
// tspecials = "(" | ")" | "<" | ">" | "@"
// | "," | ";" | ":" | "\" | <">
// | "/" | "[" | "]" | "?" | "="
// | "{" | "}" | SP | HT
ret.add(new String[]{"abc=xyz", "abc", "xyz"});
ret.add(new String[]{"abc=!bar", "abc", "!bar"});
ret.add(new String[]{"abc=#hash", "abc", "#hash"});
ret.add(new String[]{"abc=#hash", "abc", "#hash"});
// RFC2109 - quoted-string values
// quoted-string = ( <"> *(qdtext) <"> )
// qdtext = <any TEXT except <">>
return Stream.of(
// Simple test to verify behavior
Arguments.of("key=value", "key", "value"),
// lenient with spaces and EOF
ret.add(new String[]{"abc=", "abc", ""});
ret.add(new String[]{"abc = ", "abc", ""});
ret.add(new String[]{"abc = ;", "abc", ""});
ret.add(new String[]{"abc = ; ", "abc", ""});
ret.add(new String[]{"abc = x ", "abc", "x"});
ret.add(new String[]{"abc=\"\"", "abc", ""});
ret.add(new String[]{"abc= \"\" ", "abc", ""});
ret.add(new String[]{"abc= \"x\" ", "abc", "x"});
ret.add(new String[]{"abc= \"x\" ;", "abc", "x"});
ret.add(new String[]{"abc= \"x\" ; ", "abc", "x"});
// Tests that conform to RFC2109
// RFC2109 - token values
// token = 1*<any CHAR except CTLs or tspecials>
// CHAR = <any US-ASCII character (octets 0 - 127)>
// CTL = <any US-ASCII control character
// (octets 0 - 31) and DEL (127)>
// SP = <US-ASCII SP, space (32)>
// HT = <US-ASCII HT, horizontal-tab (9)>
// tspecials = "(" | ")" | "<" | ">" | "@"
// | "," | ";" | ":" | "\" | <">
// | "/" | "[" | "]" | "?" | "="
// | "{" | "}" | SP | HT
Arguments.of("abc=xyz", "abc", "xyz"),
Arguments.of("abc=!bar", "abc", "!bar"),
Arguments.of("abc=#hash", "abc", "#hash"),
Arguments.of("abc=#hash", "abc", "#hash"),
// RFC2109 - quoted-string values
// quoted-string = ( <"> *(qdtext) <"> )
// qdtext = <any TEXT except <">>
// The backslash character ("\") may be used as a single-character quoting
// mechanism only within quoted-string and comment constructs.
// quoted-pair = "\" CHAR
ret.add(new String[]{"abc=\"xyz\"", "abc", "xyz"});
ret.add(new String[]{"abc=\"!bar\"", "abc", "!bar"});
ret.add(new String[]{"abc=\"#hash\"", "abc", "#hash"});
// RFC2109 - other valid name types that conform to 'attr'/'token' syntax
ret.add(new String[]{"!f!o!o!=wat", "!f!o!o!", "wat"});
ret.add(new String[]{"__MyHost=Foo", "__MyHost", "Foo"});
ret.add(new String[]{"some-thing-else=to-parse", "some-thing-else", "to-parse"});
// RFC2109 - names with attr/token syntax starting with '$' (and not a cookie reserved word)
// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-5.2
// Cannot pass names through as javax.servlet.http.Cookie class does not allow them
ret.add(new String[]{"$foo=bar", null, null});
// lenient with spaces and EOF
Arguments.of("abc=", "abc", ""),
Arguments.of("abc = ", "abc", ""),
Arguments.of("abc = ;", "abc", ""),
Arguments.of("abc = ; ", "abc", ""),
Arguments.of("abc = x ", "abc", "x"),
Arguments.of("abc=\"\"", "abc", ""),
Arguments.of("abc= \"\" ", "abc", ""),
Arguments.of("abc= \"x\" ", "abc", "x"),
Arguments.of("abc= \"x\" ;", "abc", "x"),
Arguments.of("abc= \"x\" ; ", "abc", "x"),
// Tests that conform to RFC6265
ret.add(new String[]{"abc=foobar!", "abc", "foobar!"});
ret.add(new String[]{"abc=\"foobar!\"", "abc", "foobar!"});
// Internal quotes
ret.add(new String[]{"foo=bar\"baz", "foo", "bar\"baz"});
ret.add(new String[]{"foo=\"bar\"baz\"", "foo", "bar\"baz"});
ret.add(new String[]{"foo=\"bar\"-\"baz\"", "foo", "bar\"-\"baz"});
ret.add(new String[]{"foo=\"bar'-\"baz\"", "foo", "bar'-\"baz"});
ret.add(new String[]{"foo=\"bar''-\"baz\"", "foo", "bar''-\"baz"});
// These seem dubious until you realize the "lots of equals signs" below works
ret.add(new String[]{"foo=\"bar\"=\"baz\"", "foo", "bar\"=\"baz"});
ret.add(new String[]{"query=\"?b=c\"&\"d=e\"", "query", "?b=c\"&\"d=e"});
// Escaped quotes
ret.add(new String[]{"foo=\"bar\\\"=\\\"baz\"", "foo", "bar\"=\"baz"});
// Unterminated Quotes
ret.add(new String[]{"x=\"abc", "x", "\"abc"});
// Unterminated Quotes with valid cookie params after it
ret.add(new String[]{"x=\"abc $Path=/", "x", "\"abc $Path=/"});
// Unterminated Quotes with trailing escape
ret.add(new String[]{"x=\"abc\\", "x", "\"abc\\"});
// UTF-8 values
ret.add(new String[]{"2sides=\u262F", "2sides", "\u262f"}); // 2 byte
ret.add(new String[]{"currency=\"\u20AC\"", "currency", "\u20AC"}); // 3 byte
ret.add(new String[]{"gothic=\"\uD800\uDF48\"", "gothic", "\uD800\uDF48"}); // 4 byte
// Spaces
ret.add(new String[]{"foo=bar baz", "foo", "bar baz"});
ret.add(new String[]{"foo=\"bar baz\"", "foo", "bar baz"});
ret.add(new String[]{"z=a b c d e f g", "z", "a b c d e f g"});
// Bad tspecials usage
ret.add(new String[]{"foo=bar;baz", "foo", "bar"});
ret.add(new String[]{"foo=\"bar;baz\"", "foo", "bar;baz"});
ret.add(new String[]{"z=a;b,c:d;e/f[g]", "z", "a"});
ret.add(new String[]{"z=\"a;b,c:d;e/f[g]\"", "z", "a;b,c:d;e/f[g]"});
// Quoted with other Cookie keywords
ret.add(new String[]{"x=\"$Version=0\"", "x", "$Version=0"});
ret.add(new String[]{"x=\"$Path=/\"", "x", "$Path=/"});
ret.add(new String[]{"x=\"$Path=/ $Domain=.foo.com\"", "x", "$Path=/ $Domain=.foo.com"});
ret.add(new String[]{"x=\" $Path=/ $Domain=.foo.com \"", "x", " $Path=/ $Domain=.foo.com "});
ret.add(new String[]{"a=\"b; $Path=/a; c=d; $PATH=/c; e=f\"; $Path=/e/", "a", "b; $Path=/a; c=d; $PATH=/c; e=f"});
// Lots of equals signs
ret.add(new String[]{"query=b=c&d=e", "query", "b=c&d=e"});
// Escaping
ret.add(new String[]{"query=%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D", "query", "%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D"});
// Google cookies (seen in wild, has `tspecials` of ':' in value)
ret.add(new String[]{"GAPS=1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-", "GAPS", "1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-"});
// Strong abuse of cookie spec (lots of tspecials)
ret.add(new String[]{"$Version=0; rToken=F_TOKEN''!--\"</a>=&{()}", "rToken", "F_TOKEN''!--\"</a>=&{()}"});
return ret;
// The backslash character ("\") may be used as a single-character quoting
// mechanism only within quoted-string and comment constructs.
// quoted-pair = "\" CHAR
Arguments.of("abc=\"xyz\"", "abc", "xyz"),
Arguments.of("abc=\"!bar\"", "abc", "!bar"),
Arguments.of("abc=\"#hash\"", "abc", "#hash"),
// RFC2109 - other valid name types that conform to 'attr'/'token' syntax
Arguments.of("!f!o!o!=wat", "!f!o!o!", "wat"),
Arguments.of("__MyHost=Foo", "__MyHost", "Foo"),
Arguments.of("some-thing-else=to-parse", "some-thing-else", "to-parse"),
// RFC2109 - names with attr/token syntax starting with '$' (and not a cookie reserved word)
// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-5.2
// Cannot pass names through as javax.servlet.http.Cookie class does not allow them
Arguments.of("$foo=bar", null, null),
// Tests that conform to RFC6265
Arguments.of("abc=foobar!", "abc", "foobar!"),
Arguments.of("abc=\"foobar!\"", "abc", "foobar!"),
// Internal quotes
Arguments.of("foo=bar\"baz", "foo", "bar\"baz"),
Arguments.of("foo=\"bar\"baz\"", "foo", "bar\"baz"),
Arguments.of("foo=\"bar\"-\"baz\"", "foo", "bar\"-\"baz"),
Arguments.of("foo=\"bar'-\"baz\"", "foo", "bar'-\"baz"),
Arguments.of("foo=\"bar''-\"baz\"", "foo", "bar''-\"baz"),
// These seem dubious until you realize the "lots of equals signs" below works
Arguments.of("foo=\"bar\"=\"baz\"", "foo", "bar\"=\"baz"),
Arguments.of("query=\"?b=c\"&\"d=e\"", "query", "?b=c\"&\"d=e"),
// Escaped quotes
Arguments.of("foo=\"bar\\\"=\\\"baz\"", "foo", "bar\"=\"baz"),
// Unterminated Quotes
Arguments.of("x=\"abc", "x", "\"abc"),
// Unterminated Quotes with valid cookie params after it
Arguments.of("x=\"abc $Path=/", "x", "\"abc $Path=/"),
// Unterminated Quotes with trailing escape
Arguments.of("x=\"abc\\", "x", "\"abc\\"),
// UTF-8 values
Arguments.of("2sides=\u262F", "2sides", "\u262f"), // 2 byte
Arguments.of("currency=\"\u20AC\"", "currency", "\u20AC"), // 3 byte
Arguments.of("gothic=\"\uD800\uDF48\"", "gothic", "\uD800\uDF48"), // 4 byte
// Spaces
Arguments.of("foo=bar baz", "foo", "bar baz"),
Arguments.of("foo=\"bar baz\"", "foo", "bar baz"),
Arguments.of("z=a b c d e f g", "z", "a b c d e f g"),
// Bad tspecials usage
Arguments.of("foo=bar;baz", "foo", "bar"),
Arguments.of("foo=\"bar;baz\"", "foo", "bar;baz"),
Arguments.of("z=a;b,c:d;e/f[g]", "z", "a"),
Arguments.of("z=\"a;b,c:d;e/f[g]\"", "z", "a;b,c:d;e/f[g]"),
// Quoted with other Cookie keywords
Arguments.of("x=\"$Version=0\"", "x", "$Version=0"),
Arguments.of("x=\"$Path=/\"", "x", "$Path=/"),
Arguments.of("x=\"$Path=/ $Domain=.foo.com\"", "x", "$Path=/ $Domain=.foo.com"),
Arguments.of("x=\" $Path=/ $Domain=.foo.com \"", "x", " $Path=/ $Domain=.foo.com "),
Arguments.of("a=\"b; $Path=/a; c=d; $PATH=/c; e=f\"; $Path=/e/", "a", "b; $Path=/a; c=d; $PATH=/c; e=f"),
// Lots of equals signs
Arguments.of("query=b=c&d=e", "query", "b=c&d=e"),
// Escaping
Arguments.of("query=%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D", "query", "%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D"),
// Google cookies (seen in wild, has `tspecials` of ':' in value)
Arguments.of("GAPS=1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-", "GAPS", "1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-"),
// Strong abuse of cookie spec (lots of tspecials)
Arguments.of("$Version=0; rToken=F_TOKEN''!--\"</a>=&{()}", "rToken", "F_TOKEN''!--\"</a>=&{()}")
);
}
@Parameterized.Parameter
public String rawHeader;
@Parameterized.Parameter(1)
public String expectedName;
@Parameterized.Parameter(2)
public String expectedValue;
@Test
public void testLenientBehavior()
@ParameterizedTest
@MethodSource("data")
public void testLenientBehavior(String rawHeader, String expectedName, String expectedValue)
{
TestCutter cutter = new TestCutter();
cutter.parseField(rawHeader);

View File

@ -18,9 +18,9 @@
package org.eclipse.jetty.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -31,23 +31,17 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.eclipse.jetty.io.ArrayByteBufferPool;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class GZIPContentDecoderTest
{
@Rule
public final TestTracker tracker = new TestTracker();
ArrayByteBufferPool pool;
AtomicInteger buffers = new AtomicInteger(0);
@Before
@BeforeEach
public void beforeClass() throws Exception
{
buffers.set(0);
@ -71,7 +65,7 @@ public class GZIPContentDecoderTest
};
}
@After
@AfterEach
public void afterClass() throws Exception
{
assertEquals(0,buffers.get());

View File

@ -19,16 +19,16 @@
package org.eclipse.jetty.http;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.nio.ByteBuffer;
import org.eclipse.jetty.util.BufferUtil;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HttpFieldTest
{

View File

@ -0,0 +1,47 @@
//
// ========================================================================
// Copyright (c) 1995-2018 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 org.eclipse.jetty.http.matchers.HttpFieldsContainsHeaderValue;
import org.eclipse.jetty.http.matchers.HttpFieldsContainsHeaderKey;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class HttpFieldsMatchers
{
@Factory
public static Matcher<HttpFields> containsHeader(String keyName) {
return new HttpFieldsContainsHeaderKey(keyName);
}
@Factory
public static Matcher<HttpFields> containsHeader(HttpHeader header) {
return new HttpFieldsContainsHeaderKey(header);
}
@Factory
public static Matcher<HttpFields> containsHeaderValue(String keyName, String value) {
return new HttpFieldsContainsHeaderValue(keyName, value);
}
@Factory
public static Matcher<HttpFields> containsHeaderValue(HttpHeader header, String value) {
return new HttpFieldsContainsHeaderValue(header, value);
}
}

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