Search in sources :

Example 26 with HttpConfiguration

use of org.eclipse.jetty.server.HttpConfiguration in project blade by biezhi.

the class ConstraintSecurityHandler method checkUserDataPermissions.

@Override
protected boolean checkUserDataPermissions(String pathInContext, Request request, Response response, RoleInfo roleInfo) throws IOException {
    if (roleInfo == null)
        return true;
    if (roleInfo.isForbidden())
        return false;
    UserDataConstraint dataConstraint = roleInfo.getUserDataConstraint();
    if (dataConstraint == null || dataConstraint == UserDataConstraint.None)
        return true;
    HttpConfiguration httpConfig = Request.getBaseRequest(request).getHttpChannel().getHttpConfiguration();
    if (dataConstraint == UserDataConstraint.Confidential || dataConstraint == UserDataConstraint.Integral) {
        if (request.isSecure())
            return true;
        if (httpConfig.getSecurePort() > 0) {
            String scheme = httpConfig.getSecureScheme();
            int port = httpConfig.getSecurePort();
            String url = URIUtil.newURI(scheme, request.getServerName(), port, request.getRequestURI(), request.getQueryString());
            response.setContentLength(0);
            response.sendRedirect(url);
        } else
            response.sendError(HttpStatus.FORBIDDEN_403, "!Secure");
        request.setHandled(true);
        return false;
    } else {
        throw new IllegalArgumentException("Invalid dataConstraint value: " + dataConstraint);
    }
}
Also used : HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) Constraint(org.eclipse.jetty.util.security.Constraint)

Example 27 with HttpConfiguration

use of org.eclipse.jetty.server.HttpConfiguration in project rest.li by linkedin.

the class HttpServerBuilder method build.

public Server build() {
    Server server = new Server();
    // HTTP Configuration
    HttpConfiguration configuration = new HttpConfiguration();
    configuration.setSendXPoweredBy(true);
    configuration.setSendServerVersion(true);
    configuration.setSendXPoweredBy(false);
    configuration.setSendServerVersion(false);
    configuration.setSendDateHeader(false);
    // HTTP Connector
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(configuration), new HTTP2CServerConnectionFactory(configuration));
    http.setIdleTimeout(_idleTimeout);
    http.setPort(HTTP_PORT);
    server.addConnector(http);
    ServletContextHandler handler = new ServletContextHandler(server, "");
    handler.addServlet(new ServletHolder(new HttpServlet() {

        private static final long serialVersionUID = 0;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            awaitLatch();
            readEntity(req.getReader());
            addStatus(resp);
            addHeader(resp);
            addContent(resp);
        }

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            awaitLatch();
            readEntity(req.getReader());
            addStatus(resp);
            addHeader(resp);
            addContent(resp);
        }

        @Override
        protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            awaitLatch();
            readEntity(req.getReader());
            addStatus(resp);
            addHeader(resp);
            addContent(resp);
        }

        private void addStatus(HttpServletResponse resp) throws IOException {
            resp.setStatus(_status);
        }

        private void addHeader(HttpServletResponse resp) throws IOException {
            if (_headerSize <= 0) {
                return;
            }
            int valueSize = _headerSize - HEADER_NAME.length();
            char[] headerValue = new char[valueSize];
            Arrays.fill(headerValue, 'a');
            resp.addHeader(HEADER_NAME, new String(headerValue));
        }

        private void addContent(HttpServletResponse resp) throws IOException {
            if (_responseSize <= 0) {
                return;
            }
            char[] content = new char[_responseSize];
            Arrays.fill(content, 'a');
            resp.getWriter().write(content);
        }

        private void awaitLatch() {
            if (_responseLatch != null) {
                try {
                    _responseLatch.await(RESPONSE_LATCH_TIMEOUT, RESPONSE_LATCH_TIMEUNIT);
                } catch (InterruptedException e) {
                }
            }
        }

        private void readEntity(BufferedReader reader) throws IOException {
            while (true) {
                char[] bytes = new char[8192];
                int read = reader.read(bytes);
                if (read < 0) {
                    break;
                }
            }
        }
    }), "/*");
    return server;
}
Also used : Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) HTTP2CServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory) BufferedReader(java.io.BufferedReader) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 28 with HttpConfiguration

use of org.eclipse.jetty.server.HttpConfiguration in project camel by apache.

