org.apache.coyote.ProtocolHandler Java Examples

The following examples show how to use org.apache.coyote.ProtocolHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TomcatApplication.java    From micro-server with Apache License 2.0 6 votes vote down vote up
private void addSSL(Connector connector) {
    try {

        SSLProperties sslProperties = serverData.getRootContext().getBean(SSLProperties.class);
        ProtocolHandler handler = connector.getProtocolHandler();
        if (sslProperties != null && handler instanceof AbstractHttp11JsseProtocol) {
            new SSLConfigurationBuilder().build((AbstractHttp11JsseProtocol) handler, sslProperties);
            connector.setScheme("https");
            connector.setSecure(true);
        }

    } catch (BeanNotOfRequiredTypeException e) {

    }


}
 
Example #2
Source File: LetsEncryptSetup.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(final Tomcat tomcat) {
    final ProtocolHandler protocolHandler = tomcat.getConnector().getProtocolHandler();
    if (!AbstractHttp11Protocol.class.isInstance(protocolHandler)) {
        return;
    }

    final LetsEncryptReloadLifecycle.LetsEncryptConfig config = instance.getConfiguration()
        .getExtension(LetsEncryptReloadLifecycle.LetsEncryptConfig.class);
    if (config.getDomains() == null || config.getDomains().trim().isEmpty()) {
        return;
    }

    new LogFacade(getClass().getName()).info("Let's Encrypt extension activated");
    tomcat.getHost().getPipeline().addValve(new LetsEncryptValve(AbstractHttp11Protocol.class.cast(protocolHandler), config));
}
 
Example #3
Source File: TomcatWebServer.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void configConnector(Connector connector, TomcatConf tomcatConf) {
  connector.setURIEncoding(tomcatConf.getUriEncoding());
  ProtocolHandler protocolHandler = connector.getProtocolHandler();
  if (protocolHandler instanceof AbstractProtocol) {
    AbstractProtocol<?> handler = (AbstractProtocol<?>) protocolHandler;
    handler.setAcceptCount(tomcatConf.getAcceptCount());
    handler.setMaxConnections(tomcatConf.getMaxConnections());
    handler.setMinSpareThreads(tomcatConf.getMinSpareThreads());
    handler.setMaxThreads(tomcatConf.getMaxThreads());
    handler.setConnectionTimeout(tomcatConf.getConnectionTimeout());
    if (handler instanceof AbstractHttp11Protocol) {
      AbstractHttp11Protocol<?> protocol = (AbstractHttp11Protocol<?>) handler;
      protocol.setMaxHttpHeaderSize(tomcatConf.getMaxHttpHeaderSize());
    }
  }
}
 
Example #4
Source File: SystemBootAutoConfiguration.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Customization servlet container configuring. </br>
 * 
 * @see {@link EmbeddedServletContainerAutoConfiguration}
 * 
 * @return
 */
@Bean
public EmbeddedServletContainerCustomizer customEmbeddedServletContainerCustomizer() {
	return container -> {
		// Tomcat container customization
		if (container instanceof TomcatEmbeddedServletContainerFactory) {
			TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
			tomcat.addConnectorCustomizers(connector -> {
				ProtocolHandler handler = connector.getProtocolHandler();
				if (handler instanceof AbstractProtocol) {
					AbstractProtocol<?> protocol = (AbstractProtocol<?>) handler;
					/**
					 * {@link org.apache.tomcat.util.net.NioEndpoint#startInternal()}
					 * {@link org.apache.tomcat.util.net.NioEndpoint#createExecutor()}
					 */
					protocol.setExecutor(customTomcatExecutor(protocol));
				}
			});
		} else {
			log.warn("Skip using custom servlet container, EmbeddedServletContainer: {}", container);
		}
	};

}
 
Example #5
Source File: CrnkTomcatAutoConfiguration.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(Connector connector) {
	ProtocolHandler protocolHandler = connector.getProtocolHandler();
	if (protocolHandler instanceof AbstractHttp11Protocol) {
		AbstractHttp11Protocol protocol11 = (AbstractHttp11Protocol) protocolHandler;
		try {
			String relaxedQueryChars = (String) PropertyUtils.getProperty(protocol11, PROPERTY_NAME);
			if (relaxedQueryChars == null) {
				relaxedQueryChars = "";
			}
			relaxedQueryChars += "[]{}";
			PropertyUtils.setProperty(protocol11, PROPERTY_NAME, relaxedQueryChars);
		} catch (Exception e) {
			LOGGER.debug("failed to set relaxed query charts, Tomcat might be outdated");
		}
	}
}
 
