Java Code Examples for org.apache.catalina.connector.Connector#getPort()

The following examples show how to use org.apache.catalina.connector.Connector#getPort() . 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: TomcatWebServer.java    From spring-graalvm-native with 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 2
Source File: ArkTomcatWebServer.java    From sofa-ark with 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 3
Source File: SFContextServlet.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private int determineTomcatHttpPort(ServletContext ctx) {

		try {
            Object o = FieldUtils.readField(ctx, "context", true);
            StandardContext sCtx = (StandardContext) FieldUtils.readField(o, "context", true);
            Container container = (Container) sCtx;

            Container c = container.getParent();
	        while (c != null && !(c instanceof StandardEngine)) {
	            c = c.getParent();
	        }

	        if (c != null) {
	            StandardEngine engine = (StandardEngine) c;
	            for (Connector connector : engine.getService().findConnectors()) {

                    if(connector.getProtocol().startsWith("HTTP")) {
	            		return connector.getPort();
	            	}

	            }
	        }

        } catch (Exception e) {
            logger.error("Could not determine http port", e);
        }

		return 0;

	}
 
Example 4
Source File: ProxyTomcatConnectorCustomizer.java    From booties with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(final Connector connector) {
    if (!proxyConnectorCustomizerProperties.isEnabled()) {
        logger.warn("CUSTOMIZE CONNECTORS IS DISABLED");
        return;
    }

    for (ConnectorCustomizer cc : proxyConnectorCustomizerProperties.getCustomizers()) {

        if (cc.isEnabled()) {

            if (connector.getPort() == cc.getPort()) {
                logger.warn("CUSTOMIZE CONNECTOR ON PORT : {}", connector.getPort());

                logger.warn("SET CONNECTOR - 'secure' : {}", cc.isSecure());
                connector.setSecure(cc.isSecure());

                logger.warn("SET CONNECTOR - 'scheme' : {}", cc.getScheme());
                connector.setScheme(cc.getScheme());

                logger.warn("SET CONNECTOR - 'proxy-port' : {}", cc.getProxyPort());
                connector.setProxyPort(cc.getProxyPort());

                logger.warn("SET CONNECTOR - 'proxy-name' : {}", cc.getProxyName());
                connector.setProxyName(cc.getProxyName());
            } else {
                logger.info("No customizer found for connector on port : {}", connector.getPort());
            }

        }
    }
}
 
Example 5
Source File: TomcatWebServer.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
private void checkConnectorHasStarted(Connector connector) {
	if (LifecycleState.FAILED.equals(connector.getState())) {
		throw new RuntimeException("Failed to start connector:"+connector.getPort());
	}
}
 
Example 6
Source File: ArkTomcatWebServer.java    From sofa-ark with Apache License 2.0 4 votes vote down vote up
private void checkConnectorHasStarted(Connector connector) {
    if (LifecycleState.FAILED.equals(connector.getState())) {
        throw new ConnectorStartFailedException(connector.getPort());
    }
}
 
Example 7
Source File: ScipioConnectorInfo.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
protected ScipioConnectorInfo(ContainerConfig.Container.Property properties, Connector connector) {
    this.properties = properties;
    this.name = properties.name;
    this.port = connector.getPort();
    this.scheme = connector.getScheme();
}
 
Example 8
Source File: TomcatServer.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
public int getPort ()
{
   Connector connector =
      cat.getServer ().findServices ()[0].findConnectors ()[0];
   return connector.getPort ();
}
 
