use of java.util.HashMap in project jetty.project by eclipse.
the class ProxyServletTest method testTransparentProxyWithoutPrefix.
@Test
public void testTransparentProxyWithoutPrefix() throws Exception {
final String target = "/test";
startServer(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getHeader("Via") != null)
resp.addHeader(PROXIED_HEADER, "true");
resp.setStatus(target.equals(req.getRequestURI()) ? 200 : 404);
}
});
final String proxyTo = "http://localhost:" + serverConnector.getLocalPort();
proxyServlet = new ProxyServlet.Transparent();
Map<String, String> initParams = new HashMap<>();
initParams.put("proxyTo", proxyTo);
startProxy(initParams);
startClient();
// Make the request to the proxy, it should transparently forward to the server
ContentResponse response = client.newRequest("localhost", proxyConnector.getLocalPort()).path(target).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
use of java.util.HashMap in project jetty.project by eclipse.
the class ProxyServletTest method testTransparentProxyWithQuery.
private void testTransparentProxyWithQuery(String proxyToContext, String prefix, String target) throws Exception {
final String query = "a=1&b=2";
startServer(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getHeader("Via") != null)
resp.addHeader(PROXIED_HEADER, "true");
String expectedURI = proxyToContext + target;
if (expectedURI.isEmpty())
expectedURI = "/";
if (expectedURI.equals(req.getRequestURI())) {
if (query.equals(req.getQueryString())) {
resp.setStatus(200);
return;
}
}
resp.setStatus(404);
}
});
String proxyTo = "http://localhost:" + serverConnector.getLocalPort() + proxyToContext;
proxyServlet = new ProxyServlet.Transparent();
Map<String, String> params = new HashMap<>();
params.put("proxyTo", proxyTo);
params.put("prefix", prefix);
startProxy(params);
startClient();
// Make the request to the proxy, it should transparently forward to the server
ContentResponse response = client.newRequest("localhost", proxyConnector.getLocalPort()).path(prefix + target + "?" + query).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
use of java.util.HashMap in project jetty.project by eclipse.
the class ProxyServletTest method testProxyRequestFailureInTheMiddleOfProxyingSmallContent.
@Test
public void testProxyRequestFailureInTheMiddleOfProxyingSmallContent() throws Exception {
final CountDownLatch chunk1Latch = new CountDownLatch(1);
final int chunk1 = 'q';
final int chunk2 = 'w';
startServer(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream output = response.getOutputStream();
output.write(chunk1);
response.flushBuffer();
// Wait for the client to receive this chunk.
await(chunk1Latch, 5000);
// Send second chunk, must not be received by proxy.
output.write(chunk2);
}
private boolean await(CountDownLatch latch, long ms) throws IOException {
try {
return latch.await(ms, TimeUnit.MILLISECONDS);
} catch (InterruptedException x) {
throw new InterruptedIOException();
}
}
});
final long proxyTimeout = 1000;
Map<String, String> proxyParams = new HashMap<>();
proxyParams.put("timeout", String.valueOf(proxyTimeout));
startProxy(proxyParams);
startClient();
InputStreamResponseListener listener = new InputStreamResponseListener();
int port = serverConnector.getLocalPort();
client.newRequest("localhost", port).send(listener);
// Make the proxy request fail; given the small content, the
// proxy-to-client response is not committed yet so it will be reset.
TimeUnit.MILLISECONDS.sleep(2 * proxyTimeout);
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(504, response.getStatus());
// Make sure there is no content, as the proxy-to-client response has been reset.
InputStream input = listener.getInputStream();
Assert.assertEquals(-1, input.read());
chunk1Latch.countDown();
// Result succeeds because a 504 is a valid HTTP response.
Result result = listener.await(5, TimeUnit.SECONDS);
Assert.assertTrue(result.isSucceeded());
// Make sure the proxy does not receive chunk2.
Assert.assertEquals(-1, input.read());
HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP) client.getDestination("http", "localhost", port);
DuplexConnectionPool connectionPool = (DuplexConnectionPool) destination.getConnectionPool();
Assert.assertEquals(0, connectionPool.getIdleConnections().size());
}
use of java.util.HashMap in project jetty.project by eclipse.
the class Invoker method init.
/* ------------------------------------------------------------ */
public void init() {
ServletContext config = getServletContext();
_contextHandler = ((ContextHandler.Context) config).getContextHandler();
Handler handler = _contextHandler.getHandler();
while (handler != null && !(handler instanceof ServletHandler) && (handler instanceof HandlerWrapper)) handler = ((HandlerWrapper) handler).getHandler();
_servletHandler = (ServletHandler) handler;
Enumeration<String> e = getInitParameterNames();
while (e.hasMoreElements()) {
String param = e.nextElement();
String value = getInitParameter(param);
String lvalue = value.toLowerCase(Locale.ENGLISH);
if ("nonContextServlets".equals(param)) {
_nonContextServlets = value.length() > 0 && lvalue.startsWith("t");
}
if ("verbose".equals(param)) {
_verbose = value.length() > 0 && lvalue.startsWith("t");
} else {
if (_parameters == null)
_parameters = new HashMap<String, String>();
_parameters.put(param, value);
}
}
}
use of java.util.HashMap in project jetty.project by eclipse.
the class ServletHandler method updateMappings.
/* ------------------------------------------------------------ */
protected synchronized void updateMappings() {
// update filter mappings
if (_filterMappings == null) {
_filterPathMappings = null;
_filterNameMappings = null;
} else {
_filterPathMappings = new ArrayList<>();
_filterNameMappings = new MultiMap<>();
for (FilterMapping filtermapping : _filterMappings) {
FilterHolder filter_holder = _filterNameMap.get(filtermapping.getFilterName());
if (filter_holder == null)
throw new IllegalStateException("No filter named " + filtermapping.getFilterName());
filtermapping.setFilterHolder(filter_holder);
if (filtermapping.getPathSpecs() != null)
_filterPathMappings.add(filtermapping);
if (filtermapping.getServletNames() != null) {
String[] names = filtermapping.getServletNames();
for (String name : names) {
if (name != null)
_filterNameMappings.add(name, filtermapping);
}
}
}
}
// Map servlet paths to holders
if (_servletMappings == null || _servletNameMap == null) {
_servletPathMap = null;
} else {
PathMappings<ServletHolder> pm = new PathMappings<>();
Map<String, ServletMapping> servletPathMappings = new HashMap<>();
//create a map of paths to set of ServletMappings that define that mapping
HashMap<String, List<ServletMapping>> sms = new HashMap<>();
for (ServletMapping servletMapping : _servletMappings) {
String[] pathSpecs = servletMapping.getPathSpecs();
if (pathSpecs != null) {
for (String pathSpec : pathSpecs) {
List<ServletMapping> mappings = sms.get(pathSpec);
if (mappings == null) {
mappings = new ArrayList<>();
sms.put(pathSpec, mappings);
}
mappings.add(servletMapping);
}
}
}
//evaluate path to servlet map based on servlet mappings
for (String pathSpec : sms.keySet()) {
//for each path, look at the mappings where it is referenced
//if a mapping is for a servlet that is not enabled, skip it
List<ServletMapping> mappings = sms.get(pathSpec);
ServletMapping finalMapping = null;
for (ServletMapping mapping : mappings) {
//Get servlet associated with the mapping and check it is enabled
ServletHolder servlet_holder = _servletNameMap.get(mapping.getServletName());
if (servlet_holder == null)
throw new IllegalStateException("No such servlet: " + mapping.getServletName());
//if the servlet related to the mapping is not enabled, skip it from consideration
if (!servlet_holder.isEnabled())
continue;
//only accept a default mapping if we don't have any other
if (finalMapping == null)
finalMapping = mapping;
else {
//if the candidate is a default, or we're allowing duplicate mappings
if (finalMapping.isDefault())
finalMapping = mapping;
else if (isAllowDuplicateMappings()) {
LOG.warn("Multiple servlets map to path {}: {} and {}, choosing {}", pathSpec, finalMapping.getServletName(), mapping.getServletName(), mapping);
finalMapping = mapping;
} else {
//existing candidate isn't a default, if the one we're looking at isn't a default either, then its an error
if (!mapping.isDefault()) {
ServletHolder finalMappedServlet = _servletNameMap.get(finalMapping.getServletName());
throw new IllegalStateException("Multiple servlets map to path " + pathSpec + ": " + finalMappedServlet.getName() + "[mapped:" + finalMapping.getSource() + "]," + mapping.getServletName() + "[mapped:" + mapping.getSource() + "]");
}
}
}
}
if (finalMapping == null)
throw new IllegalStateException("No acceptable servlet mappings for " + pathSpec);
if (LOG.isDebugEnabled())
LOG.debug("Path={}[{}] mapped to servlet={}[{}]", pathSpec, finalMapping.getSource(), finalMapping.getServletName(), _servletNameMap.get(finalMapping.getServletName()).getSource());
servletPathMappings.put(pathSpec, finalMapping);
pm.put(new ServletPathSpec(pathSpec), _servletNameMap.get(finalMapping.getServletName()));
}
_servletPathMap = pm;
}
// flush filter chain cache
if (_chainCache != null) {
for (int i = _chainCache.length; i-- > 0; ) {
if (_chainCache[i] != null)
_chainCache[i].clear();
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("filterNameMap=" + _filterNameMap);
LOG.debug("pathFilters=" + _filterPathMappings);
LOG.debug("servletFilterMap=" + _filterNameMappings);
LOG.debug("servletPathMap=" + _servletPathMap);
LOG.debug("servletNameMap=" + _servletNameMap);
}
try {
if (_contextHandler != null && _contextHandler.isStarted() || _contextHandler == null && isStarted())
initialize();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Aggregations