org.apache.catalina.connector.Connector Java Examples

The following examples show how to use org.apache.catalina.connector.Connector. 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: AbstractWebServiceTest.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void initialize() throws Exception {
	AbstractSpringTest.init();
	tomcat = new Tomcat();
	Connector connector = new Connector("HTTP/1.1");
	connector.setProperty("address", InetAddress.getByName(HOST).getHostAddress());
	connector.setPort(0);
	tomcat.getService().addConnector(connector);
	tomcat.setConnector(connector);
	File wd = Files.createTempDirectory("om" + randomUUID().toString()).toFile();
	tomcat.setBaseDir(wd.getCanonicalPath());
	tomcat.getHost().setAppBase(wd.getCanonicalPath());
	tomcat.getHost().setAutoDeploy(false);
	tomcat.getHost().setDeployOnStartup(false);
	tomcat.addWebapp(CONTEXT, getOmHome().getAbsolutePath());
	tomcat.getConnector(); // to init the connector
	tomcat.start();
	port = tomcat.getConnector().getLocalPort();
}
 
Example #2
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Get the default http connector. You can set more
 * parameters - the port is already initialized.
 *
 * <p>
 * Alternatively, you can construct a Connector and set any params,
 * then call addConnector(Connector)
 *
 * @return A connector object that can be customized
 */
public Connector getConnector() {
    Service service = getService();
    if (service.findConnectors().length > 0) {
        return service.findConnectors()[0];
    }

    if (defaultConnectorCreated) {
        return null;
    }
    // The same as in standard Tomcat configuration.
    // This creates an APR HTTP connector if AprLifecycleListener has been
    // configured (created) and Tomcat Native library is available.
    // Otherwise it creates a NIO HTTP connector.
    Connector connector = new Connector("HTTP/1.1");
    connector.setPort(port);
    service.addConnector(connector);
    defaultConnectorCreated = true;
    return connector;
}
 
Example #3
Source File: ConnectorCreateRule.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Process the beginning of this element.
 *
 * @param namespace the namespace URI of the matching element, or an
 *   empty string if the parser is not namespace aware or the element has
 *   no namespace
 * @param name the local name if the parser is namespace aware, or just
 *   the element name otherwise
 * @param attributes The attribute list for this element
 */
@Override
public void begin(String namespace, String name, Attributes attributes)
        throws Exception {
    Service svc = (Service)digester.peek();
    Executor ex = null;
    if ( attributes.getValue("executor")!=null ) {
        ex = svc.getExecutor(attributes.getValue("executor"));
    }
    Connector con = new Connector(attributes.getValue("protocol"));
    if (ex != null) {
        setExecutor(con, ex);
    }
    String sslImplementationName = attributes.getValue("sslImplementationName");
    if (sslImplementationName != null) {
        setSSLImplementationName(con, sslImplementationName);
    }
    digester.push(con);
}
 
Example #4
Source File: ManagerServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected Map<String,List<String>> getConnectorCiphers(StringManager smClient) {
    Map<String,List<String>> result = new HashMap<>();

    Connector connectors[] = getConnectors();
    for (Connector connector : connectors) {
        if (Boolean.TRUE.equals(connector.getProperty("SSLEnabled"))) {
            SSLHostConfig[] sslHostConfigs = connector.getProtocolHandler().findSslHostConfigs();
            for (SSLHostConfig sslHostConfig : sslHostConfigs) {
                String name = connector.toString() + "-" + sslHostConfig.getHostName();
                /* Add cipher list, keep order but remove duplicates */
                result.put(name, new ArrayList<>(new LinkedHashSet<>(
                    Arrays.asList(sslHostConfig.getEnabledCiphers()))));
            }
        } else {
            ArrayList<String> cipherList = new ArrayList<>(1);
            cipherList.add(smClient.getString("managerServlet.notSslConnector"));
            result.put(connector.toString(), cipherList);
        }
    }
    return result;
}
 
Example #5
Source File: TomcatConfig.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * create the https additional connection for tomcat
 */
