use of org.eclipse.jetty.server.Connector in project dropwizard by dropwizard.
the class DefaultServerFactoryTest method testGracefulShutdown.
@Test
public void testGracefulShutdown() throws Exception {
CountDownLatch requestReceived = new CountDownLatch(1);
CountDownLatch shutdownInvoked = new CountDownLatch(1);
environment.jersey().register(new TestResource(requestReceived, shutdownInvoked));
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
final Server server = http.build(environment);
((AbstractNetworkConnector) server.getConnectors()[0]).setPort(0);
((AbstractNetworkConnector) server.getConnectors()[1]).setPort(0);
ScheduledFuture<Void> cleanup = executor.schedule(() -> {
if (!server.isStopped()) {
server.stop();
}
executor.shutdownNow();
return null;
}, 5, TimeUnit.SECONDS);
server.start();
final int port = ((AbstractNetworkConnector) server.getConnectors()[0]).getLocalPort();
Future<String> futureResult = executor.submit(() -> {
URL url = new URL("http://localhost:" + port + "/app/test");
URLConnection connection = url.openConnection();
connection.connect();
return CharStreams.toString(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
});
requestReceived.await(10, TimeUnit.SECONDS);
Future<Void> serverStopped = executor.submit(() -> {
server.stop();
return null;
});
Connector[] connectors = server.getConnectors();
assertThat(connectors).isNotEmpty();
assertThat(connectors[0]).isInstanceOf(NetworkConnector.class);
NetworkConnector connector = (NetworkConnector) connectors[0];
// wait for server to close the connectors
while (true) {
if (!connector.isOpen()) {
shutdownInvoked.countDown();
break;
}
Thread.sleep(5);
}
String result = futureResult.get();
assertThat(result).isEqualTo("test");
serverStopped.get();
// cancel the cleanup future since everything succeeded
cleanup.cancel(false);
executor.shutdownNow();
}
use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.
the class DataConstraintsTest method startServer.
@Before
public void startServer() {
_server = new Server();
HttpConnectionFactory http = new HttpConnectionFactory();
http.getHttpConfiguration().setSecurePort(9999);
http.getHttpConfiguration().setSecureScheme("BWTP");
_connector = new LocalConnector(_server, http);
_connector.setIdleTimeout(300000);
HttpConnectionFactory https = new HttpConnectionFactory();
https.getHttpConfiguration().addCustomizer(new HttpConfiguration.Customizer() {
@Override
public void customize(Connector connector, HttpConfiguration channelConfig, Request request) {
request.setScheme(HttpScheme.HTTPS.asString());
request.setSecure(true);
}
});
_connectorS = new LocalConnector(_server, https);
_server.setConnectors(new Connector[] { _connector, _connectorS });
ContextHandler _context = new ContextHandler();
_session = new SessionHandler();
_context.setContextPath("/ctx");
_server.setHandler(_context);
_context.setHandler(_session);
_security = new ConstraintSecurityHandler();
_session.setHandler(_security);
_security.setHandler(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
response.sendError(404);
}
});
}
use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.
the class StatisticsServlet method sendXmlResponse.
private void sendXmlResponse(HttpServletResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("<statistics>\n");
sb.append(" <requests>\n");
sb.append(" <statsOnMs>").append(_statsHandler.getStatsOnMs()).append("</statsOnMs>\n");
sb.append(" <requests>").append(_statsHandler.getRequests()).append("</requests>\n");
sb.append(" <requestsActive>").append(_statsHandler.getRequestsActive()).append("</requestsActive>\n");
sb.append(" <requestsActiveMax>").append(_statsHandler.getRequestsActiveMax()).append("</requestsActiveMax>\n");
sb.append(" <requestsTimeTotal>").append(_statsHandler.getRequestTimeTotal()).append("</requestsTimeTotal>\n");
sb.append(" <requestsTimeMean>").append(_statsHandler.getRequestTimeMean()).append("</requestsTimeMean>\n");
sb.append(" <requestsTimeMax>").append(_statsHandler.getRequestTimeMax()).append("</requestsTimeMax>\n");
sb.append(" <requestsTimeStdDev>").append(_statsHandler.getRequestTimeStdDev()).append("</requestsTimeStdDev>\n");
sb.append(" <dispatched>").append(_statsHandler.getDispatched()).append("</dispatched>\n");
sb.append(" <dispatchedActive>").append(_statsHandler.getDispatchedActive()).append("</dispatchedActive>\n");
sb.append(" <dispatchedActiveMax>").append(_statsHandler.getDispatchedActiveMax()).append("</dispatchedActiveMax>\n");
sb.append(" <dispatchedTimeTotalMs>").append(_statsHandler.getDispatchedTimeTotal()).append("</dispatchedTimeTotalMs>\n");
sb.append(" <dispatchedTimeMeanMs>").append(_statsHandler.getDispatchedTimeMean()).append("</dispatchedTimeMeanMs>\n");
sb.append(" <dispatchedTimeMaxMs>").append(_statsHandler.getDispatchedTimeMax()).append("</dispatchedTimeMaxMs>\n");
sb.append(" <dispatchedTimeStdDevMs>").append(_statsHandler.getDispatchedTimeStdDev()).append("</dispatchedTimeStdDevMs>\n");
sb.append(" <asyncRequests>").append(_statsHandler.getAsyncRequests()).append("</asyncRequests>\n");
sb.append(" <requestsSuspended>").append(_statsHandler.getAsyncRequestsWaiting()).append("</requestsSuspended>\n");
sb.append(" <requestsSuspendedMax>").append(_statsHandler.getAsyncRequestsWaitingMax()).append("</requestsSuspendedMax>\n");
sb.append(" <requestsResumed>").append(_statsHandler.getAsyncDispatches()).append("</requestsResumed>\n");
sb.append(" <requestsExpired>").append(_statsHandler.getExpires()).append("</requestsExpired>\n");
sb.append(" </requests>\n");
sb.append(" <responses>\n");
sb.append(" <responses1xx>").append(_statsHandler.getResponses1xx()).append("</responses1xx>\n");
sb.append(" <responses2xx>").append(_statsHandler.getResponses2xx()).append("</responses2xx>\n");
sb.append(" <responses3xx>").append(_statsHandler.getResponses3xx()).append("</responses3xx>\n");
sb.append(" <responses4xx>").append(_statsHandler.getResponses4xx()).append("</responses4xx>\n");
sb.append(" <responses5xx>").append(_statsHandler.getResponses5xx()).append("</responses5xx>\n");
sb.append(" <responsesBytesTotal>").append(_statsHandler.getResponsesBytesTotal()).append("</responsesBytesTotal>\n");
sb.append(" </responses>\n");
sb.append(" <connections>\n");
for (Connector connector : _connectors) {
sb.append(" <connector>\n");
sb.append(" <name>").append(connector.getClass().getName()).append("@").append(connector.hashCode()).append("</name>\n");
sb.append(" <protocols>\n");
for (String protocol : connector.getProtocols()) sb.append(" <protocol>").append(protocol).append("</protocol>\n");
sb.append(" </protocols>\n");
ConnectionStatistics connectionStats = null;
if (connector instanceof AbstractConnector)
connectionStats = ((AbstractConnector) connector).getBean(ConnectionStatistics.class);
if (connectionStats != null) {
sb.append(" <statsOn>true</statsOn>\n");
sb.append(" <connections>").append(connectionStats.getConnectionsTotal()).append("</connections>\n");
sb.append(" <connectionsOpen>").append(connectionStats.getConnections()).append("</connectionsOpen>\n");
sb.append(" <connectionsOpenMax>").append(connectionStats.getConnectionsMax()).append("</connectionsOpenMax>\n");
sb.append(" <connectionsDurationMean>").append(connectionStats.getConnectionDurationMean()).append("</connectionsDurationMean>\n");
sb.append(" <connectionsDurationMax>").append(connectionStats.getConnectionDurationMax()).append("</connectionsDurationMax>\n");
sb.append(" <connectionsDurationStdDev>").append(connectionStats.getConnectionDurationStdDev()).append("</connectionsDurationStdDev>\n");
sb.append(" <bytesIn>").append(connectionStats.getReceivedBytes()).append("</bytesIn>\n");
sb.append(" <bytesOut>").append(connectionStats.getSentBytes()).append("</connectorStats>\n");
sb.append(" <messagesIn>").append(connectionStats.getReceivedMessages()).append("</messagesIn>\n");
sb.append(" <messagesOut>").append(connectionStats.getSentMessages()).append("</messagesOut>\n");
} else {
ConnectorStatistics connectorStats = null;
if (connector instanceof AbstractConnector)
connectorStats = ((AbstractConnector) connector).getBean(ConnectorStatistics.class);
if (connectorStats != null) {
sb.append(" <statsOn>true</statsOn>\n");
sb.append(" <connections>").append(connectorStats.getConnections()).append("</connections>\n");
sb.append(" <connectionsOpen>").append(connectorStats.getConnectionsOpen()).append("</connectionsOpen>\n");
sb.append(" <connectionsOpenMax>").append(connectorStats.getConnectionsOpenMax()).append("</connectionsOpenMax>\n");
sb.append(" <connectionsDurationMean>").append(connectorStats.getConnectionDurationMean()).append("</connectionsDurationMean>\n");
sb.append(" <connectionsDurationMax>").append(connectorStats.getConnectionDurationMax()).append("</connectionsDurationMax>\n");
sb.append(" <connectionsDurationStdDev>").append(connectorStats.getConnectionDurationStdDev()).append("</connectionsDurationStdDev>\n");
sb.append(" <messagesIn>").append(connectorStats.getMessagesIn()).append("</messagesIn>\n");
sb.append(" <messagesOut>").append(connectorStats.getMessagesIn()).append("</messagesOut>\n");
sb.append(" <elapsedMs>").append(connectorStats.getStartedMillis()).append("</elapsedMs>\n");
} else {
sb.append(" <statsOn>false</statsOn>\n");
}
}
sb.append(" </connector>\n");
}
sb.append(" </connections>\n");
sb.append(" <memory>\n");
sb.append(" <heapMemoryUsage>").append(_memoryBean.getHeapMemoryUsage().getUsed()).append("</heapMemoryUsage>\n");
sb.append(" <nonHeapMemoryUsage>").append(_memoryBean.getNonHeapMemoryUsage().getUsed()).append("</nonHeapMemoryUsage>\n");
sb.append(" </memory>\n");
sb.append("</statistics>\n");
response.setContentType("text/xml");
PrintWriter pout = response.getWriter();
pout.write(sb.toString());
}
use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.
the class WebSocketServerFactory method upgrade.
/**
* Upgrade the request/response to a WebSocket Connection.
* <p/>
* This method will not normally return, but will instead throw a UpgradeConnectionException, to exit HTTP handling and initiate WebSocket handling of the
* connection.
*
* @param http the raw http connection
* @param request The request to upgrade
* @param response The response to upgrade
* @param driver The websocket handler implementation to use
*/
private boolean upgrade(HttpConnection http, ServletUpgradeRequest request, ServletUpgradeResponse response, EventDriver driver) throws IOException {
if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
throw new IllegalStateException("Not a 'WebSocket: Upgrade' request");
}
if (!"HTTP/1.1".equals(request.getHttpVersion())) {
throw new IllegalStateException("Not a 'HTTP/1.1' request");
}
int version = request.getHeaderInt("Sec-WebSocket-Version");
if (version < 0) {
// Old pre-RFC version specifications (header not present in RFC-6455)
version = request.getHeaderInt("Sec-WebSocket-Draft");
}
WebSocketHandshake handshaker = handshakes.get(version);
if (handshaker == null) {
StringBuilder warn = new StringBuilder();
warn.append("Client ").append(request.getRemoteAddress());
warn.append(" (:").append(request.getRemotePort());
warn.append(") User Agent: ");
String ua = request.getHeader("User-Agent");
if (ua == null) {
warn.append("[unset] ");
} else {
warn.append('"').append(StringUtil.sanitizeXmlString(ua)).append("\" ");
}
warn.append("requested WebSocket version [").append(version);
warn.append("], Jetty supports version");
if (handshakes.size() > 1) {
warn.append('s');
}
warn.append(": [").append(supportedVersions).append("]");
LOG.warn(warn.toString());
// Per RFC 6455 - 4.4 - Supporting Multiple Versions of WebSocket Protocol
// Using the examples as outlined
response.setHeader("Sec-WebSocket-Version", supportedVersions);
response.sendError(HttpStatus.BAD_REQUEST_400, "Unsupported websocket version specification");
return false;
}
// Initialize / Negotiate Extensions
ExtensionStack extensionStack = new ExtensionStack(getExtensionFactory());
// Usually from a Configurator.
if (response.isExtensionsNegotiated()) {
// Use pre-negotiated extension list from response
extensionStack.negotiate(response.getExtensions());
} else {
// Use raw extension list from request
extensionStack.negotiate(request.getExtensions());
}
// Get original HTTP connection
EndPoint endp = http.getEndPoint();
Connector connector = http.getConnector();
Executor executor = connector.getExecutor();
ByteBufferPool bufferPool = connector.getByteBufferPool();
// Setup websocket connection
AbstractWebSocketConnection wsConnection = new WebSocketServerConnection(endp, executor, scheduler, driver.getPolicy(), bufferPool);
extensionStack.setPolicy(driver.getPolicy());
extensionStack.configure(wsConnection.getParser());
extensionStack.configure(wsConnection.getGenerator());
if (LOG.isDebugEnabled()) {
LOG.debug("HttpConnection: {}", http);
LOG.debug("WebSocketConnection: {}", wsConnection);
}
// Setup Session
WebSocketSession session = createSession(request.getRequestURI(), driver, wsConnection);
session.setUpgradeRequest(request);
// set true negotiated extension list back to response
response.setExtensions(extensionStack.getNegotiatedExtensions());
session.setUpgradeResponse(response);
wsConnection.addListener(session);
// Setup Incoming Routing
wsConnection.setNextIncomingFrames(extensionStack);
extensionStack.setNextIncoming(session);
// Setup Outgoing Routing
session.setOutgoingHandler(extensionStack);
extensionStack.setNextOutgoing(wsConnection);
// Start Components
session.addManaged(extensionStack);
this.addManaged(session);
if (session.isFailed()) {
throw new IOException("Session failed to start");
}
// Tell jetty about the new upgraded connection
request.setServletAttribute(HttpConnection.UPGRADE_CONNECTION_ATTRIBUTE, wsConnection);
if (LOG.isDebugEnabled())
LOG.debug("Handshake Response: {}", handshaker);
if (getSendServerVersion(connector))
response.setHeader("Server", HttpConfiguration.SERVER_VERSION);
// Process (version specific) handshake response
handshaker.doHandshakeResponse(request, response);
if (LOG.isDebugEnabled())
LOG.debug("Websocket upgrade {} {} {} {}", request.getRequestURI(), version, response.getAcceptedSubProtocol(), wsConnection);
return true;
}
use of org.eclipse.jetty.server.Connector in project rest.li by linkedin.
the class HttpJettyServer method getConnectors.
protected Connector[] getConnectors(Server server) {
HttpConfiguration configuration = new HttpConfiguration();
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(configuration, HttpCompliance.RFC2616));
connector.setPort(_port);
return new Connector[] { connector };
}
Aggregations