如何使用XmlConfiguration为jetty启用https?

时间:2016-05-02 15:05:27

标签: java https jetty jetty-9

我们有一个基于OSGi的服务器,我们使用嵌入式码头处理网络流量 我使用XmlConfiguration创建了一个jetty服务器实例,请参阅下面的代码 configStream来自jetty-http.xml,默认情况下从我们的插件或自定义位置读取。

现在我尝试为服务器启用https。我想加载jetty-ssl.xmljetty-https.xmljetty-http.xml相同。

我该怎么做?我无法将另一个流加载到XmlConfiguration 还有其他方法,可能没有XmlConfiguration吗?

XmlConfiguration xmlConfig = new XmlConfiguration(configStream);
Object root = xmlConfig.configure();
if (!(root instanceof Server)) {
    throw new IllegalArgumentException("expected a Server object as a root for server configuration"); //$NON-NLS-1$
}
server = (Server) root;

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,请参阅下面的代码 XmlConfiguration可用于所有xml文件,如果其中两个创建Server个实例(例如jetty.xmljetty-ssl.xml),则只会创建一个Server个配置/ bean被添加到同一个实例中。

List<String> configurations = new ArrayList<String>();
configurations.add("jetty.xml"); //$NON-NLS-1$

// use pre-configured jetty xml files to construct a server instance
if (System.getProperty("jetty.sslContext.keyStorePath") != null) { //$NON-NLS-1$
    configurations.add("jetty-ssl.xml"); //$NON-NLS-1$
    configurations.add("jetty-ssl-context.xml"); //$NON-NLS-1$
    configurations.add("jetty-https.xml"); //$NON-NLS-1$
} else {
    configurations.add("jetty-http.xml"); //$NON-NLS-1$
}

XmlConfiguration last = null;
List<Object> objects = new ArrayList<Object>();

for (String configFile : configurations) {
    InputStream configStream = null;

    File xmlConfiguration = new File(webserverHome, CONFIG_LOCATION + configFile);
    if (xmlConfiguration.exists()) {
        configStream = new FileInputStream(xmlConfiguration);
        logger.info("Using custom XML configuration {}", xmlConfiguration); //$NON-NLS-1$
    } else {
        // configStream = ... // read from bundle
        logger.info("Using default XML configuration {}/{}", Activator.PLUGIN_ID, CONFIG_LOCATION + configFile); //$NON-NLS-1$
    }

    XmlConfiguration configuration = new XmlConfiguration(configStream);
    if (last != null) {
        configuration.getIdMap().putAll(last.getIdMap());
    }
    objects.add(configuration.configure());
    last = configuration;
}

// first object is a Server instance because of the jetty.xml
server = (Server) objects.get(0);