Example #6
Source File: Connector.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
public Connector(String protocol) {

        // 指定 协议
        setProtocol(protocol);
        // Instantiate protocol handler
        try {

            // Connector 自身在创建的时候会创建  Http11Protocol  http 的Handler处理类
            Class<?> clazz = Class.forName(protocolHandlerClassName);
            this.protocolHandler = (ProtocolHandler) clazz.newInstance();
        } catch (Exception e) {
            log.error(sm.getString(
                    "coyoteConnector.protocolHandlerInstantiationFailed"), e);
        }
    }
 
Example #7
Source File: MBeanUtils.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Deregister the MBean for this
 * <code>Connector</code> object.
 *
 * @param connector The Connector to be managed
 *
 * @exception Exception if an MBean cannot be deregistered
 * @deprecated  Unused. Will be removed in Tomcat 8.0.x
 */
@Deprecated
static void destroyMBean(Connector connector, Service service)
    throws Exception {

    // domain is engine name
    String domain = service.getContainer().getName();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    ObjectName oname = createObjectName(domain, connector);
    if( mserver.isRegistered( oname ))  {
        mserver.unregisterMBean(oname);
    }
    // Unregister associated request processor
    String worker = null;
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof Http11Protocol) {
        worker = ((Http11Protocol)handler).getName();
    } else if (handler instanceof Http11NioProtocol) {
        worker = ((Http11NioProtocol)handler).getName();
    } else if (handler instanceof Http11AprProtocol) {
        worker = ((Http11AprProtocol)handler).getName();
    } else if (handler instanceof AjpProtocol) {
        worker = ((AjpProtocol)handler).getName();
    } else if (handler instanceof AjpAprProtocol) {
        worker = ((AjpAprProtocol)handler).getName();
    }
    ObjectName query = new ObjectName(
            domain + ":type=RequestProcessor,worker=" + worker + ",*");
    Set<ObjectName> results = mserver.queryNames(query, null);
    for(ObjectName result : results) {
        mserver.unregisterMBean(result);
    }
}
 
Example #8
Source File: ThreadLocalLeakPreventionListener.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Updates each ThreadPoolExecutor with the current time, which is the time
 * when a context is being stopped.
 * 
 * @param context
 *            the context being stopped, used to discover all the Connectors
 *            of its parent Service.
 */
private void stopIdleThreads(Context context) {
    if (serverStopping) return;

    if (!(context instanceof StandardContext) ||
        !((StandardContext) context).getRenewThreadsWhenStoppingContext()) {
        log.debug("Not renewing threads when the context is stopping. "
            + "It is not configured to do it.");
        return;
    }

    Engine engine = (Engine) context.getParent().getParent();
    Service service = engine.getService();
    Connector[] connectors = service.findConnectors();
    if (connectors != null) {
        for (Connector connector : connectors) {
            ProtocolHandler handler = connector.getProtocolHandler();
            Executor executor = null;
            if (handler != null) {
                executor = handler.getExecutor();
            }

            if (executor instanceof ThreadPoolExecutor) {
                ThreadPoolExecutor threadPoolExecutor =
                    (ThreadPoolExecutor) executor;
                threadPoolExecutor.contextStopping();
            } else if (executor instanceof StandardThreadExecutor) {
                StandardThreadExecutor stdThreadExecutor =
                    (StandardThreadExecutor) executor;
                stdThreadExecutor.contextStopping();
            }

        }
    }
}
 
Example #9
Source File: MBeanUtils.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Deregister the MBean for this
 * <code>Connector</code> object.
 *
 * @param connector The Connector to be managed
 *
 * @exception Exception if an MBean cannot be deregistered
 * @deprecated  Unused. Will be removed in Tomcat 8.0.x
 */