private Connector initiateHttpsConnector(ServerProperties serverProperties) {
	Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
	connector.setScheme(ConstantsTomcat.HTTPS);
	connector.setPort(serverProperties.getServerPort());
	connector.setSecure(true);
	Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
	protocol.setSSLEnabled(true);
	protocol.setKeystoreFile(serverProperties.getHttpsKeyStore());
	protocol.setKeystorePass(serverProperties.getHttpsKeyStorePassword());
	protocol.setKeystoreType(serverProperties.getHttpsKeyStoreType());
	protocol.setKeyPass(serverProperties.getHttpsKeyPassword());
	protocol.setKeyAlias(serverProperties.getHttpsKeyAlias());
	protocol.setMaxHttpHeaderSize(serverProperties.getMaxHttpHeaderSize());
	connector.setRedirectPort(ConstantsTomcat.REDIRECT_PORT);
	connector.setAllowTrace(serverProperties.isAllowTrace());
	return connector;
}
 
Example #6
Source File: ApplicationContext.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void populateSessionTrackingModes() {
    // URL re-writing is always enabled by default
    defaultSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL);
    supportedSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL);

    if (context.getCookies()) {
        defaultSessionTrackingModes.add(SessionTrackingMode.COOKIE);
        supportedSessionTrackingModes.add(SessionTrackingMode.COOKIE);
    }

    // SSL not enabled by default as it can only used on its own
    // Context > Host > Engine > Service
    Service s = ((Engine) context.getParent().getParent()).getService();
    Connector[] connectors = s.findConnectors();
    // Need at least one SSL enabled connector to use the SSL session ID.
    for (Connector connector : connectors) {
        if (Boolean.TRUE.equals(connector.getAttribute("SSLEnabled"))) {
            supportedSessionTrackingModes.add(SessionTrackingMode.SSL);
            break;
        }
    }
}
 
Example #7
Source File: MaxKeySslConfig.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
}
 
Example #8
Source File: ConnectorStoreAppender.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Print Connector Values. <ul><li> Special handling to default jkHome.
 * </li><li> Don't save catalina.base path at server.xml</li><li></ul>
 *
 * @see org.apache.catalina.storeconfig.StoreAppender#isPrintValue(java.lang.Object,
 *      java.lang.Object, java.lang.String,
 *      org.apache.catalina.storeconfig.StoreDescription)
 */
@Override
public boolean isPrintValue(Object bean, Object bean2, String attrName,
        StoreDescription desc) {
    boolean isPrint = super.isPrintValue(bean, bean2, attrName, desc);
    if (isPrint) {
        if ("jkHome".equals(attrName)) {
            Connector connector = (Connector) bean;
            File catalinaBase = getCatalinaBase();
            File jkHomeBase = getJkHomeBase((String) connector
                    .getProperty("jkHome"), catalinaBase);
            isPrint = !catalinaBase.equals(jkHomeBase);

        }
    }
    return isPrint;
}
 
Example #9
Source File: TomcatWebSocketTestServer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void setup() {
	this.port = SocketUtils.findAvailableTcpPort();

	Connector connector = new Connector(Http11NioProtocol.class.getName());
	connector.setPort(this.port);

	File baseDir = createTempDir("tomcat");
	String baseDirPath = baseDir.getAbsolutePath();

	this.tomcatServer = new Tomcat();
	this.tomcatServer.setBaseDir(baseDirPath);
	this.tomcatServer.setPort(this.port);
	this.tomcatServer.getService().addConnector(connector);
	this.tomcatServer.setConnector(connector);
}
 
Example #10
Source File: WebappAuthenticationValveTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This method tests the behaviour of the invoke method of WebAuthenticationValve when "
        + "secured endpoints are invoked.")
public void testInvokeSecuredEndpoints() throws NoSuchFieldException, IllegalAccessException {
    String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes()));
    Request request = createRequest("basic " + encodedString);
    webappAuthenticationValve.invoke(request, null, compositeValve);
    encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER + "test").getBytes()));
    request = createRequest("basic " + encodedString);
    Response response = new Response();
    org.apache.coyote.Response coyoteResponse = new org.apache.coyote.Response();
    Connector connector = new Connector();
    response.setConnector(connector);
    response.setCoyoteResponse(coyoteResponse);
    webappAuthenticationValve.invoke(request, response, compositeValve);
    Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED,
            "Response of un-authorized request is not updated");
}
 
