简体   繁体   English

将Jetty配置从代码更改为XML

[英]Change Jetty configuration from code to XML

I have embedded Jetty into my application. 我已经将Jetty嵌入到我的应用程序中。 My requirements was simple: use HTTP/2, disable some crypto protocols and ciphers, and use my own handler to some requests. 我的要求很简单:使用HTTP / 2,禁用某些加密协议和密码,并对某些请求使用我自己的处理程序。 I did it from my code. 我从我的代码中做到了。 It works very well. 效果很好。 But now I have client who want to use more HTTP features available in Jetty like Basic Authentication, or redirection. 但是现在我有了一些客户端,他们想要使用Jetty中更多的HTTP功能,例如基本身份验证或重定向。 I don't want to add more and more HTTP configuration to my application, so I returned to idea of Jetty XML config file. 我不想向应用程序中添加越来越多的HTTP配置,所以我回到了Jetty XML配置文件的想法。

For debug/monitoring purposes I use Server.dump() and I can see enabled/disabled ciphers, or my handler. 出于调试/监视的目的,我使用Server.dump()并且可以看到启用/禁用的密码或处理程序。 Is it possible to create XML config file based on working Jetty or based on Jetty Server.dump() ? 是否可以基于正在运行的Jetty或基于Jetty Server.dump()创建XML配置文件?

You don't need to change your current code (much) to start using XML to allow modifications of your server. 您无需更改当前代码(无需太多)即可开始使用XML来允许修改服务器。

Consider the XmlEnhancedServer example: 考虑XmlEnhancedServer示例:

Available at https://github.com/jetty-project/embedded-jetty-cookbook 可在https://github.com/jetty-project/embedded-jetty-cookbook获得

package org.eclipse.jetty.cookbook;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.xml.XmlConfiguration;

/**
 * This is a Server setup in a default way, but is can be enhanced by providing
 * (0 to n) Jetty XML file arguments on the command line.
 * <p>
 *     Run without a command line argument and pay attention to the contextPath for the
 *     default Context. (It should be {@code "/"})
 *     <br/>
 *     Now run with {@code src/test/resources/xml-enhanced/adjust-default-contextpath.xml} and see
 *     that the context path is now {@code "/foobar"}
 * </p>
 * <p>
 *     Run with {@code src/test/resources/xml-enhanced/configure-http.xml} and you will be
 *     adjusting the {@link HttpConfiguration} parameters in use.
 * </p>
 * <p>
 *     Run with {@code src/test/resources/xml-enhanced/add-rewrites.xml} and you will be
 *     adjusting adding rewrite rules to the existing handler tree.
 *     <br/>
 *     Request {@code http://localhost:8080/bar/blah} and you will receive a 302 redirect
 *     to {@code http://localhost:8080/foo}
 * </p>
 * <p>
 *     Run with {@code src/test/resources/xml-enhanced/add-https.xml} and you will be
 *     adding an HTTPS connector with configuration.
 * </p>
 */