the class WebsocketComponent method createStaticResourcesServer.

protected Server createStaticResourcesServer(ServletContextHandler context, String host, int port, String home) throws Exception {
    Server server = new Server();
    HttpConfiguration httpConfig = new HttpConfiguration();
    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    connector.setHost(host);
    connector.setPort(port);
    server.addConnector(connector);
    return createStaticResourcesServer(server, context, home);
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Example 29 with HttpConfiguration

use of org.eclipse.jetty.server.HttpConfiguration in project hadoop by apache.

the class TestJettyHelper method createJettyServer.

private Server createJettyServer() {
    try {
        InetAddress localhost = InetAddress.getByName("localhost");
        String host = "localhost";
        ServerSocket ss = new ServerSocket(0, 50, localhost);
        int port = ss.getLocalPort();
        ss.close();
        Server server = new Server();
        ServerConnector conn = new ServerConnector(server);
        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setRequestHeaderSize(JettyUtils.HEADER_SIZE);
        http_config.setResponseHeaderSize(JettyUtils.HEADER_SIZE);
        http_config.setSecureScheme("https");
        http_config.addCustomizer(new SecureRequestCustomizer());
        ConnectionFactory connFactory = new HttpConnectionFactory(http_config);
        conn.addConnectionFactory(connFactory);
        conn.setHost(host);
        conn.setPort(port);
        if (ssl) {
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setNeedClientAuth(false);
            sslContextFactory.setKeyStorePath(keyStore);
            sslContextFactory.setKeyStoreType(keyStoreType);
            sslContextFactory.setKeyStorePassword(keyStorePassword);
            conn.addFirstConnectionFactory(new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()));
        }
        server.addConnector(conn);
        return server;
    } catch (Exception ex) {
        throw new RuntimeException("Could not start embedded servlet container, " + ex.getMessage(), ex);
    }
}
Also used : SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServerSocket(java.net.ServerSocket) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ConnectionFactory(org.eclipse.jetty.server.ConnectionFactory) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) InetAddress(java.net.InetAddress)

Example 30 with HttpConfiguration

use of org.eclipse.jetty.server.HttpConfiguration in project qpid-broker-j by apache.

the class HttpManagement method createConnector.