Example #11
Source File: MBeanFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Create a new Connector
 *
 * @param parent MBean Name of the associated parent component
 * @param address The IP address on which to bind
 * @param port TCP port number to listen on
 * @param isAjp Create a AJP/1.3 Connector
 * @param isSSL Create a secure Connector
 *
 * @exception Exception if an MBean cannot be created or registered
 */
private String createConnector(String parent, String address, int port, boolean isAjp, boolean isSSL)
    throws Exception {
    // Set the protocol
    String protocol = isAjp ? "AJP/1.3" : "HTTP/1.1";
    Connector retobj = new Connector(protocol);
    if ((address!=null) && (address.length()>0)) {
        retobj.setProperty("address", address);
    }
    // Set port number
    retobj.setPort(port);
    // Set SSL
    retobj.setSecure(isSSL);
    retobj.setScheme(isSSL ? "https" : "http");
    // Add the new instance to its parent component
    // FIX ME - addConnector will fail
    ObjectName pname = new ObjectName(parent);
    Service service = getService(pname);
    service.addConnector(retobj);

    // Return the corresponding MBean name
    ObjectName coname = retobj.getObjectName();

    return coname.toString();
}
 
Example #12
Source File: ConnectorSF.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aConnector,
        StoreDescription parentDesc) throws Exception {

    if (aConnector instanceof Connector) {
        Connector connector = (Connector) aConnector;
        // Store nested <Listener> elements
        LifecycleListener listeners[] = connector.findLifecycleListeners();
        storeElementArray(aWriter, indent, listeners);
        // Store nested <UpgradeProtocol> elements
        UpgradeProtocol[] upgradeProtocols = connector.findUpgradeProtocols();
        storeElementArray(aWriter, indent, upgradeProtocols);
        if (Boolean.TRUE.equals(connector.getProperty("SSLEnabled"))) {
            // Store nested <SSLHostConfig> elements
            SSLHostConfig[] hostConfigs = connector.findSslHostConfigs();
            storeElementArray(aWriter, indent, hostConfigs);
        }
    }
}
 
Example #13
Source File: ApplicationContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void populateSessionTrackingModes() {
    // URL re-writing is always enabled by default
    defaultSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL);
    supportedSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL);

    if (context.getCookies()) {
        defaultSessionTrackingModes.add(SessionTrackingMode.COOKIE);
        supportedSessionTrackingModes.add(SessionTrackingMode.COOKIE);
    }

    // SSL not enabled by default as it can only used on its own
    // Context > Host > Engine > Service
    Connector[] connectors = service.findConnectors();
    // Need at least one SSL enabled connector to use the SSL session ID.
    for (Connector connector : connectors) {
        if (Boolean.TRUE.equals(connector.getAttribute("SSLEnabled"))) {
            supportedSessionTrackingModes.add(SessionTrackingMode.SSL);
            break;
        }
    }
}
 
Example #14
Source File: TomcatConfig.java    From tailstreamer with MIT License 6 votes vote down vote up
private Connector createSslConnector() {
    if (sslConfig == null) {
        throw new IllegalStateException("SSL configuration not specified");
    }

    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
    connector.setScheme("https");
    connector.setSecure(true);
    connector.setPort(sslConfig.getPort());
    protocol.setSSLEnabled(sslConfig.isEnable());
    protocol.setKeystoreFile(sslConfig.getKeystore());
    protocol.setKeystorePass(sslConfig.getKeystorePassword());
    protocol.setKeyAlias(sslConfig.getKeyAlias());

    logger.info(String.format("Initializing SSL connector on port %d", sslConfig.getPort()));
    return connector;
}
 
Example #15
Source File: MBeanFactory.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new Connector
 *
 * @param parent MBean Name of the associated parent component
 * @param address The IP address on which to bind
 * @param port TCP port number to listen on
 * @param isAjp Create a AJP/1.3 Connector
 * @param isSSL Create a secure Connector
 *
 * @exception Exception if an MBean cannot be created or registered
 */