Example 9
Source File: SslTomEETest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    final File keystore = new File("target/keystore");

    {   // generate keystore/trustore
        if (keystore.exists()) {
            Files.delete(keystore);
        }

        keystore.getParentFile().mkdirs();
        try (final FileOutputStream fos = new FileOutputStream(keystore)) {
            final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
            keyGenerator.initialize(1024);

            final KeyPair pair = keyGenerator.generateKeyPair();

            final boolean addBc = Security.getProvider("BC") == null;
            if (addBc) {
                Security.addProvider(new BouncyCastleProvider());
            }
            try {

                final X509v1CertificateBuilder x509v1CertificateBuilder = new JcaX509v1CertificateBuilder(
                        new X500Name("cn=serveralias"),
                        BigInteger.valueOf(1),
                        new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)),
                        new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)),
                        new X500Name("cn=serveralias"),
                        pair.getPublic());

                final X509CertificateHolder certHldr = x509v1CertificateBuilder
                        .build(new JcaContentSignerBuilder("SHA1WithRSA")
                                .setProvider("BC").build(pair.getPrivate()));

                final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHldr);

                final KeyStore ks = KeyStore.getInstance("JKS");
                ks.load(null, "changeit".toCharArray());
                ks.setKeyEntry("serveralias", pair.getPrivate(), "changeit".toCharArray(), new Certificate[]{cert});
                ks.store(fos, "changeit".toCharArray());
            } finally {
                if (addBc) {
                    Security.removeProvider("BC");
                }
            }
        } catch (final Exception e) {
            Assert.fail(e.getMessage());
        }
    }

    final Configuration configuration = new Configuration();
    configuration.setSsl(true);
    configuration.setKeystoreFile(keystore.getAbsolutePath());
    configuration.setKeystorePass("changeit");
    configuration.setKeyAlias("serveralias");

    final Container container = new Container();
    container.setup(configuration);
    container.start();
    Connector[] connectors = container.getTomcat().getService().findConnectors();
    for(Connector conn : connectors) {
    	if(conn.getPort() == 8443) {
    		Object propertyObject = conn.getProperty("keystoreFile");
            assertNotNull(propertyObject);
            assertEquals(keystore.getAbsolutePath(), propertyObject.toString());
    	}
    }

    try {
        assertEquals(8443, ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("Tomcat:type=ProtocolHandler,port=8443"), "port"));
    } finally {
        container.stop();
    }

    // ensure it is not always started
    configuration.setSsl(false);
    container.setup(configuration);
    container.start();
    try {
        assertFalse(ManagementFactory.getPlatformMBeanServer().isRegistered(new ObjectName("Tomcat:type=ProtocolHandler,port=8443")));
    } finally {
        container.close();
    }

}
 
Example 10
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public List<String> setWsContainer(final HttpListener httpListener,
                                   final ClassLoader classLoader,
                                   String contextRoot, String virtualHost, final ServletInfo servletInfo,
                                   final String realmName, final String transportGuarantee, final String authMethod,
                                   final String moduleId) throws Exception {

    if (virtualHost == null) {
        virtualHost = engine.getDefaultHost();
    }

    final Container host = engine.findChild(virtualHost);
    if (host == null) {
        throw new IllegalArgumentException("Invalid virtual host '" + virtualHost + "'.  Do you have a matchiing Host entry in the server.xml?");
    }

    if ("ROOT".equals(contextRoot)) { // doesn't happen in tomee itself but with all our tooling around
        contextRoot = "";
    }
    if (!contextRoot.startsWith("/") && !contextRoot.isEmpty()) {
        contextRoot = "/" + contextRoot;
    }

    final Context context = (Context) host.findChild(contextRoot);
    if (context == null) {
        throw new IllegalArgumentException("Could not find web application context " + contextRoot + " in host " + host.getName());
    }

    final Wrapper wrapper = (Wrapper) context.findChild(servletInfo.servletName);
    if (wrapper == null) {
        throw new IllegalArgumentException("Could not find servlet " + servletInfo.servletName + " in web application context " + context.getName());
    }

    // for Pojo web services, we need to change the servlet class which is the service implementation
    // by the WsServler class
    wrapper.setServletClass(WsServlet.class.getName());
    if (wrapper.getServlet() != null) {
        wrapper.unload(); // deallocate previous one
        wrapper.load(); // reload this one withuot unloading it to keep the instance - unload is called during stop()
        // boolean controlling this method call can't be set to false through API so let do it ourself
        wrapper.getServlet().init(StandardWrapper.class.cast(wrapper)); // or Reflections.set(wrapper, "instanceInitialized", false);
    }

    setWsContainer(context, wrapper, httpListener);

    // add service locations
    final List<String> addresses = new ArrayList<>();
    for (final Connector connector : connectors) {
        for (final String mapping : wrapper.findMappings()) {
            final URI address = new URI(connector.getScheme(), null, host.getName(), connector.getPort(), (contextRoot.startsWith("/") ? "" : "/") + contextRoot + mapping, null, null);
            addresses.add(address.toString());
        }
    }
    return addresses;
}
 
