Fixing CRLF issues.

Signed-off-by: Joakim Erdfelt <joakim.erdfelt@gmail.com>
This commit is contained in:
Joakim Erdfelt 2019-04-03 15:24:29 -05:00
parent cdd553332c
commit 1f046f44fe
8 changed files with 1333 additions and 1333 deletions

View File

@ -1,162 +1,162 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.http.spi; package org.eclipse.jetty.http.spi;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.Authenticator.Result; import com.sun.net.httpserver.Authenticator.Result;
import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpPrincipal; import com.sun.net.httpserver.HttpPrincipal;
/** /**
* Jetty handler that bridges requests to {@link HttpHandler}. * Jetty handler that bridges requests to {@link HttpHandler}.
*/ */
public class HttpSpiContextHandler extends ContextHandler public class HttpSpiContextHandler extends ContextHandler
{ {
public static final Logger LOG = Log.getLogger(HttpSpiContextHandler.class); public static final Logger LOG = Log.getLogger(HttpSpiContextHandler.class);
private HttpContext _httpContext; private HttpContext _httpContext;
private HttpHandler _httpHandler; private HttpHandler _httpHandler;
public HttpSpiContextHandler(HttpContext httpContext, HttpHandler httpHandler) public HttpSpiContextHandler(HttpContext httpContext, HttpHandler httpHandler)
{ {
this._httpContext = httpContext; this._httpContext = httpContext;
this._httpHandler = httpHandler; this._httpHandler = httpHandler;
} }
@Override @Override
public void doScope(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException public void doScope(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
{ {
if (!target.startsWith(getContextPath())) if (!target.startsWith(getContextPath()))
{ {
return; return;
} }
HttpExchange jettyHttpExchange; HttpExchange jettyHttpExchange;
if (baseRequest.isSecure()) if (baseRequest.isSecure())
{ {
jettyHttpExchange = new JettyHttpsExchange(_httpContext,req,resp); jettyHttpExchange = new JettyHttpsExchange(_httpContext,req,resp);
} }
else else
{ {
jettyHttpExchange = new JettyHttpExchange(_httpContext,req,resp); jettyHttpExchange = new JettyHttpExchange(_httpContext,req,resp);
} }
// TODO: add filters processing // TODO: add filters processing
try try
{ {
Authenticator auth = _httpContext.getAuthenticator(); Authenticator auth = _httpContext.getAuthenticator();
if (auth != null) if (auth != null)
{ {
handleAuthentication(resp,jettyHttpExchange,auth); handleAuthentication(resp,jettyHttpExchange,auth);
} }
else else
{ {
_httpHandler.handle(jettyHttpExchange); _httpHandler.handle(jettyHttpExchange);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
LOG.debug(ex); LOG.debug(ex);
PrintWriter writer = new PrintWriter(jettyHttpExchange.getResponseBody()); PrintWriter writer = new PrintWriter(jettyHttpExchange.getResponseBody());
resp.setStatus(500); resp.setStatus(500);
writer.println("<h2>HTTP ERROR: 500</h2>"); writer.println("<h2>HTTP ERROR: 500</h2>");
writer.println("<pre>INTERNAL_SERVER_ERROR</pre>"); writer.println("<pre>INTERNAL_SERVER_ERROR</pre>");
writer.println("<p>RequestURI=" + StringUtil.sanitizeXmlString(req.getRequestURI()) + "</p>"); writer.println("<p>RequestURI=" + StringUtil.sanitizeXmlString(req.getRequestURI()) + "</p>");
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
{ {
writer.println("<pre>"); writer.println("<pre>");
ex.printStackTrace(writer); ex.printStackTrace(writer);
writer.println("</pre>"); writer.println("</pre>");
} }
writer.println("<p><i><small><a href=\"http://eclipse.org/jetty\">Powered by jetty://</a></small></i></p>"); writer.println("<p><i><small><a href=\"http://eclipse.org/jetty\">Powered by jetty://</a></small></i></p>");
writer.close(); writer.close();
} }
finally finally
{ {
baseRequest.setHandled(true); baseRequest.setHandled(true);
} }
} }
private void handleAuthentication(HttpServletResponse resp, HttpExchange httpExchange, Authenticator auth) throws IOException private void handleAuthentication(HttpServletResponse resp, HttpExchange httpExchange, Authenticator auth) throws IOException
{ {
Result result = auth.authenticate(httpExchange); Result result = auth.authenticate(httpExchange);
if (result instanceof Authenticator.Failure) if (result instanceof Authenticator.Failure)
{ {
int rc = ((Authenticator.Failure)result).getResponseCode(); int rc = ((Authenticator.Failure)result).getResponseCode();
for (Map.Entry<String,List<String>> header : httpExchange.getResponseHeaders().entrySet()) for (Map.Entry<String,List<String>> header : httpExchange.getResponseHeaders().entrySet())
{ {
for (String value : header.getValue()) for (String value : header.getValue())
resp.addHeader(header.getKey(),value); resp.addHeader(header.getKey(),value);
} }
resp.sendError(rc); resp.sendError(rc);
} }
else if (result instanceof Authenticator.Retry) else if (result instanceof Authenticator.Retry)
{ {
int rc = ((Authenticator.Retry)result).getResponseCode(); int rc = ((Authenticator.Retry)result).getResponseCode();
for (Map.Entry<String,List<String>> header : httpExchange.getResponseHeaders().entrySet()) for (Map.Entry<String,List<String>> header : httpExchange.getResponseHeaders().entrySet())
{ {
for (String value : header.getValue()) for (String value : header.getValue())
resp.addHeader(header.getKey(),value); resp.addHeader(header.getKey(),value);
} }
resp.setStatus(rc); resp.setStatus(rc);
resp.flushBuffer(); resp.flushBuffer();
} }
else if (result instanceof Authenticator.Success) else if (result instanceof Authenticator.Success)
{ {
HttpPrincipal principal = ((Authenticator.Success)result).getPrincipal(); HttpPrincipal principal = ((Authenticator.Success)result).getPrincipal();
((JettyExchange)httpExchange).setPrincipal(principal); ((JettyExchange)httpExchange).setPrincipal(principal);
_httpHandler.handle(httpExchange); _httpHandler.handle(httpExchange);
} }
} }
public HttpHandler getHttpHandler() public HttpHandler getHttpHandler()
{ {
return _httpHandler; return _httpHandler;
} }
public void setHttpHandler(HttpHandler handler) public void setHttpHandler(HttpHandler handler)
{ {
this._httpHandler = handler; this._httpHandler = handler;
} }
} }

View File

@ -1,111 +1,111 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.http.spi; package org.eclipse.jetty.http.spi;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.Filter; import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
/** /**
* Jetty implementation of {@link com.sun.net.httpserver.HttpContext} * Jetty implementation of {@link com.sun.net.httpserver.HttpContext}
*/ */
public class JettyHttpContext extends com.sun.net.httpserver.HttpContext public class JettyHttpContext extends com.sun.net.httpserver.HttpContext
{ {
private HttpSpiContextHandler _jettyContextHandler; private HttpSpiContextHandler _jettyContextHandler;
private HttpServer _server; private HttpServer _server;
private Map<String,Object> _attributes = new HashMap<String,Object>(); private Map<String,Object> _attributes = new HashMap<String,Object>();
private List<Filter> _filters = new ArrayList<Filter>(); private List<Filter> _filters = new ArrayList<Filter>();
private Authenticator _authenticator; private Authenticator _authenticator;
protected JettyHttpContext(HttpServer server, String path, protected JettyHttpContext(HttpServer server, String path,
HttpHandler handler) HttpHandler handler)
{ {
this._server = server; this._server = server;
_jettyContextHandler = new HttpSpiContextHandler(this, handler); _jettyContextHandler = new HttpSpiContextHandler(this, handler);
_jettyContextHandler.setContextPath(path); _jettyContextHandler.setContextPath(path);
} }
protected HttpSpiContextHandler getJettyContextHandler() protected HttpSpiContextHandler getJettyContextHandler()
{ {
return _jettyContextHandler; return _jettyContextHandler;
} }
@Override @Override
public HttpHandler getHandler() public HttpHandler getHandler()
{ {
return _jettyContextHandler.getHttpHandler(); return _jettyContextHandler.getHttpHandler();
} }
@Override @Override
public void setHandler(HttpHandler h) public void setHandler(HttpHandler h)
{ {
_jettyContextHandler.setHttpHandler(h); _jettyContextHandler.setHttpHandler(h);
} }
@Override @Override
public String getPath() public String getPath()
{ {
return _jettyContextHandler.getContextPath(); return _jettyContextHandler.getContextPath();
} }
@Override @Override
public HttpServer getServer() public HttpServer getServer()
{ {
return _server; return _server;
} }
@Override @Override
public Map<String, Object> getAttributes() public Map<String, Object> getAttributes()
{ {
return _attributes; return _attributes;
} }
@Override @Override
public List<Filter> getFilters() public List<Filter> getFilters()
{ {
return _filters; return _filters;
} }
@Override @Override
public Authenticator setAuthenticator(Authenticator auth) public Authenticator setAuthenticator(Authenticator auth)
{ {
Authenticator previous = _authenticator; Authenticator previous = _authenticator;
_authenticator = auth; _authenticator = auth;
return previous; return previous;
} }
@Override @Override
public Authenticator getAuthenticator() public Authenticator getAuthenticator()
{ {
return _authenticator; return _authenticator;
} }
} }

View File

@ -1,233 +1,233 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.http.spi; package org.eclipse.jetty.http.spi;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpPrincipal; import com.sun.net.httpserver.HttpPrincipal;
/** /**
* Jetty implementation of {@link com.sun.net.httpserver.HttpExchange} * Jetty implementation of {@link com.sun.net.httpserver.HttpExchange}
*/ */
public class JettyHttpExchangeDelegate extends HttpExchange public class JettyHttpExchangeDelegate extends HttpExchange
{ {
private HttpContext _httpContext; private HttpContext _httpContext;
private HttpServletRequest _req; private HttpServletRequest _req;
private HttpServletResponse _resp; private HttpServletResponse _resp;
private Headers _responseHeaders = new Headers(); private Headers _responseHeaders = new Headers();
private int _responseCode = 0; private int _responseCode = 0;
private InputStream _is; private InputStream _is;
private OutputStream _os; private OutputStream _os;
private HttpPrincipal _httpPrincipal; private HttpPrincipal _httpPrincipal;
JettyHttpExchangeDelegate(HttpContext jaxWsContext, HttpServletRequest req, HttpServletResponse resp) JettyHttpExchangeDelegate(HttpContext jaxWsContext, HttpServletRequest req, HttpServletResponse resp)
{ {
this._httpContext = jaxWsContext; this._httpContext = jaxWsContext;
this._req = req; this._req = req;
this._resp = resp; this._resp = resp;
try try
{ {
this._is = req.getInputStream(); this._is = req.getInputStream();
this._os = resp.getOutputStream(); this._os = resp.getOutputStream();
} }
catch (IOException ex) catch (IOException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
@Override @Override
public Headers getRequestHeaders() public Headers getRequestHeaders()
{ {
Headers headers = new Headers(); Headers headers = new Headers();
Enumeration<?> en = _req.getHeaderNames(); Enumeration<?> en = _req.getHeaderNames();
while (en.hasMoreElements()) while (en.hasMoreElements())
{ {
String name = (String)en.nextElement(); String name = (String)en.nextElement();
Enumeration<?> en2 = _req.getHeaders(name); Enumeration<?> en2 = _req.getHeaders(name);
while (en2.hasMoreElements()) while (en2.hasMoreElements())
{ {
String value = (String)en2.nextElement(); String value = (String)en2.nextElement();
headers.add(name,value); headers.add(name,value);
} }
} }
return headers; return headers;
} }
@Override @Override
public Headers getResponseHeaders() public Headers getResponseHeaders()
{ {
return _responseHeaders; return _responseHeaders;
} }
@Override @Override
public URI getRequestURI() public URI getRequestURI()
{ {
try try
{ {
String uriAsString = _req.getRequestURI(); String uriAsString = _req.getRequestURI();
if (_req.getQueryString() != null) if (_req.getQueryString() != null)
{ {
uriAsString += "?" + _req.getQueryString(); uriAsString += "?" + _req.getQueryString();
} }
return new URI(uriAsString); return new URI(uriAsString);
} }
catch (URISyntaxException ex) catch (URISyntaxException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
@Override @Override
public String getRequestMethod() public String getRequestMethod()
{ {
return _req.getMethod(); return _req.getMethod();
} }
@Override @Override
public HttpContext getHttpContext() public HttpContext getHttpContext()
{ {
return _httpContext; return _httpContext;
} }
@Override @Override
public void close() public void close()
{ {
try try
{ {
_resp.getOutputStream().close(); _resp.getOutputStream().close();
} }
catch (IOException ex) catch (IOException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
@Override @Override
public InputStream getRequestBody() public InputStream getRequestBody()
{ {
return _is; return _is;
} }
@Override @Override
public OutputStream getResponseBody() public OutputStream getResponseBody()
{ {
return _os; return _os;
} }
@Override @Override
public void sendResponseHeaders(int rCode, long responseLength) throws IOException public void sendResponseHeaders(int rCode, long responseLength) throws IOException
{ {
this._responseCode = rCode; this._responseCode = rCode;
for (Map.Entry<String, List<String>> stringListEntry : _responseHeaders.entrySet()) for (Map.Entry<String, List<String>> stringListEntry : _responseHeaders.entrySet())
{ {
String name = stringListEntry.getKey(); String name = stringListEntry.getKey();
List<String> values = stringListEntry.getValue(); List<String> values = stringListEntry.getValue();
for (String value : values) for (String value : values)
{ {
_resp.setHeader(name,value); _resp.setHeader(name,value);
} }
} }
if (responseLength > 0) if (responseLength > 0)
{ {
_resp.setHeader("content-length","" + responseLength); _resp.setHeader("content-length","" + responseLength);
} }
_resp.setStatus(rCode); _resp.setStatus(rCode);
} }
@Override @Override
public InetSocketAddress getRemoteAddress() public InetSocketAddress getRemoteAddress()
{ {
return new InetSocketAddress(_req.getRemoteAddr(),_req.getRemotePort()); return new InetSocketAddress(_req.getRemoteAddr(),_req.getRemotePort());
} }
@Override @Override
public int getResponseCode() public int getResponseCode()
{ {
return _responseCode; return _responseCode;
} }
@Override @Override
public InetSocketAddress getLocalAddress() public InetSocketAddress getLocalAddress()
{ {
return new InetSocketAddress(_req.getLocalAddr(),_req.getLocalPort()); return new InetSocketAddress(_req.getLocalAddr(),_req.getLocalPort());
} }
@Override @Override
public String getProtocol() public String getProtocol()
{ {
return _req.getProtocol(); return _req.getProtocol();
} }
@Override @Override
public Object getAttribute(String name) public Object getAttribute(String name)
{ {
return _req.getAttribute(name); return _req.getAttribute(name);
} }
@Override @Override
public void setAttribute(String name, Object value) public void setAttribute(String name, Object value)
{ {
_req.setAttribute(name,value); _req.setAttribute(name,value);
} }
@Override @Override
public void setStreams(InputStream i, OutputStream o) public void setStreams(InputStream i, OutputStream o)
{ {
_is = i; _is = i;
_os = o; _os = o;
} }
@Override @Override
public HttpPrincipal getPrincipal() public HttpPrincipal getPrincipal()
{ {
return _httpPrincipal; return _httpPrincipal;
} }
public void setPrincipal(HttpPrincipal principal) public void setPrincipal(HttpPrincipal principal)
{ {
this._httpPrincipal = principal; this._httpPrincipal = principal;
} }
} }

View File

@ -1,80 +1,80 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.http.spi; package org.eclipse.jetty.http.spi;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool; import org.eclipse.jetty.util.thread.ThreadPool;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.HttpsServer;
import com.sun.net.httpserver.spi.HttpServerProvider; import com.sun.net.httpserver.spi.HttpServerProvider;
/** /**
* Jetty implementation of <a href="http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/index.html">Java HTTP Server SPI</a> * Jetty implementation of <a href="http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/index.html">Java HTTP Server SPI</a>
*/ */
public class JettyHttpServerProvider extends HttpServerProvider public class JettyHttpServerProvider extends HttpServerProvider
{ {
private static Server _server; private static Server _server;
public static void setServer(Server server) public static void setServer(Server server)
{ {
_server = server; _server = server;
} }
@Override @Override
public HttpServer createHttpServer(InetSocketAddress addr, int backlog) public HttpServer createHttpServer(InetSocketAddress addr, int backlog)
throws IOException throws IOException
{ {
Server server = _server; Server server = _server;
boolean shared = true; boolean shared = true;
if (server == null) if (server == null)
{ {
ThreadPool threadPool = new DelegatingThreadPool(new QueuedThreadPool()); ThreadPool threadPool = new DelegatingThreadPool(new QueuedThreadPool());
server = new Server(threadPool); server = new Server(threadPool);
HandlerCollection handlerCollection = new HandlerCollection(); HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] {new ContextHandlerCollection(), new DefaultHandler()}); handlerCollection.setHandlers(new Handler[] {new ContextHandlerCollection(), new DefaultHandler()});
server.setHandler(handlerCollection); server.setHandler(handlerCollection);
shared = false; shared = false;
} }
JettyHttpServer jettyHttpServer = new JettyHttpServer(server, shared); JettyHttpServer jettyHttpServer = new JettyHttpServer(server, shared);
if (addr != null) if (addr != null)
jettyHttpServer.bind(addr, backlog); jettyHttpServer.bind(addr, backlog);
return jettyHttpServer; return jettyHttpServer;
} }
@Override @Override
public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException
{ {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@ -1,81 +1,81 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.maven.plugin; package org.eclipse.jetty.maven.plugin;
import java.io.File; import java.io.File;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
/** /**
* <p> * <p>
* This goal is used to run Jetty with a pre-assembled war. * This goal is used to run Jetty with a pre-assembled war.
* </p> * </p>
* <p> * <p>
* It accepts exactly the same options as the <a href="run-war-mojo.html">run-war</a> goal. * It accepts exactly the same options as the <a href="run-war-mojo.html">run-war</a> goal.
* However, it doesn't assume that the current artifact is a * However, it doesn't assume that the current artifact is a
* webapp and doesn't try to assemble it into a war before its execution. * webapp and doesn't try to assemble it into a war before its execution.
* So using it makes sense only when used in conjunction with the * So using it makes sense only when used in conjunction with the
* <a href="run-war-mojo.html#webApp">war</a> configuration parameter pointing to a pre-built WAR. * <a href="run-war-mojo.html#webApp">war</a> configuration parameter pointing to a pre-built WAR.
* </p> * </p>
* <p> * <p>
* This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested * This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested
* HTTP client components. * HTTP client components.
* </p> * </p>
* *
* @goal deploy-war * @goal deploy-war
* @requiresDependencyResolution runtime * @requiresDependencyResolution runtime
* @execute phase="validate" * @execute phase="validate"
* @description Deploy a pre-assembled war * @description Deploy a pre-assembled war
* *
*/ */
public class JettyDeployWar extends JettyRunWarMojo public class JettyDeployWar extends JettyRunWarMojo
{ {
/** /**
* If true, the plugin should continue and not block. Otherwise the * If true, the plugin should continue and not block. Otherwise the
* plugin will block further execution and you will need to use * plugin will block further execution and you will need to use
* cntrl-c to stop it. * cntrl-c to stop it.
* *
* *
* @parameter default-value="true" * @parameter default-value="true"
*/ */
protected boolean daemon = true; protected boolean daemon = true;
@Override @Override
public void execute() throws MojoExecutionException, MojoFailureException public void execute() throws MojoExecutionException, MojoFailureException
{ {
nonblocking = daemon; nonblocking = daemon;
super.execute(); super.execute();
} }
@Override @Override
public void finishConfigurationBeforeStart() throws Exception public void finishConfigurationBeforeStart() throws Exception
{ {
super.finishConfigurationBeforeStart(); super.finishConfigurationBeforeStart();
//only stop the server at shutdown if we are blocking //only stop the server at shutdown if we are blocking
server.setStopAtShutdown(!nonblocking); server.setStopAtShutdown(!nonblocking);
} }
} }

View File

@ -1,174 +1,174 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.security; package org.eclipse.jetty.security;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.security.Password; import org.eclipse.jetty.util.security.Password;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.Parameters;
/** /**
* Some requests for static data that is served by ResourceHandler, but some is secured. * Some requests for static data that is served by ResourceHandler, but some is secured.
* <p> * <p>
* This is mainly here to test security bypass techniques using aliased names that should be caught. * This is mainly here to test security bypass techniques using aliased names that should be caught.
*/ */
@RunWith(Parameterized.class) @RunWith(Parameterized.class)
public class AliasedConstraintTest public class AliasedConstraintTest
{ {
private static final String TEST_REALM = "TestRealm"; private static final String TEST_REALM = "TestRealm";
private static Server server; private static Server server;
private static LocalConnector connector; private static LocalConnector connector;
private static ConstraintSecurityHandler security; private static ConstraintSecurityHandler security;
@BeforeClass @BeforeClass
public static void startServer() throws Exception public static void startServer() throws Exception
{ {
server = new Server(); server = new Server();
connector = new LocalConnector(server); connector = new LocalConnector(server);
server.setConnectors(new Connector[] { connector }); server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler(); ContextHandler context = new ContextHandler();
SessionHandler session = new SessionHandler(); SessionHandler session = new SessionHandler();
HashLoginService loginService = new HashLoginService(TEST_REALM); HashLoginService loginService = new HashLoginService(TEST_REALM);
loginService.putUser("user0",new Password("password"),new String[] {}); loginService.putUser("user0",new Password("password"),new String[] {});
loginService.putUser("user",new Password("password"),new String[] { "user" }); loginService.putUser("user",new Password("password"),new String[] { "user" });
loginService.putUser("user2",new Password("password"),new String[] { "user" }); loginService.putUser("user2",new Password("password"),new String[] { "user" });
loginService.putUser("admin",new Password("password"),new String[] { "user", "administrator" }); loginService.putUser("admin",new Password("password"),new String[] { "user", "administrator" });
loginService.putUser("user3",new Password("password"),new String[] { "foo" }); loginService.putUser("user3",new Password("password"),new String[] { "foo" });
context.setContextPath("/ctx"); context.setContextPath("/ctx");
context.setResourceBase(MavenTestingUtils.getTestResourceDir("docroot").getAbsolutePath()); context.setResourceBase(MavenTestingUtils.getTestResourceDir("docroot").getAbsolutePath());
server.setHandler(context); server.setHandler(context);
context.setHandler(session); context.setHandler(session);
// context.addAliasCheck(new AllowSymLinkAliasChecker()); // context.addAliasCheck(new AllowSymLinkAliasChecker());
server.addBean(loginService); server.addBean(loginService);
security = new ConstraintSecurityHandler(); security = new ConstraintSecurityHandler();
session.setHandler(security); session.setHandler(security);
ResourceHandler handler = new ResourceHandler(); ResourceHandler handler = new ResourceHandler();
security.setHandler(handler); security.setHandler(handler);
List<ConstraintMapping> constraints = new ArrayList<>(); List<ConstraintMapping> constraints = new ArrayList<>();
Constraint constraint0 = new Constraint(); Constraint constraint0 = new Constraint();
constraint0.setAuthenticate(true); constraint0.setAuthenticate(true);
constraint0.setName("forbid"); constraint0.setName("forbid");
ConstraintMapping mapping0 = new ConstraintMapping(); ConstraintMapping mapping0 = new ConstraintMapping();
mapping0.setPathSpec("/forbid/*"); mapping0.setPathSpec("/forbid/*");
mapping0.setConstraint(constraint0); mapping0.setConstraint(constraint0);
constraints.add(mapping0); constraints.add(mapping0);
Set<String> knownRoles = new HashSet<>(); Set<String> knownRoles = new HashSet<>();
knownRoles.add("user"); knownRoles.add("user");
knownRoles.add("administrator"); knownRoles.add("administrator");
security.setConstraintMappings(constraints,knownRoles); security.setConstraintMappings(constraints,knownRoles);
server.start(); server.start();
} }
@AfterClass @AfterClass
public static void stopServer() throws Exception public static void stopServer() throws Exception
{ {
server.stop(); server.stop();
} }
@Parameters(name = "{0}: {1}") @Parameters(name = "{0}: {1}")
public static Collection<Object[]> data() public static Collection<Object[]> data()
{ {
List<Object[]> data = new ArrayList<>(); List<Object[]> data = new ArrayList<>();
final String OPENCONTENT = "this is open content"; final String OPENCONTENT = "this is open content";
data.add(new Object[] { "/ctx/all/index.txt", HttpStatus.OK_200, OPENCONTENT }); data.add(new Object[] { "/ctx/all/index.txt", HttpStatus.OK_200, OPENCONTENT });
data.add(new Object[] { "/ctx/ALL/index.txt", HttpStatus.NOT_FOUND_404, null }); data.add(new Object[] { "/ctx/ALL/index.txt", HttpStatus.NOT_FOUND_404, null });
data.add(new Object[] { "/ctx/ALL/Fred/../index.txt", HttpStatus.NOT_FOUND_404, null }); data.add(new Object[] { "/ctx/ALL/Fred/../index.txt", HttpStatus.NOT_FOUND_404, null });
data.add(new Object[] { "/ctx/../bar/../ctx/all/index.txt", HttpStatus.OK_200, OPENCONTENT }); data.add(new Object[] { "/ctx/../bar/../ctx/all/index.txt", HttpStatus.OK_200, OPENCONTENT });
data.add(new Object[] { "/ctx/forbid/index.txt", HttpStatus.FORBIDDEN_403, null }); data.add(new Object[] { "/ctx/forbid/index.txt", HttpStatus.FORBIDDEN_403, null });
data.add(new Object[] { "/ctx/all/../forbid/index.txt", HttpStatus.FORBIDDEN_403, null }); data.add(new Object[] { "/ctx/all/../forbid/index.txt", HttpStatus.FORBIDDEN_403, null });
data.add(new Object[] { "/ctx/FoRbId/index.txt", HttpStatus.NOT_FOUND_404, null }); data.add(new Object[] { "/ctx/FoRbId/index.txt", HttpStatus.NOT_FOUND_404, null });
return data; return data;
} }
@Parameter(value = 0) @Parameter(value = 0)
public String uri; public String uri;
@Parameter(value = 1) @Parameter(value = 1)
public int expectedStatusCode; public int expectedStatusCode;
@Parameter(value = 2) @Parameter(value = 2)
public String expectedContent; public String expectedContent;
@Test @Test
public void testAccess() throws Exception public void testAccess() throws Exception
{ {
StringBuilder request = new StringBuilder(); StringBuilder request = new StringBuilder();
request.append("GET ").append(uri).append(" HTTP/1.1\r\n"); request.append("GET ").append(uri).append(" HTTP/1.1\r\n");
request.append("Host: localhost\r\n"); request.append("Host: localhost\r\n");
request.append("Connection: close\r\n"); request.append("Connection: close\r\n");
request.append("\r\n"); request.append("\r\n");
String response = connector.getResponses(request.toString()); String response = connector.getResponses(request.toString());
switch (expectedStatusCode) switch (expectedStatusCode)
{ {
case 200: case 200:
assertThat(response,startsWith("HTTP/1.1 200 OK")); assertThat(response,startsWith("HTTP/1.1 200 OK"));
break; break;
case 403: case 403:
assertThat(response,startsWith("HTTP/1.1 403 Forbidden")); assertThat(response,startsWith("HTTP/1.1 403 Forbidden"));
break; break;
case 404: case 404:
assertThat(response,startsWith("HTTP/1.1 404 Not Found")); assertThat(response,startsWith("HTTP/1.1 404 Not Found"));
break; break;
default: default:
fail("Write a handler for response status code: " + expectedStatusCode); fail("Write a handler for response status code: " + expectedStatusCode);
break; break;
} }
if (expectedContent != null) if (expectedContent != null)
{ {
assertThat(response,containsString("this is open content")); assertThat(response,containsString("this is open content"));
} }
} }
} }

View File

@ -1,211 +1,211 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.start; package org.eclipse.jetty.start;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.eclipse.jetty.start.config.ConfigSources; import org.eclipse.jetty.start.config.ConfigSources;
import org.eclipse.jetty.start.config.JettyBaseConfigSource; import org.eclipse.jetty.start.config.JettyBaseConfigSource;
import org.eclipse.jetty.start.config.JettyHomeConfigSource; import org.eclipse.jetty.start.config.JettyHomeConfigSource;
import org.eclipse.jetty.toolchain.test.IO; import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
public class BaseHomeTest public class BaseHomeTest
{ {
public static void assertPathList(BaseHome hb, String message, List<String> expected, PathFinder finder) public static void assertPathList(BaseHome hb, String message, List<String> expected, PathFinder finder)
{ {
List<String> actual = new ArrayList<>(); List<String> actual = new ArrayList<>();
for (Path path : finder.getHits()) for (Path path : finder.getHits())
{ {
actual.add(hb.toShortForm(path.toFile())); actual.add(hb.toShortForm(path.toFile()));
} }
if (actual.size() != expected.size()) if (actual.size() != expected.size())
{ {
System.out.printf("Actual Path(s): %,d hits%n",actual.size()); System.out.printf("Actual Path(s): %,d hits%n",actual.size());
for (String path : actual) for (String path : actual)
{ {
System.out.printf(" %s%n",path); System.out.printf(" %s%n",path);
} }
System.out.printf("Expected Path(s): %,d entries%n",expected.size()); System.out.printf("Expected Path(s): %,d entries%n",expected.size());
for (String path : expected) for (String path : expected)
{ {
System.out.printf(" %s%n",path); System.out.printf(" %s%n",path);
} }
} }
Assert.assertThat(message + ": " + Main.join(actual,", "),actual,containsInAnyOrder(expected.toArray())); Assert.assertThat(message + ": " + Main.join(actual,", "),actual,containsInAnyOrder(expected.toArray()));
} }
public static void assertPathList(BaseHome hb, String message, List<String> expected, List<Path> paths) public static void assertPathList(BaseHome hb, String message, List<String> expected, List<Path> paths)
{ {
List<String> actual = new ArrayList<>(); List<String> actual = new ArrayList<>();
for (Path path : paths) for (Path path : paths)
{ {
actual.add(hb.toShortForm(path.toFile())); actual.add(hb.toShortForm(path.toFile()));
} }
if (actual.size() != expected.size()) if (actual.size() != expected.size())
{ {
System.out.printf("Actual Path(s): %,d hits%n",actual.size()); System.out.printf("Actual Path(s): %,d hits%n",actual.size());
for (String path : actual) for (String path : actual)
{ {
System.out.printf(" %s%n",path); System.out.printf(" %s%n",path);
} }
System.out.printf("Expected Path(s): %,d entries%n",expected.size()); System.out.printf("Expected Path(s): %,d entries%n",expected.size());
for (String path : expected) for (String path : expected)
{ {
System.out.printf(" %s%n",path); System.out.printf(" %s%n",path);
} }
} }
Assert.assertThat(message + ": " + Main.join(actual,", "),actual,containsInAnyOrder(expected.toArray())); Assert.assertThat(message + ": " + Main.join(actual,", "),actual,containsInAnyOrder(expected.toArray()));
} }
public static void assertFileList(BaseHome hb, String message, List<String> expected, List<File> files) public static void assertFileList(BaseHome hb, String message, List<String> expected, List<File> files)
{ {
List<String> actual = new ArrayList<>(); List<String> actual = new ArrayList<>();
for (File file : files) for (File file : files)
{ {
actual.add(hb.toShortForm(file)); actual.add(hb.toShortForm(file));
} }
Assert.assertThat(message + ": " + Main.join(actual,", "),actual,containsInAnyOrder(expected.toArray())); Assert.assertThat(message + ": " + Main.join(actual,", "),actual,containsInAnyOrder(expected.toArray()));
} }
@Test @Test
public void testGetPath_OnlyHome() throws IOException public void testGetPath_OnlyHome() throws IOException
{ {
File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home"); File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home");
ConfigSources config = new ConfigSources(); ConfigSources config = new ConfigSources();
config.add(new JettyHomeConfigSource(homeDir.toPath())); config.add(new JettyHomeConfigSource(homeDir.toPath()));
BaseHome hb = new BaseHome(config); BaseHome hb = new BaseHome(config);
Path startIni = hb.getPath("start.ini"); Path startIni = hb.getPath("start.ini");
String ref = hb.toShortForm(startIni); String ref = hb.toShortForm(startIni);
Assert.assertThat("Reference",ref,startsWith("${jetty.home}")); Assert.assertThat("Reference",ref,startsWith("${jetty.home}"));
String contents = IO.readToString(startIni.toFile()); String contents = IO.readToString(startIni.toFile());
Assert.assertThat("Contents",contents,containsString("Home Ini")); Assert.assertThat("Contents",contents,containsString("Home Ini"));
} }
@Test @Test
public void testGetPaths_OnlyHome() throws IOException public void testGetPaths_OnlyHome() throws IOException
{ {
File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home"); File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home");
ConfigSources config = new ConfigSources(); ConfigSources config = new ConfigSources();
config.add(new JettyHomeConfigSource(homeDir.toPath())); config.add(new JettyHomeConfigSource(homeDir.toPath()));
BaseHome hb = new BaseHome(config); BaseHome hb = new BaseHome(config);
List<Path> paths = hb.getPaths("start.d/*"); List<Path> paths = hb.getPaths("start.d/*");
List<String> expected = new ArrayList<>(); List<String> expected = new ArrayList<>();
expected.add("${jetty.home}/start.d/jmx.ini"); expected.add("${jetty.home}/start.d/jmx.ini");
expected.add("${jetty.home}/start.d/jndi.ini"); expected.add("${jetty.home}/start.d/jndi.ini");
expected.add("${jetty.home}/start.d/jsp.ini"); expected.add("${jetty.home}/start.d/jsp.ini");
expected.add("${jetty.home}/start.d/logging.ini"); expected.add("${jetty.home}/start.d/logging.ini");
expected.add("${jetty.home}/start.d/ssl.ini"); expected.add("${jetty.home}/start.d/ssl.ini");
FSTest.toOsSeparators(expected); FSTest.toOsSeparators(expected);
assertPathList(hb,"Paths found",expected,paths); assertPathList(hb,"Paths found",expected,paths);
} }
@Test @Test
public void testGetPaths_OnlyHome_InisOnly() throws IOException public void testGetPaths_OnlyHome_InisOnly() throws IOException
{ {
File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home"); File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home");
ConfigSources config = new ConfigSources(); ConfigSources config = new ConfigSources();
config.add(new JettyHomeConfigSource(homeDir.toPath())); config.add(new JettyHomeConfigSource(homeDir.toPath()));
BaseHome hb = new BaseHome(config); BaseHome hb = new BaseHome(config);
List<Path> paths = hb.getPaths("start.d/*.ini"); List<Path> paths = hb.getPaths("start.d/*.ini");
List<String> expected = new ArrayList<>(); List<String> expected = new ArrayList<>();
expected.add("${jetty.home}/start.d/jmx.ini"); expected.add("${jetty.home}/start.d/jmx.ini");
expected.add("${jetty.home}/start.d/jndi.ini"); expected.add("${jetty.home}/start.d/jndi.ini");
expected.add("${jetty.home}/start.d/jsp.ini"); expected.add("${jetty.home}/start.d/jsp.ini");
expected.add("${jetty.home}/start.d/logging.ini"); expected.add("${jetty.home}/start.d/logging.ini");
expected.add("${jetty.home}/start.d/ssl.ini"); expected.add("${jetty.home}/start.d/ssl.ini");
FSTest.toOsSeparators(expected); FSTest.toOsSeparators(expected);
assertPathList(hb,"Paths found",expected,paths); assertPathList(hb,"Paths found",expected,paths);
} }
@Test @Test
public void testGetPaths_Both() throws IOException public void testGetPaths_Both() throws IOException
{ {
File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home"); File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home");
File baseDir = MavenTestingUtils.getTestResourceDir("hb.1/base"); File baseDir = MavenTestingUtils.getTestResourceDir("hb.1/base");
ConfigSources config = new ConfigSources(); ConfigSources config = new ConfigSources();
config.add(new JettyBaseConfigSource(baseDir.toPath())); config.add(new JettyBaseConfigSource(baseDir.toPath()));
config.add(new JettyHomeConfigSource(homeDir.toPath())); config.add(new JettyHomeConfigSource(homeDir.toPath()));
BaseHome hb = new BaseHome(config); BaseHome hb = new BaseHome(config);
List<Path> paths = hb.getPaths("start.d/*.ini"); List<Path> paths = hb.getPaths("start.d/*.ini");
List<String> expected = new ArrayList<>(); List<String> expected = new ArrayList<>();
expected.add("${jetty.base}/start.d/jmx.ini"); expected.add("${jetty.base}/start.d/jmx.ini");
expected.add("${jetty.home}/start.d/jndi.ini"); expected.add("${jetty.home}/start.d/jndi.ini");
expected.add("${jetty.home}/start.d/jsp.ini"); expected.add("${jetty.home}/start.d/jsp.ini");
expected.add("${jetty.base}/start.d/logging.ini"); expected.add("${jetty.base}/start.d/logging.ini");
expected.add("${jetty.home}/start.d/ssl.ini"); expected.add("${jetty.home}/start.d/ssl.ini");
expected.add("${jetty.base}/start.d/myapp.ini"); expected.add("${jetty.base}/start.d/myapp.ini");
FSTest.toOsSeparators(expected); FSTest.toOsSeparators(expected);
assertPathList(hb,"Paths found",expected,paths); assertPathList(hb,"Paths found",expected,paths);
} }
@Test @Test
public void testDefault() throws IOException public void testDefault() throws IOException
{ {
BaseHome bh = new BaseHome(); BaseHome bh = new BaseHome();
Assert.assertThat("Home",bh.getHome(),notNullValue()); Assert.assertThat("Home",bh.getHome(),notNullValue());
Assert.assertThat("Base",bh.getBase(),notNullValue()); Assert.assertThat("Base",bh.getBase(),notNullValue());
} }
@Test @Test
public void testGetPath_Both() throws IOException public void testGetPath_Both() throws IOException
{ {
File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home"); File homeDir = MavenTestingUtils.getTestResourceDir("hb.1/home");
File baseDir = MavenTestingUtils.getTestResourceDir("hb.1/base"); File baseDir = MavenTestingUtils.getTestResourceDir("hb.1/base");
ConfigSources config = new ConfigSources(); ConfigSources config = new ConfigSources();
config.add(new JettyBaseConfigSource(baseDir.toPath())); config.add(new JettyBaseConfigSource(baseDir.toPath()));
config.add(new JettyHomeConfigSource(homeDir.toPath())); config.add(new JettyHomeConfigSource(homeDir.toPath()));
BaseHome hb = new BaseHome(config); BaseHome hb = new BaseHome(config);
Path startIni = hb.getPath("start.ini"); Path startIni = hb.getPath("start.ini");
String ref = hb.toShortForm(startIni); String ref = hb.toShortForm(startIni);
Assert.assertThat("Reference",ref,startsWith("${jetty.base}")); Assert.assertThat("Reference",ref,startsWith("${jetty.base}"));
String contents = IO.readToString(startIni.toFile()); String contents = IO.readToString(startIni.toFile());
Assert.assertThat("Contents",contents,containsString("Base Ini")); Assert.assertThat("Contents",contents,containsString("Base Ini"));
} }
} }

View File

@ -1,281 +1,281 @@
// //
// ======================================================================== // ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. // Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials // All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0 // are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution. // and Apache License v2.0 which accompanies this distribution.
// //
// The Eclipse Public License is available at // The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html // http://www.eclipse.org/legal/epl-v10.html
// //
// The Apache License v2.0 is available at // The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php // http://www.opensource.org/licenses/apache2.0.php
// //
// You may elect to redistribute this code under either of these licenses. // You may elect to redistribute this code under either of these licenses.
// ======================================================================== // ========================================================================
// //
package org.eclipse.jetty.start; package org.eclipse.jetty.start;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.eclipse.jetty.start.Props.Prop; import org.eclipse.jetty.start.Props.Prop;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.Assert; import org.junit.Assert;
public class ConfigurationAssert public class ConfigurationAssert
{ {
/** /**
* Given a provided StartArgs, assert that the configuration it has determined is valid based on values in a assert text file. * Given a provided StartArgs, assert that the configuration it has determined is valid based on values in a assert text file.
* *
* @param baseHome * @param baseHome
* the BaseHome used. Access it via {@link Main#getBaseHome()} * the BaseHome used. Access it via {@link Main#getBaseHome()}
* @param args * @param args
* the StartArgs that has been processed via {@link Main#processCommandLine(String[])} * the StartArgs that has been processed via {@link Main#processCommandLine(String[])}
* @param filename * @param filename
* the filename of the assertion values * the filename of the assertion values
* @throws IOException * @throws IOException
*/ */
public static void assertConfiguration(BaseHome baseHome, StartArgs args, String filename) throws FileNotFoundException, IOException public static void assertConfiguration(BaseHome baseHome, StartArgs args, String filename) throws FileNotFoundException, IOException
{ {
Path testResourcesDir = MavenTestingUtils.getTestResourcesDir().toPath().toAbsolutePath(); Path testResourcesDir = MavenTestingUtils.getTestResourcesDir().toPath().toAbsolutePath();
File file = MavenTestingUtils.getTestResourceFile(filename); File file = MavenTestingUtils.getTestResourceFile(filename);
TextFile textFile = new TextFile(file.toPath()); TextFile textFile = new TextFile(file.toPath());
// Validate XMLs (order is important) // Validate XMLs (order is important)
List<String> expectedXmls = new ArrayList<>(); List<String> expectedXmls = new ArrayList<>();
for (String line : textFile) for (String line : textFile)
{ {
if (line.startsWith("XML|")) if (line.startsWith("XML|"))
{ {
expectedXmls.add(FS.separators(getValue(line))); expectedXmls.add(FS.separators(getValue(line)));
} }
} }
List<String> actualXmls = new ArrayList<>(); List<String> actualXmls = new ArrayList<>();
for (Path xml : args.getXmlFiles()) for (Path xml : args.getXmlFiles())
{ {
actualXmls.add(shorten(baseHome,xml,testResourcesDir)); actualXmls.add(shorten(baseHome,xml,testResourcesDir));
} }
assertOrdered("XML Resolution Order",expectedXmls,actualXmls); assertOrdered("XML Resolution Order",expectedXmls,actualXmls);
// Validate LIBs (order is not important) // Validate LIBs (order is not important)
List<String> expectedLibs = new ArrayList<>(); List<String> expectedLibs = new ArrayList<>();
for (String line : textFile) for (String line : textFile)
{ {
if (line.startsWith("LIB|")) if (line.startsWith("LIB|"))
{ {
expectedLibs.add(FS.separators(getValue(line))); expectedLibs.add(FS.separators(getValue(line)));
} }
} }
List<String> actualLibs = new ArrayList<>(); List<String> actualLibs = new ArrayList<>();
for (File path : args.getClasspath()) for (File path : args.getClasspath())
{ {
actualLibs.add(shorten(baseHome,path.toPath(),testResourcesDir)); actualLibs.add(shorten(baseHome,path.toPath(),testResourcesDir));
} }
assertContainsUnordered("Libs",expectedLibs,actualLibs); assertContainsUnordered("Libs",expectedLibs,actualLibs);
// Validate PROPERTIES (order is not important) // Validate PROPERTIES (order is not important)
Set<String> expectedProperties = new HashSet<>(); Set<String> expectedProperties = new HashSet<>();
for (String line : textFile) for (String line : textFile)
{ {
if (line.startsWith("PROP|")) if (line.startsWith("PROP|"))
{ {
expectedProperties.add(getValue(line)); expectedProperties.add(getValue(line));
} }
} }
List<String> actualProperties = new ArrayList<>(); List<String> actualProperties = new ArrayList<>();
for (Prop prop : args.getProperties()) for (Prop prop : args.getProperties())
{ {
String name = prop.key; String name = prop.key;
if ("jetty.home".equals(name) || "jetty.base".equals(name) || if ("jetty.home".equals(name) || "jetty.base".equals(name) ||
"user.dir".equals(name) || prop.origin.equals(Props.ORIGIN_SYSPROP)) "user.dir".equals(name) || prop.origin.equals(Props.ORIGIN_SYSPROP))
{ {
// strip these out from assertion, to make assertions easier. // strip these out from assertion, to make assertions easier.
continue; continue;
} }
actualProperties.add(prop.key + "=" + args.getProperties().expand(prop.value)); actualProperties.add(prop.key + "=" + args.getProperties().expand(prop.value));
} }
assertContainsUnordered("Properties",expectedProperties,actualProperties); assertContainsUnordered("Properties",expectedProperties,actualProperties);
// Validate Downloads // Validate Downloads
List<String> expectedDownloads = new ArrayList<>(); List<String> expectedDownloads = new ArrayList<>();
for (String line : textFile) for (String line : textFile)
{ {
if (line.startsWith("DOWNLOAD|")) if (line.startsWith("DOWNLOAD|"))
{ {
expectedDownloads.add(getValue(line)); expectedDownloads.add(getValue(line));
} }
} }
List<String> actualDownloads = new ArrayList<>(); List<String> actualDownloads = new ArrayList<>();
for (FileArg darg : args.getFiles()) for (FileArg darg : args.getFiles())
{ {
if (darg.uri != null) if (darg.uri != null)
{ {
actualDownloads.add(String.format("%s|%s",darg.uri,darg.location)); actualDownloads.add(String.format("%s|%s",darg.uri,darg.location));
} }
} }
assertContainsUnordered("Downloads",expectedDownloads,actualDownloads); assertContainsUnordered("Downloads",expectedDownloads,actualDownloads);
// Validate Files/Dirs creation // Validate Files/Dirs creation
List<String> expectedFiles = new ArrayList<>(); List<String> expectedFiles = new ArrayList<>();
for(String line: textFile) for(String line: textFile)
{ {
if(line.startsWith("FILE|")) if(line.startsWith("FILE|"))
{ {
expectedFiles.add(getValue(line)); expectedFiles.add(getValue(line));
} }
} }
List<String> actualFiles = new ArrayList<>(); List<String> actualFiles = new ArrayList<>();
for(FileArg farg: args.getFiles()) for(FileArg farg: args.getFiles())
{ {
if(farg.uri == null) if(farg.uri == null)
{ {
actualFiles.add(farg.location); actualFiles.add(farg.location);
} }
} }
assertContainsUnordered("Files/Dirs",expectedFiles,actualFiles); assertContainsUnordered("Files/Dirs",expectedFiles,actualFiles);
} }
private static String shorten(BaseHome baseHome, Path path, Path testResourcesDir) private static String shorten(BaseHome baseHome, Path path, Path testResourcesDir)
{ {
String value = baseHome.toShortForm(path); String value = baseHome.toShortForm(path);
if (value.startsWith("${")) if (value.startsWith("${"))
{ {
return value; return value;
} }
if (path.startsWith(testResourcesDir)) if (path.startsWith(testResourcesDir))
{ {
int len = testResourcesDir.toString().length(); int len = testResourcesDir.toString().length();
value = "${maven-test-resources}" + value.substring(len); value = "${maven-test-resources}" + value.substring(len);
} }
return value; return value;
} }
public static void assertContainsUnordered(String msg, Collection<String> expectedSet, Collection<String> actualSet) public static void assertContainsUnordered(String msg, Collection<String> expectedSet, Collection<String> actualSet)
{ {
// same size? // same size?
boolean mismatch = expectedSet.size() != actualSet.size(); boolean mismatch = expectedSet.size() != actualSet.size();
// test content // test content
Set<String> missing = new HashSet<>(); Set<String> missing = new HashSet<>();
for (String expected : expectedSet) for (String expected : expectedSet)
{ {
if (!actualSet.contains(expected)) if (!actualSet.contains(expected))
{ {
missing.add(expected); missing.add(expected);
} }
} }
if (mismatch || missing.size() > 0) if (mismatch || missing.size() > 0)
{ {
// build up detailed error message // build up detailed error message
StringWriter message = new StringWriter(); StringWriter message = new StringWriter();
PrintWriter err = new PrintWriter(message); PrintWriter err = new PrintWriter(message);
err.printf("%s: Assert Contains (Unordered)",msg); err.printf("%s: Assert Contains (Unordered)",msg);
if (mismatch) if (mismatch)
{ {
err.print(" [size mismatch]"); err.print(" [size mismatch]");
} }
if (missing.size() >= 0) if (missing.size() >= 0)
{ {
err.printf(" [%d entries missing]",missing.size()); err.printf(" [%d entries missing]",missing.size());
} }
err.println(); err.println();
err.printf("Actual Entries (size: %d)%n",actualSet.size()); err.printf("Actual Entries (size: %d)%n",actualSet.size());
for (String actual : actualSet) for (String actual : actualSet)
{ {
char indicator = expectedSet.contains(actual)?' ':'>'; char indicator = expectedSet.contains(actual)?' ':'>';
err.printf("%s| %s%n",indicator,actual); err.printf("%s| %s%n",indicator,actual);
} }
err.printf("Expected Entries (size: %d)%n",expectedSet.size()); err.printf("Expected Entries (size: %d)%n",expectedSet.size());
for (String expected : expectedSet) for (String expected : expectedSet)
{ {
char indicator = actualSet.contains(expected)?' ':'>'; char indicator = actualSet.contains(expected)?' ':'>';
err.printf("%s| %s%n",indicator,expected); err.printf("%s| %s%n",indicator,expected);
} }
err.flush(); err.flush();
Assert.fail(message.toString()); Assert.fail(message.toString());
} }
} }
public static void assertOrdered(String msg, List<String> expectedList, List<String> actualList) public static void assertOrdered(String msg, List<String> expectedList, List<String> actualList)
{ {
// same size? // same size?
boolean mismatch = expectedList.size() != actualList.size(); boolean mismatch = expectedList.size() != actualList.size();
// test content // test content
List<Integer> badEntries = new ArrayList<>(); List<Integer> badEntries = new ArrayList<>();
int min = Math.min(expectedList.size(),actualList.size()); int min = Math.min(expectedList.size(),actualList.size());
int max = Math.max(expectedList.size(),actualList.size()); int max = Math.max(expectedList.size(),actualList.size());
for (int i = 0; i < min; i++) for (int i = 0; i < min; i++)
{ {
if (!expectedList.get(i).equals(actualList.get(i))) if (!expectedList.get(i).equals(actualList.get(i)))
{ {
badEntries.add(i); badEntries.add(i);
} }
} }
for (int i = min; i < max; i++) for (int i = min; i < max; i++)
{ {
badEntries.add(i); badEntries.add(i);
} }
if (mismatch || badEntries.size() > 0) if (mismatch || badEntries.size() > 0)
{ {
// build up detailed error message // build up detailed error message
StringWriter message = new StringWriter(); StringWriter message = new StringWriter();
PrintWriter err = new PrintWriter(message); PrintWriter err = new PrintWriter(message);
err.printf("%s: Assert Contains (Unordered)",msg); err.printf("%s: Assert Contains (Unordered)",msg);
if (mismatch) if (mismatch)
{ {
err.print(" [size mismatch]"); err.print(" [size mismatch]");
} }
if (badEntries.size() >= 0) if (badEntries.size() >= 0)
{ {
err.printf(" [%d entries not matched]",badEntries.size()); err.printf(" [%d entries not matched]",badEntries.size());
} }
err.println(); err.println();
err.printf("Actual Entries (size: %d)%n",actualList.size()); err.printf("Actual Entries (size: %d)%n",actualList.size());
for (int i = 0; i < actualList.size(); i++) for (int i = 0; i < actualList.size(); i++)
{ {
String actual = actualList.get(i); String actual = actualList.get(i);
char indicator = badEntries.contains(i)?'>':' '; char indicator = badEntries.contains(i)?'>':' ';
err.printf("%s[%d] %s%n",indicator,i,actual); err.printf("%s[%d] %s%n",indicator,i,actual);
} }
err.printf("Expected Entries (size: %d)%n",expectedList.size()); err.printf("Expected Entries (size: %d)%n",expectedList.size());
for (int i = 0; i < expectedList.size(); i++) for (int i = 0; i < expectedList.size(); i++)
{ {
String expected = expectedList.get(i); String expected = expectedList.get(i);
char indicator = badEntries.contains(i)?'>':' '; char indicator = badEntries.contains(i)?'>':' ';
err.printf("%s[%d] %s%n",indicator,i,expected); err.printf("%s[%d] %s%n",indicator,i,expected);
} }
err.flush(); err.flush();
Assert.fail(message.toString()); Assert.fail(message.toString());
} }
} }
private static String getValue(String arg) private static String getValue(String arg)
{ {
int idx = arg.indexOf('|'); int idx = arg.indexOf('|');
Assert.assertThat("Expecting '|' sign in [" + arg + "]",idx,greaterThanOrEqualTo(0)); Assert.assertThat("Expecting '|' sign in [" + arg + "]",idx,greaterThanOrEqualTo(0));
String value = arg.substring(idx + 1).trim(); String value = arg.substring(idx + 1).trim();
Assert.assertThat("Expecting Value after '|' in [" + arg + "]",value.length(),greaterThan(0)); Assert.assertThat("Expecting Value after '|' in [" + arg + "]",value.length(),greaterThan(0));
return value; return value;
} }
} }