private String createConnector(String parent, String address, int port, boolean isAjp, boolean isSSL)
    throws Exception {
    Connector retobj = new Connector();
    if ((address!=null) && (address.length()>0)) {
        retobj.setProperty("address", address);
    }
    // Set port number
    retobj.setPort(port);
    // Set the protocol
    retobj.setProtocol(isAjp ? "AJP/1.3" : "HTTP/1.1");
    // Set SSL
    retobj.setSecure(isSSL);
    retobj.setScheme(isSSL ? "https" : "http");
    // Add the new instance to its parent component
    // FIX ME - addConnector will fail
    ObjectName pname = new ObjectName(parent);
    Service service = getService(pname);
    service.addConnector(retobj);
    
    // Return the corresponding MBean name
    ObjectName coname = retobj.getObjectName();
    
    return (coname.toString());
}
 
Example #16
Source File: TestClientCertTls13.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    Tomcat tomcat = getTomcatInstance();

    Connector connector = tomcat.getConnector();
    Assume.assumeTrue(TesterSupport.isDefaultTLSProtocolForTesting13(connector));

    TesterSupport.configureClientCertContext(tomcat);
    // Need to override some of the previous settings
    tomcat.getConnector().setProperty("sslEnabledProtocols", Constants.SSL_PROTO_TLSv1_3);
    // And add force authentication to occur on the initial handshake
    tomcat.getConnector().setProperty("clientAuth", "required");

    TesterSupport.configureClientSsl();
}
 
Example #17
Source File: TestSwallowAbortedUploads.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private synchronized void init(int status, boolean swallow)
        throws Exception {

    Tomcat tomcat = getTomcatInstance();
    context = tomcat.addContext("", TEMP_DIR);
    AbortedPOSTServlet servlet = new AbortedPOSTServlet(status);
    Tomcat.addServlet(context, servletName, servlet);
    context.addServletMappingDecoded(URI, servletName);
    context.setSwallowAbortedUploads(swallow);

    tomcat.start();

    Connector c = tomcat.getConnector();
    c.setMaxPostSize(2 * hugeSize);
    c.setProperty("maxSwallowSize", Integer.toString(hugeSize));

    setPort(c.getLocalPort());
}
 
Example #18
Source File: Http2TestBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
void handleGoAwayResponse(int lastStream, Http2Error expectedError)
        throws Http2Exception, IOException {
    try {
        parser.readFrame(true);

        Assert.assertTrue(output.getTrace(), output.getTrace().startsWith(
                "0-Goaway-[" + lastStream + "]-[" + expectedError.getCode() + "]-["));
    } catch (SocketException se) {
        // On some platform / Connector combinations (e.g. Windows / NIO2),
        // the TCP connection close will be processed before the client gets
        // a chance to read the connection close frame.
        Tomcat tomcat = getTomcatInstance();
        Connector connector = tomcat.getConnector();

        Assume.assumeTrue("This test is only expected to trigger an exception with NIO2",
                connector.getProtocolHandlerClassName().contains("Nio2"));

        Assume.assumeTrue("This test is only expected to trigger an exception on Windows",
                System.getProperty("os.name").startsWith("Windows"));
    }
}
 
Example #19
Source File: Bootstrap.java    From lite-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(Connector connector) {
    Http11NioProtocol protocol = (Http11NioProtocol) connector
            .getProtocolHandler();
    // 设置最大连接数
    protocol.setMaxConnections(2000);
    // 设置最大线程数
    protocol.setMaxThreads(2000);
    protocol.setConnectionTimeout(30000);
}
 
Example #20
Source File: Port80ServletContainerCustomizer.java    From JSF-on-Spring-Boot with GNU General Public License v3.0 5 votes vote down vote up
public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) {
    factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
      @Override
      public void customize(Connector connector) {
    	  connector.setPort(80);
//        Object defaultMaxThreads = connector.getAttribute("maxThreads");
//        connector.getAttribute("javax.faces.CLIENT_WINDOW_MODE")
        connector.setAttribute("maxThreads", MAX_THREADS);
      }
    });
  }
 
Example #21
Source File: Bootstrap.java    From lite-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(Connector connector) {
    Http11NioProtocol protocol = (Http11NioProtocol) connector
            .getProtocolHandler();
    // 设置最大连接数
    protocol.setMaxConnections(2000);
    // 设置最大线程数
    protocol.setMaxThreads(2000);
    protocol.setConnectionTimeout(30000);
}
 