public class XmlEnhancedServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
        HttpConfiguration httpConfig = new HttpConfiguration();
        ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
        httpConnector.setPort(8080);
        server.addConnector(httpConnector);

        // Figure out what path to serve content from
        ClassLoader cl = DefaultServletFileServer.class.getClassLoader();
        // We look for a file, as ClassLoader.getResource() is not
        // designed to look for directories (we resolve the directory later)
        URL f = cl.getResource("static-root/hello.html");
        if (f == null)
        {
            throw new RuntimeException("Unable to find resource directory");
        }

        // Resolve file to directory
        URI webRootUri = f.toURI().resolve("./").normalize();
        System.err.println("WebRoot is " + webRootUri);

        HandlerList handlers = new HandlerList();
        ContextHandlerCollection contexts = new ContextHandlerCollection();

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(Resource.newResource(webRootUri));
        contexts.addHandler(context);

        ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
        holderPwd.setInitParameter("dirAllowed", "true");
        context.addServlet(holderPwd, "/");

        handlers.addHandler(contexts);
        DefaultHandler defaultHandler = new DefaultHandler();
        handlers.addHandler(defaultHandler); // always last in handler list

        server.setHandler(handlers);

        // apply extra XML (provided on command line)
        if (args.length > 0)
        {
            // Map some well known objects via an id that can be referenced in the XMLs
            Map<String, Object> idMap = new HashMap<>();
            idMap.put("Server", server);
            idMap.put("httpConfig", httpConfig);
            idMap.put("httpConnector", httpConnector);
            idMap.put("Handlers", handlers);
            idMap.put("Contexts", contexts);
            idMap.put("Context", context);
            idMap.put("DefaultHandler", defaultHandler);

            // Map some well known properties
            Map<String,String> globalProps = new HashMap<>();
            URI resourcesUriBase = webRootUri.resolve("..");
            System.err.println("ResourcesUriBase is " + resourcesUriBase);
            globalProps.put("resources.location", resourcesUriBase.toASCIIString());

            List<Object> configuredObjects = new ArrayList<>();
            XmlConfiguration lastConfig = null;
            for (String xml : args)
            {
                URL url = new File(xml).toURI().toURL();
                System.err.println("Applying XML: " + url);
                XmlConfiguration configuration = new XmlConfiguration(url);
                if (lastConfig != null)
                    configuration.getIdMap().putAll(lastConfig.getIdMap());
                configuration.getProperties().putAll(globalProps);
                configuration.getIdMap().putAll(idMap);
                idMap.putAll(configuration.getIdMap());
                configuredObjects.add(configuration.configure());
                lastConfig = configuration;
            }

            // Dump what was configured
            for(Object configuredObject: configuredObjects)
            {
                System.err.printf("Configured (%s)%n", configuredObject.getClass().getName());
            }

            // Dump the resulting idMap
            idMap.forEach((id, obj) -> System.err.printf("IdMap[%s]: (%s)%n", id, obj.getClass().getName()));
        }

        server.setDumpAfterStart(true);
        server.start();
        server.join();
    }
}

This will take an existing Embedded Jetty Server, tag specific components inside and ID Map, along with a few properties, and a user provided list of XML files to configure this server. 这将使用现有的Embedded Jetty服务器,标记内部特定组件和ID映射以及一些属性,以及用户提供的XML文件列表来配置此服务器。

Here's a few of the XML that can be used in this kind of setup. 这是可以在这种设置中使用的一些XML。

adjust-default-contextpath.xml : Adjust-default-contextpath.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
  "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure id="Context" class="org.eclipse.jetty.servlet.ServletContextHandler">
  <Set name="contextPath">/foobar</Set>
</Configure>

configure-http.xml : configure-http.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
  "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
  <Set name="secureScheme">https</Set>
  <Set name="securePort">8443</Set>
  <Set name="outputBufferSize">32768</Set>
  <Set name="requestHeaderSize">8192</Set>
  <Set name="responseHeaderSize">8192</Set>
  <Set name="sendServerVersion">true</Set>
</Configure>