@Deprecated
static void destroyMBean(Connector connector, Service service)
    throws Exception {

    // domain is engine name
    String domain = service.getContainer().getName();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    ObjectName oname = createObjectName(domain, connector);
    if( mserver.isRegistered( oname ))  {
        mserver.unregisterMBean(oname);
    }
    // Unregister associated request processor
    String worker = null;
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof Http11Protocol) {
        worker = ((Http11Protocol)handler).getName();
    } else if (handler instanceof Http11NioProtocol) {
        worker = ((Http11NioProtocol)handler).getName();
    } else if (handler instanceof Http11AprProtocol) {
        worker = ((Http11AprProtocol)handler).getName();
    } else if (handler instanceof AjpProtocol) {
        worker = ((AjpProtocol)handler).getName();
    } else if (handler instanceof AjpAprProtocol) {
        worker = ((AjpAprProtocol)handler).getName();
    }
    ObjectName query = new ObjectName(
            domain + ":type=RequestProcessor,worker=" + worker + ",*");
    Set<ObjectName> results = mserver.queryNames(query, null);
    for(ObjectName result : results) {
        mserver.unregisterMBean(result);
    }
}
 
Example #10
Source File: ThreadLocalLeakPreventionListener.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Updates each ThreadPoolExecutor with the current time, which is the time
 * when a context is being stopped.
 * 
 * @param context
 *            the context being stopped, used to discover all the Connectors
 *            of its parent Service.
 */
private void stopIdleThreads(Context context) {
    if (serverStopping) return;

    if (!(context instanceof StandardContext) ||
        !((StandardContext) context).getRenewThreadsWhenStoppingContext()) {
        log.debug("Not renewing threads when the context is stopping. "
            + "It is not configured to do it.");
        return;
    }

    Engine engine = (Engine) context.getParent().getParent();
    Service service = engine.getService();
    Connector[] connectors = service.findConnectors();
    if (connectors != null) {
        for (Connector connector : connectors) {
            ProtocolHandler handler = connector.getProtocolHandler();
            Executor executor = null;
            if (handler != null) {
                executor = handler.getExecutor();
            }

            if (executor instanceof ThreadPoolExecutor) {
                ThreadPoolExecutor threadPoolExecutor =
                    (ThreadPoolExecutor) executor;
                threadPoolExecutor.contextStopping();
            } else if (executor instanceof StandardThreadExecutor) {
                StandardThreadExecutor stdThreadExecutor =
                    (StandardThreadExecutor) executor;
                stdThreadExecutor.contextStopping();
            }

        }
    }
}
 
Example #11
Source File: Connector.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public Connector(String protocol) {
    setProtocol(protocol);
    // Instantiate protocol handler
    try {
        Class<?> clazz = Class.forName(protocolHandlerClassName);
        this.protocolHandler = (ProtocolHandler) clazz.newInstance();
    } catch (Exception e) {
        log.error(sm.getString(
                "coyoteConnector.protocolHandlerInstantiationFailed"), e);
    }
}
 
Example #12
Source File: TomcatServerFactory.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
static int getLocalPort(Tomcat tomcat) {
    Service[] services = tomcat.getServer().findServices();
    for (Service service : services) {
        for (Connector connector : service.findConnectors()) {
            ProtocolHandler protocolHandler = connector.getProtocolHandler();
            if (protocolHandler instanceof Http11AprProtocol || protocolHandler instanceof Http11NioProtocol) {
                return connector.getLocalPort();
            }
        }
    }
    return 0;
}
 
Example #13
Source File: TomcatContainerCustomizer.java    From radar with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
	MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
	mappings.add("woff", "application/x-font-woff");
	mappings.add("eot", "application/vnd.ms-fontobject");
	mappings.add("ttf", "application/x-font-ttf");
	container.setMimeMappings(mappings);

	if (!(container instanceof TomcatEmbeddedServletContainerFactory)) {
		return;
	}
	if (!environment.containsProperty(TOMCAT_ACCEPTOR_COUNT)) {
		return;
	}
	TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
	tomcat.addConnectorCustomizers(new TomcatConnectorCustomizer() {

		@Override
		public void customize(Connector connector) {
			ProtocolHandler handler = connector.getProtocolHandler();
			if (handler instanceof Http11NioProtocol) {
				Http11NioProtocol http = (Http11NioProtocol) handler;
				acceptCount = soaConfig.getTomcatAcceptCount();
				soaConfig.registerChanged(() -> {
					if (acceptCount != soaConfig.getTomcatAcceptCount()) {
						acceptCount = soaConfig.getTomcatAcceptCount();
						http.setBacklog(acceptCount);
					}
				});
				http.setBacklog(acceptCount);
				logger.info("Setting tomcat accept count to {}", acceptCount);
			}
		}
	});
}
 