private ServerConnector createConnector(final HttpPort<?> port, final Server server) {
    port.setPortManager(this);
    if (port.getState() != State.ACTIVE) {
        // TODO - RG - probably does nothing
        port.startAsync();
    }
    HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory();
    httpConnectionFactory.getHttpConfiguration().setSendServerVersion(false);
    httpConnectionFactory.getHttpConfiguration().setSendXPoweredBy(false);
    HttpConfiguration.Customizer requestAttributeCustomizer = (connector, httpConfiguration, request) -> HttpManagementUtil.getPortAttributeAction(port).performAction(request);
    httpConnectionFactory.getHttpConfiguration().addCustomizer(requestAttributeCustomizer);
    httpConnectionFactory.getHttpConfiguration().addCustomizer(new SecureRequestCustomizer());
    ConnectionFactory[] connectionFactories;
    Collection<Transport> transports = port.getTransports();
    if (!transports.contains(Transport.SSL)) {
        connectionFactories = new ConnectionFactory[] { httpConnectionFactory };
    } else if (transports.contains(Transport.SSL)) {
        SslContextFactory sslContextFactory = getSslContextFactory(port);
        ConnectionFactory sslConnectionFactory;
        if (port.getTransports().contains(Transport.TCP)) {
            sslConnectionFactory = new TlsOrPlainConnectionFactory(sslContextFactory, httpConnectionFactory.getProtocol());
        } else {
            sslConnectionFactory = new SslConnectionFactory(sslContextFactory, httpConnectionFactory.getProtocol());
        }
        connectionFactories = new ConnectionFactory[] { sslConnectionFactory, httpConnectionFactory };
    } else {
        throw new IllegalArgumentException("Unexpected transport on port " + port.getName() + ":" + transports);
    }
    ServerConnector connector = new ServerConnector(server, new QBBTrackingThreadPool(port.getThreadPoolMaximum(), port.getThreadPoolMinimum()), null, null, port.getDesiredNumberOfAcceptors(), port.getDesiredNumberOfSelectors(), connectionFactories) {

        @Override
        public void open() throws IOException {
            try {
                super.open();
            } catch (BindException e) {
                InetSocketAddress addr = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
                throw new PortBindFailureException(addr);
            }
        }
    };
    connector.setAcceptQueueSize(port.getAcceptBacklogSize());
    String bindingAddress = port.getBindingAddress();
    if (bindingAddress != null && !bindingAddress.trim().equals("") && !bindingAddress.trim().equals("*")) {
        connector.setHost(bindingAddress.trim());
    }
    connector.setPort(port.getPort());
    if (transports.contains(Transport.SSL)) {
        connector.addBean(new SslHandshakeListener() {

            @Override
            public void handshakeFailed(final Event event, final Throwable failure) {
                SSLEngine sslEngine = event.getSSLEngine();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.info("TLS handshake failed: host='{}', port={}", sslEngine.getPeerHost(), sslEngine.getPeerPort(), failure);
                } else {
                    LOGGER.info("TLS handshake failed: host='{}', port={}: {}", sslEngine.getPeerHost(), sslEngine.getPeerPort(), String.valueOf(failure));
                }
            }
        });
    }
    int acceptors = connector.getAcceptors();
    int selectors = connector.getSelectorManager().getSelectorCount();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Created connector for http port {} with maxThreads={}, minThreads={}, acceptors={}, selectors={}, acceptBacklog={}", port.getName(), port.getThreadPoolMaximum(), port.getThreadPoolMinimum(), acceptors, selectors, port.getAcceptBacklogSize());
    }
    int requiredNumberOfConnections = acceptors + 2 * selectors + 1;
    if (port.getThreadPoolMaximum() < requiredNumberOfConnections) {
        throw new IllegalConfigurationException(String.format("Insufficient number of threads is configured on http port '%s': max=%d < needed(acceptors=%d + selectors=2*%d + request=1)", port.getName(), port.getThreadPoolMaximum(), acceptors, selectors));
    }
    return connector;
}
Also used : ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) PortMessages(org.apache.qpid.server.logging.messages.PortMessages) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) ManagedAttributeField(org.apache.qpid.server.model.ManagedAttributeField) PortManager(org.apache.qpid.server.model.port.PortManager) BrokerModel(org.apache.qpid.server.model.BrokerModel) InteractiveAuthenticationFilter(org.apache.qpid.server.management.plugin.filter.InteractiveAuthenticationFilter) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) VirtualHostQueryServlet(org.apache.qpid.server.management.plugin.servlet.rest.VirtualHostQueryServlet) StructureServlet(org.apache.qpid.server.management.plugin.servlet.rest.StructureServlet) Map(java.util.Map) Server(org.eclipse.jetty.server.Server) EnumSet(java.util.EnumSet) SslHandshakeListener(org.eclipse.jetty.io.ssl.SslHandshakeListener) RestServlet(org.apache.qpid.server.management.plugin.servlet.rest.RestServlet) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) Set(java.util.Set) Executors(java.util.concurrent.Executors) ExceptionHandlingFilter(org.apache.qpid.server.management.plugin.filter.ExceptionHandlingFilter) TlsOrPlainConnectionFactory(org.apache.qpid.server.management.plugin.portunification.TlsOrPlainConnectionFactory) Transport(org.apache.qpid.server.model.Transport) StateTransition(org.apache.qpid.server.model.StateTransition) KeyStore(org.apache.qpid.server.model.KeyStore) ForbiddingTraceFilter(org.apache.qpid.server.management.plugin.filter.ForbiddingTraceFilter) TaskExecutor(org.apache.qpid.server.configuration.updater.TaskExecutor) Joiner(com.google.common.base.Joiner) FileServlet(org.apache.qpid.server.management.plugin.servlet.FileServlet) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) SSLParameters(javax.net.ssl.SSLParameters) MetaDataServlet(org.apache.qpid.server.management.plugin.servlet.rest.MetaDataServlet) AbstractPluginAdapter(org.apache.qpid.server.model.adapter.AbstractPluginAdapter) JsonValueServlet(org.apache.qpid.server.management.plugin.servlet.rest.JsonValueServlet) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HttpPort(org.apache.qpid.server.model.port.HttpPort) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) StringWriter(java.io.StringWriter) ManagedObjectFactoryConstructor(org.apache.qpid.server.model.ManagedObjectFactoryConstructor) ExecutorThreadPool(org.eclipse.jetty.util.thread.ExecutorThreadPool) IOException(java.io.IOException) ConnectionFactory(org.eclipse.jetty.server.ConnectionFactory) AuthenticationCheckFilter(org.apache.qpid.server.management.plugin.filter.AuthenticationCheckFilter) Futures(com.google.common.util.concurrent.Futures) Connection(org.eclipse.jetty.io.Connection) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) DaemonThreadFactory(org.apache.qpid.server.util.DaemonThreadFactory) LoggerFactory(org.slf4j.LoggerFactory) SettableFuture(com.google.common.util.concurrent.SettableFuture) TrustStore(org.apache.qpid.server.model.TrustStore) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ThreadFactory(java.util.concurrent.ThreadFactory) SSLSessionContext(javax.net.ssl.SSLSessionContext) Port(org.apache.qpid.server.model.Port) LoggingFilter(org.apache.qpid.server.management.plugin.filter.LoggingFilter) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) RedirectFilter(org.apache.qpid.server.management.plugin.filter.RedirectFilter) MultipartConfigElement(javax.servlet.MultipartConfigElement) InetSocketAddress(java.net.InetSocketAddress) PortBindFailureException(org.apache.qpid.server.transport.PortBindFailureException) ManagedObject(org.apache.qpid.server.model.ManagedObject) List(java.util.List) TimeZoneServlet(org.apache.qpid.server.management.plugin.servlet.rest.TimeZoneServlet) Name(org.eclipse.jetty.util.annotation.Name) Writer(java.io.Writer) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) LogoutServlet(org.apache.qpid.server.management.plugin.servlet.rest.LogoutServlet) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BrokerQueryServlet(org.apache.qpid.server.management.plugin.servlet.rest.BrokerQueryServlet) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) HashMap(java.util.HashMap) BindException(java.net.BindException) ManagementConsoleMessages(org.apache.qpid.server.logging.messages.ManagementConsoleMessages) SSLEngine(javax.net.ssl.SSLEngine) HashSet(java.util.HashSet) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) RewriteRequestForUncompressedJavascript(org.apache.qpid.server.management.plugin.filter.RewriteRequestForUncompressedJavascript) AbstractConfigurationChangeListener(org.apache.qpid.server.model.AbstractConfigurationChangeListener) ExecutorService(java.util.concurrent.ExecutorService) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) SaslServlet(org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet) Logger(org.slf4j.Logger) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) SSLUtil(org.apache.qpid.server.transport.network.security.ssl.SSLUtil) Broker(org.apache.qpid.server.model.Broker) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) State(org.apache.qpid.server.model.State) Protocol(org.apache.qpid.server.model.Protocol) QueueReportServlet(org.apache.qpid.server.management.plugin.servlet.rest.QueueReportServlet) RootServlet(org.apache.qpid.server.management.plugin.servlet.RootServlet) ServerConnector(org.eclipse.jetty.server.ServerConnector) ApiDocsServlet(org.apache.qpid.server.management.plugin.servlet.rest.ApiDocsServlet) DispatcherType(javax.servlet.DispatcherType) Collections(java.util.Collections) PortBindFailureException(org.apache.qpid.server.transport.PortBindFailureException) SslHandshakeListener(org.eclipse.jetty.io.ssl.SslHandshakeListener) InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServerConnector(org.eclipse.jetty.server.ServerConnector) TlsOrPlainConnectionFactory(org.apache.qpid.server.management.plugin.portunification.TlsOrPlainConnectionFactory) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ConnectionFactory(org.eclipse.jetty.server.ConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) TlsOrPlainConnectionFactory(org.apache.qpid.server.management.plugin.portunification.TlsOrPlainConnectionFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) BindException(java.net.BindException) Transport(org.apache.qpid.server.model.Transport)

Aggregations

HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)199 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)148 ServerConnector (org.eclipse.jetty.server.ServerConnector)148 Server (org.eclipse.jetty.server.Server)103 SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)88 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)88 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)81 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)42 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)40 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)34 IOException (java.io.IOException)24 Connector (org.eclipse.jetty.server.Connector)23 File (java.io.File)20 HTTP2ServerConnectionFactory (org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 ServletException (javax.servlet.ServletException)15 HttpServletResponse (javax.servlet.http.HttpServletResponse)15 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)15 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)15 HTTP2CServerConnectionFactory (org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory)13