Issue #1977 jetty-http-spi tests with java9

For now, I have removed the tests using powermock and replaced with a simple test.
Also fixed some lifecycle issues

Signed-off-by: Greg Wilkins <gregw@webtide.com>
This commit is contained in:
Greg Wilkins 2017-11-15 13:49:23 +01:00
parent bb0f06fecc
commit 76352cad2f
23 changed files with 165 additions and 2120 deletions

View File

@ -29,24 +29,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.openpojo</groupId>
<artifactId>openpojo</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>

View File

@ -24,7 +24,6 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
@ -35,7 +34,6 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.ThreadPool;
@ -122,6 +120,8 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer
@Override
public InetSocketAddress getAddress()
{
if (_addr.getPort()==0 && _server.isStarted())
return new InetSocketAddress(_addr.getHostString(),_server.getBean(NetworkConnector.class).getLocalPort());
return _addr;
}
@ -215,39 +215,27 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer
JettyHttpContext context = new JettyHttpContext(this, path, httpHandler);
HttpSpiContextHandler jettyContextHandler = context.getJettyContextHandler();
ContextHandlerCollection chc = findContextHandlerCollection(_server.getHandlers());
ContextHandlerCollection chc = _server.getChildHandlerByClass(ContextHandlerCollection.class);
if (chc == null)
throw new RuntimeException("could not find ContextHandlerCollection, you must configure one");
chc.addHandler(jettyContextHandler);
if (chc.isStarted())
{
try
{
jettyContextHandler.start();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
_contexts.put(path, context);
return context;
}
private ContextHandlerCollection findContextHandlerCollection(Handler[] handlers)
{
if (handlers == null)
return null;
for (Handler handler : handlers)
{
if (handler instanceof ContextHandlerCollection)
{
return (ContextHandlerCollection) handler;
}
if (handler instanceof HandlerCollection)
{
HandlerCollection hc = (HandlerCollection) handler;
ContextHandlerCollection chc = findContextHandlerCollection(hc.getHandlers());
if (chc != null)
return chc;
}
}
return null;
}
private void checkIfContextIsFree(String path)
{
Handler serverHandler = _server.getHandler();
@ -282,7 +270,18 @@ public class JettyHttpServer extends com.sun.net.httpserver.HttpServer
{
JettyHttpContext context = _contexts.remove(path);
if (context == null) return;
_server.removeBean(context.getJettyContextHandler());
HttpSpiContextHandler handler = context.getJettyContextHandler();
ContextHandlerCollection chc = _server.getChildHandlerByClass(ContextHandlerCollection.class);
try
{
handler.stop();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
chc.removeHandler(handler);
}
@Override

View File

@ -1,41 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.junit.After;
import org.junit.Before;
public class DelegateThreadPoolBase
{
protected DelegatingThreadPool delegatingThreadPool;
@Before
public void setUp() throws Exception
{
delegatingThreadPool = SpiUtility.getDelegatingThreadPool();
}
@After
public void tearDown() throws Exception
{
delegatingThreadPool.stop();
}
}

View File

@ -1,144 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.eclipse.jetty.http.spi.util.Pool;
import org.eclipse.jetty.http.spi.util.PrintTask;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.junit.Test;
public class DelegatingThreadPoolBasicOperationsTest extends DelegateThreadPoolBase
{
private ThreadPoolExecutor newThreadPoolExecutor;
private ThreadPoolExecutor previousThreadPoolExecutor;
private ThreadPool threadPool;
@Test
public void testExecutorInstances() throws Exception
{
// given
newThreadPoolExecutor = SpiUtility.getThreadPoolExecutor(Pool.CORE_POOL_SIZE.getValue(),SpiConstants.poolInfo);
previousThreadPoolExecutor = (ThreadPoolExecutor)delegatingThreadPool.getExecutor();
// when
delegatingThreadPool.setExecutor(newThreadPoolExecutor);
// then
assertNotEquals("Executor instances shouldn't be equal, as we have modified the executor",(ThreadPoolExecutor)delegatingThreadPool.getExecutor(),
previousThreadPoolExecutor);
}
private void setUpForThreadPools() throws Exception
{
ThreadPool threadPool = mock(ThreadPool.class);
when(threadPool.getIdleThreads()).thenReturn(SpiConstants.ZERO);
when(threadPool.getThreads()).thenReturn(SpiConstants.ZERO);
when(threadPool.isLowOnThreads()).thenReturn(false);
delegatingThreadPool = new DelegatingThreadPool(threadPool);
}
@Test
public void testBasicOperationsForThreadPool() throws Exception
{
// given
setUpForThreadPools();
// then
assertEquals("Idle thread count must be zero as no job ran so far",SpiConstants.ZERO,delegatingThreadPool.getIdleThreads());
assertEquals("Pool count must be zero as no job ran so far",SpiConstants.ZERO,delegatingThreadPool.getThreads());
assertFalse("Threads must haeve been available as no job has been started so far",delegatingThreadPool.isLowOnThreads());
}
@Test
public void testBasicOperationsForThreadPoolExecutors() throws Exception
{
// given
delegatingThreadPool = SpiUtility.getDelegatingThreadPool();
// then
assertEquals("Idle thread count must be zero as no job ran so far",Pool.DEFAULT_SIZE.getValue(),delegatingThreadPool.getIdleThreads());
assertEquals("Pool count must be zero as no job ran so far",Pool.DEFAULT_SIZE.getValue(),delegatingThreadPool.getThreads());
assertFalse("Threads must haeve been available as no job has been started so far",delegatingThreadPool.isLowOnThreads());
}
@Test
public void testBasicOperationsForExecutors() throws Exception
{
// given
Executor executor = mock(Executor.class);
// when
delegatingThreadPool = new DelegatingThreadPool(executor);
// then
assertEquals("Idle thread count must be zero as no job ran so far",SpiConstants.MINUS_ONE,delegatingThreadPool.getIdleThreads());
assertEquals("Pool count must be zero as no job ran so far",SpiConstants.MINUS_ONE,delegatingThreadPool.getThreads());
assertFalse("Threads must haeve been available as no job has been started so far",delegatingThreadPool.isLowOnThreads());
}
@Test
public void testTask() throws Exception
{
// given
PrintTask printTask = null;
// when
for (int i = 0; i < 30; i++)
{
printTask = new PrintTask();
delegatingThreadPool.execute(printTask);
}
// then
// Based on processor speed/job execution time thread count will vary.
// So checking the boundary conditions(DEFAULT_SIZE,MAXIMUM_POOL_SIZE).
String succssMsgOnMaxSize = "Current thread pool must be always less than or equal " + "to max pool size, even though the jobs are more";
String succssMsgOnMinSize = "Current thread pool must be always greater than or equal to defalut size";
assertTrue(succssMsgOnMaxSize,delegatingThreadPool.getThreads() <= Pool.MAXIMUM_POOL_SIZE.getValue());
assertTrue(succssMsgOnMinSize,delegatingThreadPool.getThreads() >= Pool.DEFAULT_SIZE.getValue());
}
@Test
public void testJoinForThreadPools() throws Exception
{
// given
threadPool = mock(ThreadPool.class);
delegatingThreadPool = new DelegatingThreadPool(threadPool);
// when
delegatingThreadPool.join();
// then
verify(threadPool).join();
}
}

View File

@ -1,63 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.fail;
import static org.powermock.api.mockito.PowerMockito.mock;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.eclipse.jetty.http.spi.util.Pool;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.junit.Test;
public class DelegatingThreadPoolExceptionTest extends DelegateThreadPoolBase
{
private ThreadPoolExecutor threadPoolExecutor;
@Test(expected = IllegalStateException.class)
public void testJoinIllegalStateException() throws Exception
{
// given
Executor mockExecutor = mock(Executor.class);
delegatingThreadPool.setExecutor(mockExecutor);
// when
delegatingThreadPool.join();
// then
fail("A IllegalStateException must have occured by now as executor type " + "not in ThreadPool or ExecutorService.");
}
@Test(expected = IllegalStateException.class)
public void testSetExecutorIllegalStateException() throws Exception
{
// given
delegatingThreadPool.start();
threadPoolExecutor = SpiUtility.getThreadPoolExecutor(Pool.CORE_POOL_SIZE.getValue(),SpiConstants.poolInfo);
// when
delegatingThreadPool.setExecutor(threadPoolExecutor);
// then
fail("A IllegalStateException must have occured by now as current threadpool "
+ "has been already started. So it shouldn't allow us to reset the pool.");
}
}

View File

@ -1,255 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.doThrow;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.junit.Before;
import org.junit.Test;
import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.Authenticator.Result;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpPrincipal;
public class HttpSpiContextHandlerTest
{
private HttpSpiContextHandler httpSpiContextHandler;
private HttpContext httpContext;
private HttpHandler httpHandler;
private Request baseRequest;
private HttpServletRequest req;
private HttpServletResponse resp;
private HttpExchange httpExchange;
private Authenticator auth;
@Before
public void setUp() throws Exception
{
httpContext = mock(HttpContext.class);
httpHandler = mock(HttpHandler.class);
httpSpiContextHandler = new HttpSpiContextHandler(httpContext,httpHandler);
}
@Test
public void testGetSetHttpHandler()
{
// given
httpHandler = mock(HttpHandler.class);
// when
httpSpiContextHandler.setHttpHandler(httpHandler);
// then
assertEquals("HttpHandler instances must be equal.",httpHandler,httpSpiContextHandler.getHttpHandler());
}
@Test
public void testDoScopeWithNoHandler() throws Exception
{
// given
setUpDoScope();
// when
httpSpiContextHandler.doScope("test",baseRequest,req,resp);
// then
assertFalse("Context path doesn't start with /, so none of the handler will handle the request",baseRequest.isHandled());
}
@Test
public void testDoScopeHttpExchangeHandler() throws Exception
{
// given
setUpDoScope();
// when
httpSpiContextHandler.doScope("/test",baseRequest,req,resp);
// then
verify(httpHandler).handle((JettyHttpExchange)anyObject());
}
@Test
public void testDoScopeHttpsExchangeHandler() throws Exception
{
// given
setUpDoScope();
when(baseRequest.isSecure()).thenReturn(true);
// when
httpSpiContextHandler.doScope("/test",baseRequest,req,resp);
// then
verify(httpHandler).handle((JettyHttpsExchange)anyObject());
}
@Test
public void testDoScopeAuthenticationHandlerFailure() throws Exception
{
// given
Authenticator.Result failure = new Authenticator.Failure(SpiConstants.FAILURE_STATUS);
setUpAuthentication(failure);
// when
httpSpiContextHandler.doScope("/test",baseRequest,req,resp);
// then
verify(resp).sendError(SpiConstants.FAILURE_STATUS);
}
@Test
public void testDoScopeAuthenticationHandlerSuccess() throws Exception
{
// given
HttpPrincipal principle = mock(HttpPrincipal.class);
Authenticator.Result retry = new Authenticator.Success(principle);
setUpSuccessAuthentication(retry);
// when
httpSpiContextHandler.doScope("/test",baseRequest,req,resp);
// then
verify(httpHandler).handle((JettyHttpExchange)anyObject());
}
@Test
public void testDoScopeAuthenticationHandlerRetry() throws Exception
{
// given
Authenticator.Result retry = new Authenticator.Retry(SpiConstants.RETRY_STATUS);
setUpRetryAuthentication(retry);
// when
httpSpiContextHandler.doScope("/test",baseRequest,req,resp);
// then
verify(resp).setStatus(SpiConstants.RETRY_STATUS);
}
@Test
public void testDoScopeExceptionWithLoggerEnable() throws Exception
{
// given
setUpAuthenticationException();
try
{
Log.getRootLogger().setDebugEnabled(true);
((StdErrLog)Log.getLogger(HttpSpiContextHandler.class)).setHideStacks(true);
// when
httpSpiContextHandler.doScope("/test", baseRequest, req, resp);
// then
verify(resp).setStatus(SpiConstants.FAILURE_STATUS);
}
finally
{
Log.getRootLogger().setDebugEnabled(false);
((StdErrLog)Log.getLogger(HttpSpiContextHandler.class)).setHideStacks(false);
}
}
@Test
public void testDoScopeExceptionWithLoggerDisable() throws Exception
{
// given
setUpAuthenticationException();
// when
httpSpiContextHandler.doScope("/test",baseRequest,req,resp);
// then
verify(resp).setStatus(SpiConstants.FAILURE_STATUS);
}
private void setUpDoScope() throws Exception
{
req = mock(HttpServletRequest.class);
resp = mock(HttpServletResponse.class);
baseRequest = mock(Request.class);
}
private void setUpAuthenticationException() throws Exception
{
setUpDoScope();
ServletOutputStream printStream = mock(ServletOutputStream.class);
when(resp.getOutputStream()).thenReturn(printStream);
HttpChannel httpChannel = mock(HttpChannel.class);
when(baseRequest.getHttpChannel()).thenReturn(httpChannel);
HttpConfiguration configuration = mock(HttpConfiguration.class);
when(httpChannel.getHttpConfiguration()).thenReturn(configuration);
doThrow(new RuntimeException("Expected Test Exception")).when(httpContext).getAuthenticator();
}
private void setUpAuthentication(Result result) throws Exception
{
setUpDoScope();
httpExchange = mock(HttpExchange.class);
auth = mock(Authenticator.class);
Map<String, List<String>> reqHeaders = new HashMap<>();
reqHeaders.put("accepted-Language",SpiUtility.getReqHeaderValues());
Headers headers = new Headers();
headers.putAll(reqHeaders);
when(httpExchange.getResponseHeaders()).thenReturn(headers);
when(auth.authenticate(anyObject())).thenReturn(result);
when(httpContext.getAuthenticator()).thenReturn(auth);
}
private void setUpRetryAuthentication(Result result) throws Exception
{
setUpAuthentication(result);
when(req.getAttribute(SpiConstants.USER_NAME)).thenReturn(SpiConstants.VALID_USER);
}
private void setUpSuccessAuthentication(Result result) throws Exception
{
setUpAuthentication(result);
when(req.getAttribute(SpiConstants.USER_NAME)).thenReturn(SpiConstants.VALID_USER);
when(req.getAttribute(SpiConstants.PASSWORD)).thenReturn(SpiConstants.VALID_PASSWORD);
}
}

View File

@ -1,89 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.powermock.api.mockito.PowerMockito.mock;
import org.junit.Before;
import org.junit.Test;
import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class JettyHttpContextTest
{
private HttpServer httpServer;
private HttpHandler handler;
private String path = "/test";
private JettyHttpContext jettyHttpContext;
private HttpHandler newHttpHandler;
private Authenticator authenticator;
@Before
public void setUp() throws Exception
{
httpServer = mock(HttpServer.class);
handler = mock(HttpHandler.class);
jettyHttpContext = new JettyHttpContext(httpServer,path,handler);
}
@Test
public void testBasicOperations()
{
assertNotNull("Contexthandler instance shouldn't be null",jettyHttpContext.getJettyContextHandler());
assertEquals("Path should be equal",path,jettyHttpContext.getPath());
assertEquals("Server instances must be equal",httpServer,jettyHttpContext.getServer());
assertEquals("Handler instances must be equal",handler,jettyHttpContext.getHandler());
assertNotNull("Attributes shouldn't be null",jettyHttpContext.getAttributes());
assertNotNull("filters shouldn't be null",jettyHttpContext.getFilters());
}
@Test
public void testGetSetHandler()
{
// given
newHttpHandler = mock(HttpHandler.class);
// when
jettyHttpContext.setHandler(newHttpHandler);
// then
assertEquals("Handler instances must be equal",newHttpHandler,jettyHttpContext.getHandler());
}
@Test
public void testGetSetAuthenticator()
{
// given
authenticator = mock(Authenticator.class);
// when
jettyHttpContext.setAuthenticator(authenticator);
// then
assertEquals("Authenticator instances must be equal",authenticator,jettyHttpContext.getAuthenticator());
}
}

View File

@ -1,120 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.junit.Test;
import com.sun.net.httpserver.Headers;
public class JettyHttpExchangeAdvancedOperationsTest extends JettyHttpExchangeBase
{
private JettyHttpExchange mockjettyHttpExchange;
private Boolean match;
private Headers headers;
@Test
public void testAdvancedOperations() throws Exception
{
// given
mockjettyHttpExchange = mock(JettyHttpExchange.class);
// when
match = jettyHttpExchange.equals(mockjettyHttpExchange);
// then
assertFalse("This should return false as both instances shouldn't equal",match);
}
@Test
public void testRequestHeaders() throws Exception
{
// given
when(request.getHeaderNames()).thenReturn(Collections.enumeration(getAcceptCharsetHeader().keySet()));
when(request.getHeaders(SpiConstants.ACCEPT_CHARSET)).thenReturn(Collections.enumeration(getAcceptCharsetHeader().get(SpiConstants.ACCEPT_CHARSET)));
// when
headers = jettyHttpExchange.getRequestHeaders();
// then
assertTrue("CharSetKey must be registered in headers list",headers.containsKey(SpiConstants.ACCEPT_CHARSET));
assertEquals("Charset value must be UTF8",SpiConstants.UTF_8,headers.get(SpiConstants.ACCEPT_CHARSET).get(SpiConstants.ZERO));
}
private Map<String, List<String>> getAcceptCharsetHeader()
{
Map<String, List<String>> headers = new Hashtable<>();
ArrayList<String> valueSet = new ArrayList<String>();
valueSet.add(SpiConstants.UTF_8);
headers.put(SpiConstants.ACCEPT_CHARSET,valueSet);
return headers;
}
@Test
public void testResponseHeaders() throws Exception
{
// when
jettyHttpExchange.sendResponseHeaders(200,1000);
// then
assertEquals("Response must be equal to 200",200,jettyHttpExchange.getResponseCode());
}
@Test
public void testInputStream() throws Exception
{
// given
InputStream is = mock(InputStream.class);
OutputStream os = mock(OutputStream.class);
// when
jettyHttpExchange.setStreams(is,os);
// then
assertEquals("Input stream must be equal",is,jettyHttpExchange.getRequestBody());
assertEquals("Output stream must be equal",os,jettyHttpExchange.getResponseBody());
}
@Test
public void testAttributes() throws Exception
{
// given
when(request.getAttribute("tone")).thenReturn("vone");
// when
jettyHttpExchange.setAttribute("tone","vone");
// then
assertEquals("Attribute value must be equal to vone","vone",(String)jettyHttpExchange.getAttribute("tone"));
}
}

View File

@ -1,46 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.powermock.api.mockito.PowerMockito.mock;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import com.sun.net.httpserver.HttpContext;
public class JettyHttpExchangeBase
{
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpContext context;
protected JettyHttpExchange jettyHttpExchange;
@Before
public void setUp() throws Exception
{
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
context = mock(HttpContext.class);
jettyHttpExchange = new JettyHttpExchange(context,request,response);
}
}

View File

@ -1,168 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.junit.Test;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpPrincipal;
public class JettyHttpExchangeBasicOperationsTest extends JettyHttpExchangeBase
{
private InetSocketAddress address;
private URI uri;
private String reqMethod;
private String protocol;
private HttpPrincipal principal;
@Test
public void testBasicOperations()
{
assertNotNull("Hashcode shouldn't be null",jettyHttpExchange.hashCode());
assertNotNull("String representation shouldn't be null",jettyHttpExchange.toString());
assertEquals("Context should be equal",context,jettyHttpExchange.getHttpContext());
assertEquals("Default size must be equal to zero",SpiConstants.ZERO,jettyHttpExchange.getResponseHeaders().size());
}
@Test
public void testUri() throws Exception
{
// given
when(request.getRequestURI()).thenReturn(SpiConstants.REQUEST_URI);
when(request.getQueryString()).thenReturn(SpiConstants.QUERY_STRING);
// when
uri = jettyHttpExchange.getRequestURI();
// then
assertEquals("Query strings must be equal",SpiConstants.QUERY_STRING,uri.getQuery());
assertEquals("Query strings must be equal",SpiConstants.REQUEST_URI,uri.getPath());
}
@Test
public void testRemoteAddress() throws Exception
{
// given
when(request.getRemoteAddr()).thenReturn(SpiConstants.LOCAL_HOST);
when(request.getRemotePort()).thenReturn(SpiConstants.DEFAULT_PORT);
// when
address = jettyHttpExchange.getRemoteAddress();
// then
assertEquals("Host name must be equal with local host",SpiConstants.LOCAL_HOST,address.getHostName());
assertEquals("Port value must be equal to default port",SpiConstants.DEFAULT_PORT,address.getPort());
}
@Test
public void testLocalAddress() throws Exception
{
// given
when(request.getLocalAddr()).thenReturn(SpiConstants.LOCAL_HOST);
when(request.getLocalPort()).thenReturn(SpiConstants.DEFAULT_PORT);
// when
address = jettyHttpExchange.getLocalAddress();
// then
assertEquals("Host name must be equal with local host",SpiConstants.LOCAL_HOST,address.getHostName());
assertEquals("Port value must be equal to default port",SpiConstants.DEFAULT_PORT,address.getPort());
}
@Test
public void testGetMethod() throws Exception
{
// given
when(request.getMethod()).thenReturn(SpiConstants.REQUEST_METHOD);
// when
reqMethod = jettyHttpExchange.getRequestMethod();
// then
assertEquals("Request method must be POST",SpiConstants.REQUEST_METHOD,reqMethod);
}
@Test
public void testProtocol() throws Exception
{
// given
when(request.getProtocol()).thenReturn(SpiConstants.PROTOCOL);
// when
protocol = jettyHttpExchange.getProtocol();
// then
assertEquals("Protocol must be equal to HTTP",SpiConstants.PROTOCOL,protocol);
}
@Test
public void testPrincipal() throws Exception
{
// given
principal = mock(HttpPrincipal.class);
// when
jettyHttpExchange.setPrincipal(principal);
// then
assertEquals("Principal instances must be equal",principal,jettyHttpExchange.getPrincipal());
}
@Test(expected = RuntimeException.class)
public void testClose() throws Exception
{
// given
doOutputStreamSetup();
// when
jettyHttpExchange.close();
jettyHttpExchange.close();
// then
fail("A RuntimeException must have occured by now as we are closing a stream which has been already closed");
}
private void doOutputStreamSetup() throws Exception
{
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
context = mock(HttpContext.class);
ServletOutputStream os = mock(ServletOutputStream.class);
doNothing().doThrow(new IOException("Test")).when(os).close();
when(response.getOutputStream()).thenReturn(os);
jettyHttpExchange = new JettyHttpExchange(context,request,response);
}
}

View File

@ -1,80 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import java.io.IOException;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.junit.Before;
import org.junit.Test;
import com.sun.net.httpserver.HttpContext;
public class JettyHttpExchangeDelegateTest
{
private HttpContext jaxWsContext;
private HttpServletRequest req;
private HttpServletResponse resp;
private JettyHttpExchangeDelegate httpDelegate;
@Before
public void setUp() throws Exception
{
jaxWsContext = mock(HttpContext.class);
req = mock(HttpServletRequest.class);
resp = mock(HttpServletResponse.class);
}
@Test(expected = RuntimeException.class)
public void testInputStreamRuntimeException() throws Exception
{
// given
when(req.getInputStream()).thenThrow(new IOException());
// when
new JettyHttpExchangeDelegate(jaxWsContext,req,resp);
// then
fail("A RuntimeException must have been occured by now as getInputStream() throwing exception");
}
@Test
public void testGetRequestUri()
{
// given
httpDelegate = new JettyHttpExchangeDelegate(jaxWsContext,req,resp);
when(req.getQueryString()).thenReturn(null);
when(req.getRequestURI()).thenReturn(SpiConstants.REQUEST_URI);
// when
URI uri = httpDelegate.getRequestURI();
// then
assertNull("QueryString must be null as we set it up in request scope",uri.getQuery());
}
}

View File

@ -1,59 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.log.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.powermock.reflect.Whitebox;
public class JettyHttpServerBase
{
protected JettyHttpServer jettyHttpServer;
@BeforeClass
public static void setUpBeforeClass()
{
Log.getRootLogger().setDebugEnabled(true);
}
@Before
public void setUp() throws Exception
{
jettyHttpServer = new JettyHttpServer(new Server(),false);
}
@After
public void tearDown() throws Exception
{
if (jettyHttpServer != null)
{
Server server = Whitebox.getInternalState(jettyHttpServer,"_server");
if (server.getBeans(NetworkConnector.class) != null)
{
jettyHttpServer.stop(SpiConstants.DELAY);
}
}
}
}

View File

@ -1,65 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerCollection;
public class JettyHttpServerCreateContextBase
{
protected JettyHttpServer jettyHttpServer;
protected Server getContextHandlerServer()
{
// context handler default path is "/"
Handler handler = new ContextHandler();
Server server = new Server();
server.setHandler(handler);
return server;
}
protected Server getContextHandlerCollectionServer()
{
Handler handler = new ContextHandlerCollection();
Server server = new Server();
server.setHandler(handler);
return server;
}
protected Server getContextHandlerCollectionsServer()
{
ContextHandlerCollection handler = new ContextHandlerCollection();
Handler[] handles =
{ handler };
HandlerCollection contextHandler = new HandlerCollection();
contextHandler.setHandlers(handles);
Server server = new Server();
server.setHandler(contextHandler);
return server;
}
protected void initializeJettyHttpServer(Server server)
{
jettyHttpServer = new JettyHttpServer(server,false);
}
}

View File

@ -1,117 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.server.Server;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.sun.net.httpserver.HttpContext;
public class JettyHttpServerCreateContextTest extends JettyHttpServerCreateContextBase
{
private HttpContext context;
private Server server;
@Before
public void setUp() throws Exception
{
initializeJettyHttpServer(new Server());
}
@After
public void tearDown() throws Exception
{
if (jettyHttpServer != null)
{
jettyHttpServer.stop(SpiConstants.ONE);
}
}
@Test(expected = RuntimeException.class)
public void testWithoutContextHandler()
{
// when
jettyHttpServer.createContext("/");
// then
fail("A runtime exception must have occured by now as We haven't configure at " + "least one context handler collection.");
}
@Test(expected = RuntimeException.class)
public void testWithContextHandler()
{
// given
server = getContextHandlerServer();
initializeJettyHttpServer(server);
// when
jettyHttpServer.createContext("/");
// then
fail("A runtime exception must have occured by now as another context already bound to the given path.");
}
@Test(expected = RuntimeException.class)
public void testWithoutMatchedContextHandler()
{
// given
server = getContextHandlerServer();
initializeJettyHttpServer(server);
// when
jettyHttpServer.createContext("/a-context-that-does-not-exist");
// then
fail("A runtime exception must have occured by now as there is no matching " + "context handler collection has found.");
}
@Test
public void testWithMatchedContextHandler()
{
// given
server = getContextHandlerCollectionServer();
initializeJettyHttpServer(server);
// when
context = jettyHttpServer.createContext("/");
// then
assertEquals("Path must be equal to /","/",context.getPath());
}
@Test
public void testWithMatchedContextHandlerCollections()
{
// given
server = getContextHandlerCollectionsServer();
initializeJettyHttpServer(server);
// when
context = jettyHttpServer.createContext("/");
// then
assertEquals("Path must be equal to /","/",context.getPath());
}
}

View File

@ -1,118 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertNull;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.io.IOException;
import java.util.concurrent.Executor;
import org.eclipse.jetty.http.spi.util.Pool;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
@PrepareForTest(JettyHttpServer.class)
public class JettyHttpServerExceptionsTest extends JettyHttpServerBase
{
private Executor executor;
@Test(expected = IllegalArgumentException.class)
public void testSetExecutorIllegalArgumentException()
{
// given
executor = null;
// when
jettyHttpServer.setExecutor(executor);
// then
fail("An IllegalArgumentException must have occured by now as executor is null");
}
@Test(expected = UnsupportedOperationException.class)
public void testSetExecutorUnsupportedOperationException()
{
// given
executor = SpiUtility.getThreadPoolExecutor(Pool.CORE_POOL_SIZE.getValue(),SpiConstants.poolInfo);
// when
jettyHttpServer.setExecutor(executor);
// then
fail("An UnsupportedOperationException must have occured by now as executor " + "instance is not of type DelegatingThreadPool");
}
@Test(expected = IOException.class)
public void testBindIOException() throws Exception
{
// given
setUpForBindException();
// when
jettyHttpServer.stop(SpiConstants.DELAY);
// then
fail("A IOException must have occured by now as the server shared value is true");
}
private void setUpForBindException() throws Exception
{
jettyHttpServer = new JettyHttpServer(new Server(),true);
jettyHttpServer.start();
SpiUtility.callBind(jettyHttpServer);
}
@Test(expected = RuntimeException.class)
public void testStopServer() throws Exception
{
// given
Server server = mock(Server.class);
when(server.getBeans(NetworkConnector.class)).thenReturn(null);
jettyHttpServer = new JettyHttpServer(server,false);
jettyHttpServer.bind(SpiUtility.getInetSocketAddress(),SpiConstants.BACK_LOG);
// when
jettyHttpServer.stop(SpiConstants.DELAY);
// then
fail("A RuntimeException must have occured by now as we are stopping the server with wrong object");
}
@Test
public void test() throws Exception
{
// when
ContextHandlerCollection handler = Whitebox.<ContextHandlerCollection> invokeMethod(jettyHttpServer,"findContextHandlerCollection",new Object[]
{ null });
// then
assertNull("Handler must be null as handlers parameter is null",handler);
}
}

View File

@ -1,90 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import java.io.IOException;
import java.net.InetSocketAddress;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.server.Server;
import org.junit.After;
import org.junit.Test;
import com.sun.net.httpserver.HttpServer;
public class JettyHttpServerProviderTest
{
private HttpServer jettyHttpServer;
@After
public void tearDown() throws Exception
{
JettyHttpServerProvider.setServer(null);
if (jettyHttpServer != null)
{
jettyHttpServer.stop(SpiConstants.ONE);
}
}
@Test
public void testCreateHttpServer() throws Exception
{
// when
initializeHttpServerProvider();
// then
assertNotNull("HttpServer instance shouldn't be null after server creation",jettyHttpServer);
}
@Test(expected = IOException.class)
public void testCreateHttpServerIOException() throws Exception
{
// given
Server server = new Server();
JettyHttpServerProvider.setServer(server);
// when
initializeHttpServerProvider();
// then
fail("A IOException must have occured by now as port is in use and shared flag is on");
}
@Test(expected = UnsupportedOperationException.class)
public void testcreateHttpsServerUnsupportedOperationException() throws Exception
{
// given
initializeHttpServerProvider();
JettyHttpServerProvider jettyHttpServerProvider = new JettyHttpServerProvider();
// when
jettyHttpServerProvider.createHttpsServer(new InetSocketAddress("localhost",SpiConstants.ONE),SpiConstants.BACK_LOG);
// then
fail("A UnsupportedOperationException must have occured by now as " + "JettyHttpServerProvider not supporting this operation");
}
private void initializeHttpServerProvider() throws Exception
{
String localHost = "localhost";
int port = SpiConstants.ONE;
jettyHttpServer = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(localHost,port),SpiConstants.BACK_LOG);
}
}

View File

@ -1,175 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(JettyHttpServer.class)
public class JettyHttpServerTest extends JettyHttpServerBase
{
private DelegatingThreadPool delegatingThreadPool;
private Executor executor;
private Executor actualExecutor;
private HttpConfiguration httpConfiguration;
private InetSocketAddress inetSocketAddress;
private InetSocketAddress address;
private ServerConnector serverConnector;
private HttpConfiguration configuration;
@Test
public void testSetExecutor()
{
// given
delegatingThreadPool = SpiUtility.getDelegatingThreadPool();
jettyHttpServer = new JettyHttpServer(new Server(delegatingThreadPool),false);
executor = SpiUtility.getDelegatingThreadPool();
jettyHttpServer.setExecutor(executor);
// when
actualExecutor = jettyHttpServer.getExecutor();
// then
assertEquals("Executor instances must be equal.",executor,actualExecutor);
}
@Test
public void testGetExecutor() throws Exception
{
// when
executor = jettyHttpServer.getExecutor();
// then
assertNotNull("Executor instance shouldn't be null after server creation",executor);
}
@Test
public void testGetDefaultHttpConfiguration() throws Exception
{
// when
httpConfiguration = jettyHttpServer.getHttpConfiguration();
// then
assertNotNull("HttpConfiguratoin instance shouldn't be null after server creation",httpConfiguration);
}
@Test
public void testGetCustomHttpConfiguration() throws Exception
{
// given
configuration = new HttpConfiguration();
// when
jettyHttpServer = new JettyHttpServer(new Server(),false,configuration);
// then
assertEquals("Configuration instance must be equal.",configuration,jettyHttpServer.getHttpConfiguration());
}
@Test
public void testInetSocketAddress() throws Exception
{
// given
inetSocketAddress = new InetSocketAddress(SpiConstants.LOCAL_HOST,8080);
// when
jettyHttpServer.bind(inetSocketAddress,SpiConstants.BACK_LOG);
// then
assertEquals("InetSocketAddress instances must be equal",inetSocketAddress,jettyHttpServer.getAddress());
}
@Test
public void testBindWithNewPort() throws Exception
{
// given
SpiUtility.callBind(jettyHttpServer);
inetSocketAddress = new InetSocketAddress(SpiConstants.LOCAL_HOST,8082);
// when
jettyHttpServer.bind(inetSocketAddress,8082);
// then
assertEquals("InetSocketAddress instances must be equal",inetSocketAddress,jettyHttpServer.getAddress());
}
@Test
public void testBindWithNewPortWithDebugDisable() throws Exception
{
// given
SpiUtility.callBind(jettyHttpServer);
inetSocketAddress = new InetSocketAddress(SpiConstants.LOCAL_HOST,8082);
Log.getRootLogger().setDebugEnabled(false);
// when
jettyHttpServer.bind(inetSocketAddress,8082);
// then
assertEquals("InetSocketAddress instances must be equal",inetSocketAddress,jettyHttpServer.getAddress());
}
@Test
public void testServerConnector()
{
// given
address = new InetSocketAddress(SpiConstants.DEFAULT_PORT);
// when
serverConnector = jettyHttpServer.newServerConnector(address,SpiConstants.HUNDRED);
// then
assertEquals("Port value must be equal to default port value",SpiConstants.DEFAULT_PORT,serverConnector.getPort());
}
@Test(expected = UnsupportedOperationException.class)
public void testStart()
{
// given
jettyHttpServer.start();
executor = SpiUtility.getDelegatingThreadPool();
// when
jettyHttpServer.setExecutor(executor);
// then
fail("An Unsupported Operation exception must have been raised by now as we cannot " + "reset executor after server started.");
}
}

View File

@ -1,100 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.eclipse.jetty.http.spi.util.SpiUtility;
import org.junit.Test;
import com.sun.net.httpserver.Headers;
public class JettyHttpsExchangeAdvancedOperationsTest extends JettyHttpsExchangeBase
{
private JettyHttpsExchange mockJettyHttpsExchange;
private Boolean match;
private Headers headers;
private InputStream is;
private OutputStream os;
@Test
public void testAdvancedOperations() throws Exception
{
// given
mockJettyHttpsExchange = mock(JettyHttpsExchange.class);
// when
match = jettyHttpsExchange.equals(mockJettyHttpsExchange);
// then
assertFalse("This should return false as both instances shouldn't equal",match);
}
@Test
public void testRequestHeaders() throws Exception
{
// given
when(request.getHeaderNames()).thenReturn(Collections.enumeration(SpiUtility.getAcceptCharsetHeader().keySet()));
when(request.getHeaders(SpiConstants.ACCEPT_CHARSET))
.thenReturn(Collections.enumeration(SpiUtility.getAcceptCharsetHeader().get(SpiConstants.ACCEPT_CHARSET)));
// when
headers = jettyHttpsExchange.getRequestHeaders();
// then
assertTrue("CharSetKey must be registered in headers list",headers.containsKey(SpiConstants.ACCEPT_CHARSET));
assertEquals("Charset value must be UTF8",SpiConstants.UTF_8,headers.get(SpiConstants.ACCEPT_CHARSET).get(SpiConstants.ZERO));
}
@Test
public void testResponseHeaders() throws Exception
{
// when
jettyHttpsExchange.sendResponseHeaders(SpiConstants.TWO_HUNDRED,SpiConstants.THOUSAND);
// then
assertEquals("Response must be equal to 200",SpiConstants.TWO_HUNDRED,(Integer)jettyHttpsExchange.getResponseCode());
}
@Test
public void testInputStream() throws Exception
{
// given
is = mock(InputStream.class);
os = mock(OutputStream.class);
// when
jettyHttpsExchange.setStreams(is,os);
// then
assertEquals("Input stream must be equal",is,jettyHttpsExchange.getRequestBody());
assertEquals("Output stream must be equal",os,jettyHttpsExchange.getResponseBody());
}
}

View File

@ -1,46 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.powermock.api.mockito.PowerMockito.mock;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import com.sun.net.httpserver.HttpContext;
public class JettyHttpsExchangeBase
{
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpContext context;
protected JettyHttpsExchange jettyHttpsExchange;
@Before
public void setUp() throws Exception
{
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
context = mock(HttpContext.class);
jettyHttpsExchange = new JettyHttpsExchange(context,request,response);
}
}

View File

@ -1,170 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.spi.util.SpiConstants;
import org.junit.Test;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpPrincipal;
public class JettyHttpsExchangeBasicOperationsTest extends JettyHttpsExchangeBase
{
private InetSocketAddress address;
private URI uri;
private String reqMethod;
private String protocol;
private HttpPrincipal principal;
@Test
public void testBasicOperations()
{
assertNotNull("Hashcode shouldn't be null",jettyHttpsExchange.hashCode());
assertNotNull("String representation shouldn't be null",jettyHttpsExchange.toString());
assertEquals("Context should be equal",context,jettyHttpsExchange.getHttpContext());
assertNull("SSL session must be null as this method call always returns null",jettyHttpsExchange.getSSLSession());
assertEquals("Default size must be equal to zero",SpiConstants.ZERO,jettyHttpsExchange.getResponseHeaders().size());
}
@Test
public void testUri() throws Exception
{
// given
when(request.getRequestURI()).thenReturn(SpiConstants.REQUEST_URI);
when(request.getQueryString()).thenReturn(SpiConstants.QUERY_STRING);
// when
uri = jettyHttpsExchange.getRequestURI();
// then
assertEquals("Query strings must be equal",SpiConstants.QUERY_STRING,uri.getQuery());
assertEquals("Query strings must be equal",SpiConstants.REQUEST_URI,uri.getPath());
}
@Test
public void testRemoteAddress() throws Exception
{
// given
when(request.getRemoteAddr()).thenReturn(SpiConstants.LOCAL_HOST);
when(request.getRemotePort()).thenReturn(SpiConstants.DEFAULT_PORT);
// when
address = jettyHttpsExchange.getRemoteAddress();
// then
assertEquals("Host name must be equal with local host",SpiConstants.LOCAL_HOST,address.getHostName());
assertEquals("Port value must be equal to default port",SpiConstants.DEFAULT_PORT,address.getPort());
}
@Test
public void testLocalAddress() throws Exception
{
// given
when(request.getLocalAddr()).thenReturn(SpiConstants.LOCAL_HOST);
when(request.getLocalPort()).thenReturn(SpiConstants.DEFAULT_PORT);
// when
address = jettyHttpsExchange.getLocalAddress();
// then
assertEquals("Host name must be equal with local host",SpiConstants.LOCAL_HOST,address.getHostName());
assertEquals("Port value must be equal to default port",SpiConstants.DEFAULT_PORT,address.getPort());
}
@Test
public void testGetMethod() throws Exception
{
// given
when(request.getMethod()).thenReturn(SpiConstants.REQUEST_METHOD);
// when
reqMethod = jettyHttpsExchange.getRequestMethod();
// then
assertEquals("Request method must be POST",SpiConstants.REQUEST_METHOD,reqMethod);
}
@Test
public void testProtocol() throws Exception
{
// given
when(request.getProtocol()).thenReturn(SpiConstants.PROTOCOL);
// when
protocol = jettyHttpsExchange.getProtocol();
// then
assertEquals("Protocol must be equal to HTTP",SpiConstants.PROTOCOL,protocol);
}
@Test
public void testPrincipal() throws Exception
{
// given
principal = mock(HttpPrincipal.class);
// when
jettyHttpsExchange.setPrincipal(principal);
// then
assertEquals("Principal instances must be equal",principal,jettyHttpsExchange.getPrincipal());
}
@Test(expected = RuntimeException.class)
public void testClose() throws Exception
{
// given
doOutputStreamSetup();
// when
jettyHttpsExchange.close();
jettyHttpsExchange.close();
// then
fail("A RuntimeException must have occured by now as we are closing a stream which has been already closed");
}
private void doOutputStreamSetup() throws Exception
{
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
context = mock(HttpContext.class);
ServletOutputStream os = mock(ServletOutputStream.class);
doNothing().doThrow(new IOException("Test")).when(os).close();
when(response.getOutputStream()).thenReturn(os);
jettyHttpsExchange = new JettyHttpsExchange(context,request,response);
}
}

View File

@ -1,48 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
/*
* This class tests all the getters and setters for a given list of classes.
*/
public class PojoTest
{
private Validator validator;
@Test
public void testOpenPojo()
{
validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
List<Class> classes = Arrays.asList(DelegatingThreadPool.class,JettyExchange.class,JettyHttpServer.class,JettyHttpServerProvider.class);
for (Class clazz : classes)
{
validator.validate(PojoClassFactory.getPojoClass(clazz));
}
}
}

View File

@ -0,0 +1,142 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.net.ssl.HttpsURLConnection;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.sun.net.httpserver.BasicAuthenticator;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class SPIServerTest
{
String host = "localhost";
HttpServer server;
int port;
@Before
public void before() throws Exception
{
server = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(host,0),10);
server.start();
port = server.getAddress().getPort();
System.err.println(port);
}
@After
public void after() throws Exception
{
server.stop(0);
}
@Test
public void testSimple() throws Exception
{
server.createContext("/",new HttpHandler()
{
public void handle(HttpExchange exchange) throws IOException
{
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type","text/plain");
exchange.sendResponseHeaders(200,0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write("Hello".getBytes(StandardCharsets.ISO_8859_1));
responseBody.close();
}
});
URL url = new URL("http://localhost:"+port+"/");
assertThat(IO.toString(url.openConnection().getInputStream()),is("Hello"));
}
@Test
public void testAuth() throws Exception
{
final HttpContext httpContext = server.createContext("/",new HttpHandler()
{
public void handle(HttpExchange exchange) throws IOException
{
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type","text/plain");
exchange.sendResponseHeaders(200,0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write("Hello".getBytes(StandardCharsets.ISO_8859_1));
responseBody.close();
}
});
httpContext.setAuthenticator(new BasicAuthenticator("Test")
{
@Override
public boolean checkCredentials(String username, String password)
{
if ("username".equals(username) && password.equals("password"))
return true;
return false;
}
});
URL url = new URL("http://localhost:"+port+"/");
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
assertThat(client.getResponseCode(),is(401));
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
client = (HttpURLConnection)url.openConnection();
String userpass = "username:password";
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(userpass.getBytes(StandardCharsets.ISO_8859_1));
client.setRequestProperty ("Authorization", basicAuth);
client.connect();
assertThat(client.getResponseCode(),is(200));
assertThat(IO.toString(client.getInputStream()),is("Hello"));
}
}

View File

@ -1,84 +0,0 @@
//
// ========================================================================
// Copyright (c) 1995-2017 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.spi;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.sun.net.httpserver.BasicAuthenticator;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class TestSPIServer
{
public static void main(String[] args) throws Exception
{
String host = "localhost";
int port = 8080;
HttpServer server = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(host,port),10);
server.start();
final HttpContext httpContext = server.createContext("/",new HttpHandler()
{
public void handle(HttpExchange exchange) throws IOException
{
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type","text/plain");
exchange.sendResponseHeaders(200,0);
OutputStream responseBody = exchange.getResponseBody();
Headers requestHeaders = exchange.getRequestHeaders();
Set<String> keySet = requestHeaders.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext())
{
String key = iter.next();
List values = requestHeaders.get(key);
String s = key + " = " + values.toString() + "\n";
responseBody.write(s.getBytes());
}
responseBody.close();
}
});
httpContext.setAuthenticator(new BasicAuthenticator("Test")
{
@Override
public boolean checkCredentials(String username, String password)
{
if ("username".equals(username) && password.equals("password"))
return true;
return false;
}
});
Thread.sleep(10000000);
}
}