Java Code Examples for org.apache.catalina.connector.Connector

The following examples show how to use org.apache.catalina.connector.Connector. These examples are extracted from open source projects. 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 Project: Tomcat8-Source-Read   Source File: ManagerServlet.java    License: 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 2
Source Project: Tomcat8-Source-Read   Source File: Tomcat.java    License: 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 Project: Tomcat8-Source-Read   Source File: ConnectorCreateRule.java    License: 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 Project: Tomcat7.0.67   Source File: ApplicationContext.java    License: 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 5
@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 6
Source Project: Tomcat8-Source-Read   Source File: MBeanFactory.java    License: 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 7
Source Project: Tomcat8-Source-Read   Source File: ConnectorStoreAppender.java    License: 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 8
Source Project: Tomcat8-Source-Read   Source File: ConnectorSF.java    License: 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 9
Source Project: Tomcat8-Source-Read   Source File: ApplicationContext.java    License: 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 10
Source Project: tailstreamer   Source File: TomcatConfig.java    License: 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 11
Source Project: Tomcat7.0.67   Source File: MBeanFactory.java    License: 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 12
Source Project: Tomcat8-Source-Read   Source File: TestSwallowAbortedUploads.java    License: 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 13
Source Project: Tomcat8-Source-Read   Source File: Http2TestBase.java    License: 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 14
Source Project: openmeetings   Source File: AbstractWebServiceTest.java    License: 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 15
Source Project: Tomcat8-Source-Read   Source File: TestClientCertTls13.java    License: 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 16
@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 17
Source Project: singleton   Source File: TomcatConfig.java    License: 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 18
Source Project: MaxKey   Source File: MaxKeySslConfig.java    License: 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 19
Source Project: sofa-ark   Source File: ArkTomcatWebServer.java    License: Apache License 2.0 5 votes vote down vote up
private String getPortsDescription(boolean localPort) {
    StringBuilder ports = new StringBuilder();
    for (Connector connector : this.tomcat.getService().findConnectors()) {
        if (ports.length() != 0) {
            ports.append(' ');
        }
        int port = localPort ? connector.getLocalPort() : connector.getPort();
        ports.append(port).append(" (").append(connector.getScheme()).append(')');
    }
    return ports.toString();
}
 
Example 20
Source Project: Tomcat8-Source-Read   Source File: ManagerServlet.java    License: 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 21
Source Project: Tomcat7.0.67   Source File: StandardService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Remove the specified Connector from the set associated from this
 * Service.  The removed Connector will also be disassociated from our
 * Container.
 *
 * @param connector The Connector to be removed
 */
@Override
public void removeConnector(Connector connector) {

    synchronized (connectors) {
        int j = -1;
        for (int i = 0; i < connectors.length; i++) {
            if (connector == connectors[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;
        if (connectors[j].getState().isAvailable()) {
            try {
                connectors[j].stop();
            } catch (LifecycleException e) {
                log.error(sm.getString(
                        "standardService.connector.stopFailed",
                        connectors[j]), e);
            }
        }
        connector.setService(null);
        int k = 0;
        Connector results[] = new Connector[connectors.length - 1];
        for (int i = 0; i < connectors.length; i++) {
            if (i != j)
                results[k++] = connectors[i];
        }
        connectors = results;

        // Report this property change to interested listeners
        support.firePropertyChange("connector", connector, null);
    }

}
 
Example 22
Source Project: Java-API-Test-Examples   Source File: TomcatHttpConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 配置一个Http连接信息
 * @return
 */
private Connector redirectConnector() {
	Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
	connector.setScheme("http");
	connector.setPort(8088);
	connector.setSecure(false);
	connector.setRedirectPort(443);
	return connector;
}
 
Example 23
Source Project: Tomcat8-Source-Read   Source File: ConnectorCreateRule.java    License: MIT License 5 votes vote down vote up
private static void setExecutor(Connector con, Executor ex) throws Exception {
    Method m = IntrospectionUtils.findMethod(con.getProtocolHandler().getClass(),"setExecutor",new Class[] {java.util.concurrent.Executor.class});
    if (m!=null) {
        m.invoke(con.getProtocolHandler(), new Object[] {ex});
    }else {
        log.warn(sm.getString("connector.noSetExecutor", con));
    }
}
 
Example 24
Source Project: armeria   Source File: UnmanagedTomcatServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    // Prepare Tomcat instances.
    tomcatWithWebApp = new Tomcat();
    tomcatWithWebApp.setPort(0);
    tomcatWithWebApp.setBaseDir("build" + File.separatorChar +
                                "tomcat-" + UnmanagedTomcatServiceTest.class.getSimpleName() + "-1");

    tomcatWithWebApp.addWebapp("", WebAppContainerTest.webAppRoot().getAbsolutePath());
    TomcatUtil.engine(tomcatWithWebApp.getService(), "foo").setName("tomcatWithWebApp");

    tomcatWithoutWebApp = new Tomcat();
    tomcatWithoutWebApp.setPort(0);
    tomcatWithoutWebApp.setBaseDir("build" + File.separatorChar +
                                   "tomcat-" + UnmanagedTomcatServiceTest.class.getSimpleName() + "-2");
    assertThat(TomcatUtil.engine(tomcatWithoutWebApp.getService(), "bar")).isNotNull();

    // Start the Tomcats.
    tomcatWithWebApp.start();
    tomcatWithoutWebApp.start();

    // Bind them to the Server.
    sb.serviceUnder("/empty/", TomcatService.of(new Connector(), "someHost"))
      .serviceUnder("/some-webapp-nohostname/",
                    TomcatService.of(tomcatWithWebApp.getConnector()))
      .serviceUnder("/no-webapp/", TomcatService.of(tomcatWithoutWebApp))
      .serviceUnder("/some-webapp/", TomcatService.of(tomcatWithWebApp));
}
 
Example 25
@Override
public void customize(Connector connector) {
    Http11NioProtocol protocol = (Http11NioProtocol) connector
            .getProtocolHandler();
    // 设置最大连接数
    protocol.setMaxConnections(2000);
    // 设置最大线程数
    protocol.setMaxThreads(2000);
    protocol.setConnectionTimeout(30000);
}
 
Example 26
Source Project: Tomcat8-Source-Read   Source File: ServiceMBean.java    License: MIT License 5 votes vote down vote up
/**
 * Add a new Connector to the set of defined Connectors, and associate it
 * with this Service's Container.
 *
 * @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
 *
 * @throws MBeanException error creating the connector
 */
public void addConnector(String address, int port, boolean isAjp, boolean isSSL) throws MBeanException {

    Service service = doGetManagedResource();
    String protocol = isAjp ? "AJP/1.3" : "HTTP/1.1";
    Connector connector = new Connector(protocol);
    if ((address!=null) && (address.length()>0)) {
        connector.setProperty("address", address);
    }
    connector.setPort(port);
    connector.setSecure(isSSL);
    connector.setScheme(isSSL ? "https" : "http");

    service.addConnector(connector);
}
 
Example 27
Source Project: Tomcat8-Source-Read   Source File: MBeanFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Remove an existing Connector.
 *
 * @param name MBean Name of the component to remove
 *
 * @exception Exception if a component cannot be removed
 */
public void removeConnector(String name) throws Exception {

    // Acquire a reference to the component to be removed
    ObjectName oname = new ObjectName(name);
    Service service = getService(oname);
    String port = oname.getKeyProperty("port");
    String address = oname.getKeyProperty("address");
    if (address != null) {
        address = ObjectName.unquote(address);
    }

    Connector conns[] = service.findConnectors();

    for (int i = 0; i < conns.length; i++) {
        String connAddress = null;
        Object objConnAddress = conns[i].getProperty("address");
        if (objConnAddress != null) {
            connAddress = ((InetAddress) objConnAddress).getHostAddress();
        }
        String connPort = ""+conns[i].getPort();

        if (address == null) {
            // Don't combine this with outer if or we could get an NPE in
            // 'else if' below
            if (connAddress == null && port.equals(connPort)) {
                service.removeConnector(conns[i]);
                conns[i].destroy();
                break;
            }
        } else if (address.equals(connAddress) && port.equals(connPort)) {
            service.removeConnector(conns[i]);
            conns[i].destroy();
            break;
        }
    }
}
 
Example 28
Source Project: Tomcat8-Source-Read   Source File: StandardServiceSF.java    License: MIT License 5 votes vote down vote up
/**
 * Store the specified service element children.
 *
 * @param aWriter Current output writer
 * @param indent Indentation level
 * @param aService Service to store
 * @param parentDesc The element description
 * @throws Exception Configuration storing error
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aService,
        StoreDescription parentDesc) throws Exception {
    if (aService instanceof StandardService) {
        StandardService service = (StandardService) aService;
        // Store nested <Listener> elements
        LifecycleListener listeners[] = ((Lifecycle) service)
                .findLifecycleListeners();
        storeElementArray(aWriter, indent, listeners);

        // Store nested <Executor> elements
        Executor[] executors = service.findExecutors();
        storeElementArray(aWriter, indent, executors);

        Connector connectors[] = service.findConnectors();
        storeElementArray(aWriter, indent, connectors);

        // Store nested <Engine> element
        Engine container = service.getContainer();
        if (container != null) {
            StoreDescription elementDesc = getRegistry().findDescription(container.getClass());
            if (elementDesc != null) {
                IStoreFactory factory = elementDesc.getStoreFactory();
                factory.store(aWriter, indent, container);
            }
        }
    }
}
 
Example 29
Source Project: Tomcat7.0.67   Source File: StandardService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Start nested components ({@link Executor}s, {@link Connector}s and
 * {@link Container}s) and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {

    if(log.isInfoEnabled())
        log.info(sm.getString("standardService.start.name", this.name));
    setState(LifecycleState.STARTING);

    // Start our defined Container first
    if (container != null) {
        synchronized (container) {
            container.start();
        }
    }

    synchronized (executors) {
        for (Executor executor: executors) {
            executor.start();
        }
    }

    // Start our defined Connectors second
    synchronized (connectors) {
        for (Connector connector: connectors) {
            try {
                // If it has already failed, don't try and start it
                if (connector.getState() != LifecycleState.FAILED) {
                    connector.start();
                }
            } catch (Exception e) {
                log.error(sm.getString(
                        "standardService.connector.startFailed",
                        connector), e);
            }
        }
    }
}
 
Example 30
Source Project: tomcatsrc   Source File: StandardService.java    License: 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 (connectorsLock) {
        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);
            }
        }
    }
}