Example 11
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void addServlet(final Container host, final Context context, final String mapping, final HttpListener httpListener, final String path,
                        final List<String> addresses, final boolean fakeDeployment, final String moduleId) {
    // build the servlet
    final Wrapper wrapper = context.createWrapper();
    wrapper.setName("webservice" + path.substring(1));
    wrapper.setServletClass(WsServlet.class.getName());

    // add servlet to context
    context.addChild(wrapper);
    context.addServletMappingDecoded(mapping, wrapper.getName());

    final String webServicecontainerID = wrapper.getName() + WsServlet.WEBSERVICE_CONTAINER + httpListener.hashCode();
    wrapper.addInitParameter(WsServlet.WEBSERVICE_CONTAINER, webServicecontainerID);

    setWsContainer(context, wrapper, httpListener);

    webserviceContexts.put(new Key(path, moduleId), context);

    // register wsdl locations for service-ref resolution
    for (final Connector connector : connectors) {
        final StringBuilder fullContextpath;
        if (!WEBSERVICE_OLDCONTEXT_ACTIVE && !fakeDeployment) {
            String contextPath = context.getPath();
            if (contextPath == null ||  !contextPath.isEmpty()) {
                if (contextPath != null && !contextPath.startsWith("/")) {
                    contextPath = "/" + contextPath;
                } else if (contextPath == null) {
                    contextPath = "/";
                }
            }

            fullContextpath = new StringBuilder(contextPath);
            if (!WEBSERVICE_SUB_CONTEXT.equals("/")) {
                fullContextpath.append(WEBSERVICE_SUB_CONTEXT);
            }
            fullContextpath.append(path);
        } else {
            fullContextpath = new StringBuilder(context.getPath()).append(path);
        }

        try {
            final URI address = new URI(connector.getScheme(), null, host.getName(), connector.getPort(), fullContextpath.toString(), null, null);
            addresses.add(address.toString());
        } catch (final URISyntaxException ignored) {
            // no-op
        }
    }
}
 
Example 12
Source File: TomcatHessianRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public String deploy(final ClassLoader loader, final HessianServer listener,
                     final String hostname, final String app,
                     final String authMethod, final String transportGuarantee,
                     final String realmName, final String name) throws URISyntaxException {
    Container host = engine.findChild(hostname);
    if (host == null) {
        host = engine.findChild(engine.getDefaultHost());
        if (host == null) {
            throw new IllegalArgumentException("Invalid virtual host '" + engine.getDefaultHost() + "'.  Do you have a matchiing Host entry in the server.xml?");
        }
    }

    final String contextRoot = contextName(app);
    Context context = Context.class.cast(host.findChild(contextRoot));
    if (context == null) {
        Pair<Context, Integer> fakeContext = fakeContexts.get(contextRoot);
        if (fakeContext != null) {
            context = fakeContext.getLeft();
            fakeContext.setValue(fakeContext.getValue() + 1);
        } else {
            context = Context.class.cast(host.findChild(contextRoot));
            if (context == null) {
                fakeContext = fakeContexts.get(contextRoot);
                if (fakeContext == null) {
                    context = createNewContext(loader, authMethod, transportGuarantee, realmName, app);
                    fakeContext = new MutablePair<>(context, 1);
                    fakeContexts.put(contextRoot, fakeContext);
                } else {
                    context = fakeContext.getLeft();
                    fakeContext.setValue(fakeContext.getValue() + 1);
                }
            }
        }
    }

    final String servletMapping = generateServletPath(name);

    Wrapper wrapper = Wrapper.class.cast(context.findChild(servletMapping));
    if (wrapper != null) {
        throw new IllegalArgumentException("Servlet " + servletMapping + " in web application context " + context.getName() + " already exists");
    }

    wrapper = context.createWrapper();
    wrapper.setName(HESSIAN.replace("/", "") + "_" + name);
    wrapper.setServlet(new OpenEJBHessianServlet(listener));
    context.addChild(wrapper);
    context.addServletMappingDecoded(servletMapping, wrapper.getName());

    if ("BASIC".equals(authMethod) && StandardContext.class.isInstance(context)) {
        final StandardContext standardContext = StandardContext.class.cast(context);

        boolean found = false;
        for (final Valve v : standardContext.getPipeline().getValves()) {
            if (LimitedBasicValve.class.isInstance(v) || BasicAuthenticator.class.isInstance(v)) {
                found = true;
                break;
            }
        }
        if (!found) {
            standardContext.addValve(new LimitedBasicValve());
        }
    }

    final List<String> addresses = new ArrayList<>();
    for (final Connector connector : connectors) {
        for (final String mapping : wrapper.findMappings()) {
            final URI address = new URI(connector.getScheme(), null, host.getName(), connector.getPort(), contextRoot + mapping, null, null);
            addresses.add(address.toString());
        }
    }
    return HttpUtil.selectSingleAddress(addresses);
}