add-rewrites.xml : add-rewrites.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
  "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure id="Server" class="org.eclipse.jetty.server.Server">
  <Call name="insertHandler">
    <Arg>
      <New class="org.eclipse.jetty.rewrite.handler.RewriteHandler">
        <Set name="rewriteRequestURI">true</Set>
        <Set name="rewritePathInfo">false</Set>
        <Set name="originalPathAttribute">requestedPath</Set>

        <Set name="dispatcherTypes">
          <Array type="javax.servlet.DispatcherType">
            <Item>
              <Call class="javax.servlet.DispatcherType" name="valueOf">
                <Arg>REQUEST</Arg>
              </Call>
            </Item>
            <Item>
              <Call class="javax.servlet.DispatcherType" name="valueOf">
                <Arg>ASYNC</Arg>
              </Call>
            </Item>
          </Array>
        </Set>

        <Get name="ruleContainer">
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.RedirectPatternRule">
                <Set name="pattern">/bar/*</Set>
                <Set name="location">/foo</Set>
              </New>
            </Arg>
          </Call>
        </Get>
      </New>
    </Arg>
  </Call>
</Configure>

add-https.xml : add-https.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
  "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure id="Server" class="org.eclipse.jetty.server.Server">

  <New id="sslContextFactory" class="org.eclipse.jetty.util.ssl.SslContextFactory">
    <Set name="KeyStorePath"><Property name="resources.location"/>/ssl/keystore</Set>
    <Set name="KeyStorePassword">OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4</Set>
    <Set name="KeyStoreType">JKS</Set>
    <Set name="KeyManagerPassword">OBF:1u2u1wml1z7s1z7a1wnl1u2g</Set>
    <Set name="TrustStorePath"><Property name="resources.location"/>/ssl/keystore</Set>
    <Set name="RenegotiationAllowed">false</Set>
  </New>

  <New id="sslHttpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
    <Arg><Ref refid="httpConfig"/></Arg>
    <Call name="addCustomizer">
      <Arg>
        <New class="org.eclipse.jetty.server.SecureRequestCustomizer">
          <Arg name="sniHostCheck" type="boolean">true</Arg>
          <Arg name="stsMaxAgeSeconds" type="int">-1</Arg>
          <Arg name="stsIncludeSubdomains" type="boolean">false</Arg>
        </New>
      </Arg>
    </Call>
  </New>

  <Call  name="addConnector">
    <Arg>
      <New id="sslConnector" class="org.eclipse.jetty.server.ServerConnector">
        <Arg name="server"><Ref refid="Server" /></Arg>
        <Arg name="acceptors" type="int">-1</Arg>
        <Arg name="selectors" type="int">-1</Arg>
        <Arg name="factories">
          <Array type="org.eclipse.jetty.server.ConnectionFactory">
            <!-- uncomment to support proxy protocol
            <Item>
              <New class="org.eclipse.jetty.server.ProxyConnectionFactory"/>
            </Item>-->
          </Array>
        </Arg>

        <Set name="port">8443</Set>
        <Set name="idleTimeout">30000</Set>
        <Set name="soLingerTime">-1</Set>
        <Set name="acceptorPriorityDelta">0</Set>
        <Set name="acceptQueueSize">0</Set>
        <Get name="SelectorManager">
          <Set name="connectTimeout">15000</Set>
        </Get>

        <Call name="addIfAbsentConnectionFactory">
          <Arg>
            <New class="org.eclipse.jetty.server.SslConnectionFactory">
              <Arg name="next">http/1.1</Arg>
              <Arg name="sslContextFactory"><Ref refid="sslContextFactory"/></Arg>
            </New>
          </Arg>
        </Call>

        <Call name="addConnectionFactory">
          <Arg>
            <New class="org.eclipse.jetty.server.HttpConnectionFactory">
              <Arg name="config"><Ref refid="sslHttpConfig" /></Arg>
              <Arg name="compliance">
                <Call class="org.eclipse.jetty.http.HttpCompliance" name="valueOf">
                  <Arg>RFC7230</Arg>
                </Call>
              </Arg>
            </New>
          </Arg>
        </Call>
      </New>
    </Arg>
  </Call>
</Configure>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将配置从XML更改为注释 - Change Configuration from XML to annotations 在 tomcat 或 jetty 中部署 mule 应用程序时,如何在 configuration.xml 文件中将 http 端点更改为 servlet 端点? - While deploying mule application in tomcat or jetty , How to change http endpoints to servlet endpoints in configuration.xml file? 如何从代码访问Jetty服务器的XML中指定的配置 - How to access configurations specified in XML of a jetty server from code 通过jetty.xml进行Swagger UI配置 - Swagger UI configuration via jetty.xml 嵌入式Jetty和Jax-rs xml配置 - Embedded Jetty and Jax-rs xml configuration 从 xml 到基于 Java 的配置的问题更改 - Problem change from xml to Java Based Configuration 如何从XML Spring调度配置转向注释/代码配置? - How to go from XML Spring scheduling configuration to annotation/code configuration? MyBatis Spring与Jetty集成,未找到Map Config XML配置 - MyBatis Spring integration with Jetty, Map Config XML configuration not found 没有XML的嵌入式Jetty 8和JNDI MySQL连接池的配置 - Embedded Jetty 8 and configuration of JNDI MySQL connection pool with no XML 告诉Jetty重新加载webapp更改,而不是context.xml更改 - Tell Jetty to reload on webapp change, not context.xml change
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM