Search in sources :

Example 56 with Connector

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();
}
Also used : AbstractNetworkConnector(org.eclipse.jetty.server.AbstractNetworkConnector) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) Connector(org.eclipse.jetty.server.Connector) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Server(org.eclipse.jetty.server.Server) InputStreamReader(java.io.InputStreamReader) CountDownLatch(java.util.concurrent.CountDownLatch) URL(java.net.URL) URLConnection(java.net.URLConnection) AbstractNetworkConnector(org.eclipse.jetty.server.AbstractNetworkConnector) AbstractNetworkConnector(org.eclipse.jetty.server.AbstractNetworkConnector) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) Test(org.junit.Test)

Example 57 with Connector

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);
        }
    });
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) LocalConnector(org.eclipse.jetty.server.LocalConnector) Connector(org.eclipse.jetty.server.Connector) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) LocalConnector(org.eclipse.jetty.server.LocalConnector) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Before(org.junit.Before)

Example 58 with Connector

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());
}
Also used : AbstractConnector(org.eclipse.jetty.server.AbstractConnector) Connector(org.eclipse.jetty.server.Connector) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) ConnectorStatistics(org.eclipse.jetty.server.ConnectorStatistics) AbstractConnector(org.eclipse.jetty.server.AbstractConnector) PrintWriter(java.io.PrintWriter)

Example 59 with Connector

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;
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) Connector(org.eclipse.jetty.server.Connector) EndPoint(org.eclipse.jetty.io.EndPoint) IOException(java.io.IOException) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) EndPoint(org.eclipse.jetty.io.EndPoint) AbstractWebSocketConnection(org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Executor(java.util.concurrent.Executor)

Example 60 with Connector

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 };
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Aggregations

Connector (org.eclipse.jetty.server.Connector)79 Server (org.eclipse.jetty.server.Server)41 ServerConnector (org.eclipse.jetty.server.ServerConnector)25 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)22 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)17 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)15 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)13 IOException (java.io.IOException)12 NetworkConnector (org.eclipse.jetty.server.NetworkConnector)12 Test (org.junit.Test)11 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)10 SelectChannelConnector (org.eclipse.jetty.server.nio.SelectChannelConnector)8 Test (org.testng.annotations.Test)8 Handler (org.eclipse.jetty.server.Handler)7 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)6 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)6 ServletException (javax.servlet.ServletException)5