Example #14
Source File: GracefulShutdownTomcatConnectorCustomizerTest.java    From spring-boot-graceful-shutdown with Apache License 2.0 5 votes vote down vote up
private Connector configureConnectorToReturnDifferentThreadPoolImplementation() {
    Connector mockConnector = mock(Connector.class);
    ProtocolHandler mockProtocolHandler = mock(ProtocolHandler.class);

    when(mockConnector.getProtocolHandler()).thenReturn(mockProtocolHandler);
    when(mockProtocolHandler.getExecutor()).thenReturn(new SyncTaskExecutor());

    return mockConnector;
}
 
Example #15
Source File: ThreadLocalLeakPreventionListener.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Updates each ThreadPoolExecutor with the current time, which is the time
 * when a context is being stopped.
 *
 * @param context
 *            the context being stopped, used to discover all the Connectors
 *            of its parent Service.
 */
private void stopIdleThreads(Context context) {
    if (serverStopping) return;

    if (!(context instanceof StandardContext) ||
        !((StandardContext) context).getRenewThreadsWhenStoppingContext()) {
        log.debug("Not renewing threads when the context is stopping. "
            + "It is not configured to do it.");
        return;
    }

    Engine engine = (Engine) context.getParent().getParent();
    Service service = engine.getService();
    Connector[] connectors = service.findConnectors();
    if (connectors != null) {
        for (Connector connector : connectors) {
            ProtocolHandler handler = connector.getProtocolHandler();
            Executor executor = null;
            if (handler != null) {
                executor = handler.getExecutor();
            }

            if (executor instanceof ThreadPoolExecutor) {
                ThreadPoolExecutor threadPoolExecutor =
                    (ThreadPoolExecutor) executor;
                threadPoolExecutor.contextStopping();
            } else if (executor instanceof StandardThreadExecutor) {
                StandardThreadExecutor stdThreadExecutor =
                    (StandardThreadExecutor) executor;
                stdThreadExecutor.contextStopping();
            }

        }
    }
}
 
Example #16
Source File: ManagerServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected void sslReload(PrintWriter writer, String tlsHostName, StringManager smClient) {
    Connector connectors[] = getConnectors();
    boolean found = false;
    for (Connector connector : connectors) {
        if (Boolean.TRUE.equals(connector.getProperty("SSLEnabled"))) {
            ProtocolHandler protocol = connector.getProtocolHandler();
            if (protocol instanceof AbstractHttp11Protocol<?>) {
                AbstractHttp11Protocol<?> http11Protoocol = (AbstractHttp11Protocol<?>) protocol;
                if (tlsHostName == null || tlsHostName.length() == 0) {
                    found = true;
                    http11Protoocol.reloadSslHostConfigs();
                } else {
                    SSLHostConfig[] sslHostConfigs = http11Protoocol.findSslHostConfigs();
                    for (SSLHostConfig sslHostConfig : sslHostConfigs) {
                        if (sslHostConfig.getHostName().equalsIgnoreCase(tlsHostName)) {
                            found = true;
                            http11Protoocol.reloadSslHostConfig(tlsHostName);
                        }
                    }
                }
            }
        }
    }
    if (found) {
        if (tlsHostName == null || tlsHostName.length() == 0) {
            writer.println(smClient.getString("managerServlet.sslReloadAll"));
        } else {
            writer.println(smClient.getString("managerServlet.sslReload", tlsHostName));
        }
    } else {
        writer.println(smClient.getString("managerServlet.sslReloadFail"));
    }
}
 