Example #22
Source File: WebServerService.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ServletWebServerFactory servletContainer() {
	TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
  connector.setScheme("http");
  connector.setPort(getAppHttpPort());

  tomcat.addAdditionalTomcatConnectors(connector);
  return tomcat;
}
 
Example #23
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 #24
Source File: App.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
private Connector createHTTPConnector() {
	Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
	// 同时启用http(8080)、https(8443)两个端口
	connector.setScheme("http");
	connector.setSecure(false);
	connector.setPort(80);
	connector.setRedirectPort(8443);
	return connector;
}
 
Example #25
Source File: TomcatWebSocketTestServer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void setup() {
	Connector connector = new Connector(Http11NioProtocol.class.getName());
	connector.setPort(0);

	File baseDir = createTempDir("tomcat");
	String baseDirPath = baseDir.getAbsolutePath();

	this.tomcatServer = new Tomcat();
	this.tomcatServer.setBaseDir(baseDirPath);
	this.tomcatServer.setPort(0);
	this.tomcatServer.getService().addConnector(connector);
	this.tomcatServer.setConnector(connector);
}
 
Example #26
Source File: StandardService.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke a pre-startup initialization. This is used to allow connectors
 * to bind to restricted ports under Unix operating environments.
 */
@Override
protected void initInternal() throws LifecycleException {

    super.initInternal();
    
    if (container != null) {
        container.init();
    }

    // Initialize any Executors
    for (Executor executor : findExecutors()) {
        if (executor instanceof LifecycleMBeanBase) {
            ((LifecycleMBeanBase) executor).setDomain(getDomain());
        }
        executor.init();
    }

    // Initialize our defined Connectors
    synchronized (connectors) {
        for (Connector connector : connectors) {
            try {
                connector.init();
            } catch (Exception e) {
                String message = sm.getString(
                        "standardService.connector.initFailed", connector);
                log.error(message, e);

                if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"))
                    throw new LifecycleException(message);
            }
        }
    }
}
 
Example #27
Source File: CustomConfig.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private Connector createTomcatConnector() {
    Connector connector = new
        Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setPort(8000);
    connector.setSecure(false);
    connector.setRedirectPort(8443);
    return connector;
}
 
Example #28
Source File: WebConfig.java    From jcart with MIT License 5 votes vote down vote up
private Connector initiateHttpConnector() {
	Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
	connector.setScheme("http");
	connector.setPort(9090);
	connector.setSecure(false);
	connector.setRedirectPort(serverPort);

	return connector;
}
 
Example #29
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static Tomcat startServer(String port)
    throws ServletException, LifecycleException, IOException {
    Tomcat server = new Tomcat();
    server.setPort(0);
    String currentDir = new File(".").getCanonicalPath();
    String baseDir = currentDir + File.separator + "target";
    server.setBaseDir(baseDir);

    server.getHost().setAppBase("tomcat/idp/webapps");
    server.getHost().setAutoDeploy(true);
    server.getHost().setDeployOnStartup(true);

    Connector httpsConnector = new Connector();
    httpsConnector.setPort(Integer.parseInt(port));
    httpsConnector.setSecure(true);
    httpsConnector.setScheme("https");
    httpsConnector.setAttribute("keyAlias", "mytomidpkey");
    httpsConnector.setAttribute("keystorePass", "tompass");
    httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
    httpsConnector.setAttribute("truststorePass", "tompass");
    httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
    httpsConnector.setAttribute("clientAuth", "want");
    // httpsConnector.setAttribute("clientAuth", "false");
    httpsConnector.setAttribute("sslProtocol", "TLS");
    httpsConnector.setAttribute("SSLEnabled", true);

    server.getService().addConnector(httpsConnector);

    File stsWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp-sts");
    server.addWebapp("/fediz-idp-sts", stsWebapp.getAbsolutePath());

    File idpWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp");
    server.addWebapp("/fediz-idp", idpWebapp.getAbsolutePath());

    server.start();

    return server;
}
 
Example #30
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;
}