Example #17
Source File: TestCustomSsl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void doTestCustomTrustManager(boolean serverTrustAll)
        throws Exception {

    if (!TesterSupport.RFC_5746_SUPPORTED) {
        // Make sure SSL renegotiation is not disabled in the JVM
        System.setProperty("sun.security.ssl.allowUnsafeRenegotiation",
                "true");
    }

    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    TesterSupport.configureClientCertContext(tomcat);

    // Override the defaults
    ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
    if (handler instanceof AbstractHttp11JsseProtocol) {
        ((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
    } else {
        // Unexpected
        fail("Unexpected handler type");
    }
    if (serverTrustAll) {
        tomcat.getConnector().setAttribute("trustManagerClassName",
                "org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
    }

    // Start Tomcat
    tomcat.start();

    TesterSupport.configureClientSsl();

    // Unprotected resource
    ByteChunk res =
            getUrl("https://localhost:" + getPort() + "/unprotected");
    assertEquals("OK", res.toString());

    // Protected resource
    res.recycle();
    int rc = -1;
    try {
        rc = getUrl("https://localhost:" + getPort() + "/protected", res,
            null, null);
    } catch (SocketException se) {
        if (serverTrustAll) {
            fail(se.getMessage());
            se.printStackTrace();
        }
    } catch (SSLException he) {
        if (serverTrustAll) {
            fail(he.getMessage());
            he.printStackTrace();
        }
    }
    if (serverTrustAll) {
        assertEquals(200, rc);
        assertEquals("OK-" + TesterSupport.ROLE, res.toString());
    } else {
        assertTrue(rc != 200);
        assertEquals("", res.toString());
    }
}
 
Example #18
Source File: TomcatServer.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public void initialize() {
		try {
			JFishTomcat tomcat = new JFishTomcat();
			if(serverConfig.getTomcatContextClassName()!=null){
				tomcat.setContextClass((Class<StandardContext>)ReflectUtils.loadClass(serverConfig.getTomcatContextClassName(), true));
			}
			int port = serverConfig.getPort();
			tomcat.setPort(port);
//			tomcat.setBaseDir(webConfig.getServerBaseDir());
			String baseDir = null;
			if(!Utils.isBlank(serverConfig.getServerBaseDir())){
				baseDir = serverConfig.getServerBaseDir();
			}else{
				baseDir = System.getProperty("java.io.tmpdir");
				logger.info("set serverBaseDir as java.io.tmpdir : {} ", baseDir);
			}
			tomcat.setBaseDir(baseDir);
			
			// This magic line makes Tomcat look for WAR files in catalinaHome/webapps
			// and automatically deploy them
//			tomcat.getHost().addLifecycleListener(new HostConfig());
			appBaseFile = new File(baseDir+"/tomcat.webapps."+this.serverConfig.getPort());
			if(!appBaseFile.exists()){
				appBaseFile.mkdirs();
			}
			appBaseFile.deleteOnExit();
			tomcat.getHost().setAppBase(appBaseFile.getAbsolutePath());
			Connector connector = tomcat.getConnector();
			connector.setURIEncoding("UTF-8");
			connector.setRedirectPort(serverConfig.getRedirectPort());
			connector.setMaxPostSize(serverConfig.getMaxPostSize());
			
			ProtocolHandler protocol = connector.getProtocolHandler();
			if(protocol instanceof AbstractHttp11Protocol){
				/*****
				 * <Connector port="8080" protocol="HTTP/1.1" 
					   connectionTimeout="20000" 
   						redirectPort="8181" compression="500" 
  						compressableMimeType="text/html,text/xml,text/plain,application/octet-stream" />
				 */
				AbstractHttp11Protocol<?> hp = (AbstractHttp11Protocol<?>) protocol;
				hp.setCompression("on");
				hp.setCompressableMimeTypes("text/html,text/xml,text/plain,application/octet-stream");
			}
			
			
			StandardServer server = (StandardServer) tomcat.getServer();
			AprLifecycleListener listener = new AprLifecycleListener();
			server.addLifecycleListener(listener);

			/*tomcat.addUser("adminuser", "adminuser");
			tomcat.addRole("adminuser", "admin");
			tomcat.addRole("adminuser", "admin");*/
			
			this.tomcat = tomcat;
		} catch (Exception e) {
			throw new RuntimeException("web server initialize error , check it. " + e.getMessage(), e);
		}
		
		/*Runtime.getRuntime().addShutdownHook(new Thread(){

			@Override
			public void run() {
				appBaseFile.delete();
			}
			
		});*/
	}
 
Example #19
Source File: TestCustomSsl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void doTestCustomTrustManager(boolean serverTrustAll)
        throws Exception {

    if (!TesterSupport.RFC_5746_SUPPORTED) {
        // Make sure SSL renegotiation is not disabled in the JVM
        System.setProperty("sun.security.ssl.allowUnsafeRenegotiation",
                "true");
    }

    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    TesterSupport.configureClientCertContext(tomcat);

    // Override the defaults
    ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
    if (handler instanceof AbstractHttp11JsseProtocol) {
        ((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
    } else {
        // Unexpected
        fail("Unexpected handler type");
    }
    if (serverTrustAll) {
        tomcat.getConnector().setAttribute("trustManagerClassName",
                "org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
    }

    // Start Tomcat
    tomcat.start();

    TesterSupport.configureClientSsl();

    // Unprotected resource
    ByteChunk res =
            getUrl("https://localhost:" + getPort() + "/unprotected");
    assertEquals("OK", res.toString());

    // Protected resource
    res.recycle();
    int rc = -1;
    try {
        rc = getUrl("https://localhost:" + getPort() + "/protected", res,
            null, null);
    } catch (SocketException se) {
        if (serverTrustAll) {
            fail(se.getMessage());
            se.printStackTrace();
        }
    } catch (SSLException he) {
        if (serverTrustAll) {
            fail(he.getMessage());
            he.printStackTrace();
        }
    }
    if (serverTrustAll) {
        assertEquals(200, rc);
        assertEquals("OK-" + TesterSupport.ROLE, res.toString());
    } else {
        assertTrue(rc != 200);
        assertEquals("", res.toString());
    }
}
 
Example #20
Source File: HugeGraphStudio.java    From hugegraph-studio with Apache License 2.0 4 votes vote down vote up
/**
 * Run tomcat with configuration
 *
 * @param config the studio configuration
 * @throws Exception the exception
 */
public static void run(StudioServerConfig config) throws Exception {

    String address = config.getHttpBindAddress();
    int port = config.getHttpPort();
    validateHttpPort(address, port);

    String baseDir = config.getServerBasePath();
    String uiDir = String.format("%s/%s", baseDir,
                                 config.getServerUIDirectory());
    String apiWarFile = String.format("%s/%s", baseDir,
                                      config.getServerWarDirectory());
    validatePathExists(new File(uiDir));
    validateFileExists(new File(apiWarFile));

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(config.getHttpPort());

    ProtocolHandler ph = tomcat.getConnector().getProtocolHandler();
    if (ph instanceof AbstractProtocol) {
        ((AbstractProtocol) ph).setAddress(InetAddress.getByName(address));
    }
    tomcat.setHostname(address);

    StandardContext ui = configureUi(tomcat, uiDir);
    StandardContext api = configureWarFile(tomcat, apiWarFile, "/api");

    tomcat.start();

    server = tomcat.getServer();
    while (!server.getState().equals(LifecycleState.STARTED)) {
        Thread.sleep(100L);
    }

    if (!ui.getState().equals(LifecycleState.STARTED)) {
        LOG.error("Studio-ui failed to start. " +
                  "Please check logs for details");
        System.exit(1);
    }
    if (!api.getState().equals(LifecycleState.STARTED)) {
        LOG.error("Studio-api failed to start. " +
                  "Please check logs for details");
        System.exit(1);
    }

    String upMessage = String.format("HugeGraphStudio is now running on: " +
                                     "http://%s:%d\n", address, port);
    LOG.info(upMessage);
}
 
Example #21
Source File: TomcatContainerCustomizer.java    From pmq with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
	MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
	mappings.add("woff", "application/x-font-woff");
	mappings.add("eot", "application/vnd.ms-fontobject");
	mappings.add("ttf", "application/x-font-ttf");
	container.setMimeMappings(mappings);

	if (!(container instanceof TomcatEmbeddedServletContainerFactory)) {
		return;
	}
	if (!environment.containsProperty(TOMCAT_ACCEPTOR_COUNT)) {
		return;
	}
	TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
	tomcat.addConnectorCustomizers(new TomcatConnectorCustomizer() {

		@Override
		public void customize(Connector connector) {
			ProtocolHandler handler = connector.getProtocolHandler();
			if (handler instanceof Http11NioProtocol) {
				Http11NioProtocol http = (Http11NioProtocol) handler;
				acceptCount = soaConfig.getTomcatAcceptCount();
				maxThreads = soaConfig.getTomcatMaxThreads();
				minThreads = soaConfig.getTomcatMinThreads();
				soaConfig.registerChanged(() -> {						
					if (maxThreads != soaConfig.getTomcatMaxThreads()) {
						maxThreads = soaConfig.getTomcatMaxThreads();
						if (maxThreads > 0) {
							http.setMaxThreads(maxThreads);
						} else {
							http.setMaxThreads(200);
						}
					}
					if (minThreads != soaConfig.getTomcatMinThreads()) {
						minThreads = soaConfig.getTomcatMinThreads();
						if (minThreads > 0) {
							http.setMinSpareThreads(minThreads);
						} else {
							http.setMinSpareThreads(10);
						}
					}


				});
				http.setBacklog(acceptCount);
				http.setMaxThreads(maxThreads);
				http.setMinSpareThreads(minThreads);
				logger.info("Setting tomcat accept count to {}", acceptCount);
			}
		}
	});
}
 
Example #22
Source File: TestCustomSsl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestCustomTrustManager(TrustType trustType)
        throws Exception {

    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    TesterSupport.configureClientCertContext(tomcat);

    // Override the defaults
    ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
    if (handler instanceof AbstractHttp11JsseProtocol) {
        ((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
    } else {
        // Unexpected
        Assert.fail("Unexpected handler type");
    }
    if (trustType.equals(TrustType.ALL)) {
        tomcat.getConnector().setAttribute("trustManagerClassName",
                "org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
    } else if (trustType.equals(TrustType.CA)) {
        tomcat.getConnector().setAttribute("trustManagerClassName",
                "org.apache.tomcat.util.net.TesterSupport$SequentialTrustManager");
    }

    // Start Tomcat
    tomcat.start();

    TesterSupport.configureClientSsl();

    // Unprotected resource
    ByteChunk res =
            getUrl("https://localhost:" + getPort() + "/unprotected");
    Assert.assertEquals("OK", res.toString());

    // Protected resource
    res.recycle();
    int rc = -1;
    try {
        rc = getUrl("https://localhost:" + getPort() + "/protected", res,
            null, null);
    } catch (SocketException se) {
        if (!trustType.equals(TrustType.NONE)) {
            Assert.fail(se.getMessage());
            se.printStackTrace();
        }
    } catch (SSLException he) {
        if (!trustType.equals(TrustType.NONE)) {
            Assert.fail(he.getMessage());
            he.printStackTrace();
        }
    }

    if (trustType.equals(TrustType.CA)) {
        if (log.isDebugEnabled()) {
            int count = TesterSupport.getLastClientAuthRequestedIssuerCount();
            log.debug("Last client KeyManager usage: " + TesterSupport.getLastClientAuthKeyManagerUsage() +
                      ", " + count + " requested Issuers, first one: " +
                      (count > 0 ? TesterSupport.getLastClientAuthRequestedIssuer(0).getName() : "NONE"));
            log.debug("Expected requested Issuer: " + TesterSupport.getClientAuthExpectedIssuer());
        }
        Assert.assertTrue("Checking requested client issuer against " +
                TesterSupport.getClientAuthExpectedIssuer(),
                TesterSupport.checkLastClientAuthRequestedIssuers());
    }

    if (trustType.equals(TrustType.NONE)) {
        Assert.assertTrue(rc != 200);
        Assert.assertEquals("", res.toString());
    } else {
        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK-" + TesterSupport.ROLE, res.toString());
    }
}
 
Example #23
Source File: Connector.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * @return the protocol handler associated with the connector.
 */
public ProtocolHandler getProtocolHandler() {
    return this.protocolHandler;
}
 
Example #24
Source File: Connector.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Return the protocol handler associated with the connector.
 */
public ProtocolHandler getProtocolHandler() {

    return (this.protocolHandler);

}
 
Example #25
Source File: Connector.java    From Tomcat7.0.67 with Apache License 2.0 2 votes vote down vote up
/**
 * Return the protocol handler associated with the connector.
 */
public ProtocolHandler getProtocolHandler() {

    return (this.protocolHandler);

}