2016-03-02 2 views
0

Я пытался настроить встроенный сервер причала (Jetty версии 9.3.7) и имел некоторые трудности с файлом jetty-env.Embedded Jetty с файлом env файл не работает

Мое приложение успешно развернуто на нескольких серверах, поэтому я знаю, что проблема должна быть связана с конфигурацией пристани.

Я рассмотрел this question и основывал свою текущую реализацию на ответе, но он не работает.

У меня есть следующий src/main/resources/WEB-INF/jetty-env.xml файл:

<?xml version="1.0" encoding="UTF-8"?> 
<Configure class="org.eclipse.jetty.webapp.WebAppContext"> 
    <New id="datasource" class="org.eclipse.jetty.plus.jndi.Resource"> 
    <Arg>jdbc/datasource</Arg> 
    <Arg> 
     <New class="org.apache.commons.dbcp.BasicDataSource"> 
     <Set name="url">jdbc:h2:tcp://localhost:9092/build/db/testdb;USER=sa</Set> 
     </New> 
    </Arg> 
    </New> 
</Configure> 

У меня также есть src/main/resources/WEB-INF/web.xml файла, который содержит следующий сегмент:

<resource-ref> 
    <description>TESTDB</description> 
    <res-ref-name>jdbc/datasource</res-ref-name> 
    <res-type>javax.sql.DataSource</res-type> 
    <res-auth>Container</res-auth> 
    <res-sharing-scope>Shareable</res-sharing-scope> 
</resource-ref> 

Я могу использовать причал плагин Gradle, чтобы начать Jetty Server, и поэтому знайте, что эта конфигурация действительна.

Ниже класс, который я пытаюсь использовать для создания причала сервера:

public class JettyServer { 

    private static final Logger LOGGER = LoggerFactory.getLogger(JettyServer.class); 

    public static void main(final String[] args) throws Exception { 
     LOGGER.debug("Starting jetty server"); 
     int port = 8083; 
     LOGGER.debug("Setting the port to {}", port); 
     final Server server = new Server(port); 
     Configuration.ClassList classList = Configuration.ClassList.serverDefault(server); 
     classList.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", 
      "org.eclipse.jetty.plus.webapp.PlusConfiguration"); 
     final WebAppContext root = new WebAppContext(); 
     root.setContextPath("/"); 
     root.setResourceBase("."); 
     root.setDescriptor(JettyServer.class.getResource("/WEB-INF/web.xml").toString()); 
     server.setHandler(root); 
     server.start(); 
     server.join(); 
    } 
} 

Имя JNDI упоминается в классе весной конфигурации Java:

@Bean 
public DataSource dataSource() throws NamingException { 
    final JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean(); 
    jndiObjectFactoryBean.setJndiName("java:comp/env/jdbc/datasource"); 
    jndiObjectFactoryBean.setResourceRef(true); 
    jndiObjectFactoryBean.setProxyInterface(DataSource.class); 
    jndiObjectFactoryBean.afterPropertiesSet(); 
    return (DataSource)jndiObjectFactoryBean.getObject(); 
} 

Когда я пытаюсь начните мою заявку, я получаю следующую ошибку:

Caused by: javax.naming.NameNotFoundException: null 
at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:532) ~[jetty-jndi-9.3.7.v20160115.jar:9.3.7.v20160115] 
at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:563) ~[jetty-jndi-9.3.7.v20160115.jar:9.3.7.v20160115] 
at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:578) ~[jetty-jndi-9.3.7.v20160115.jar:9.3.7.v20160115] 
at org.eclipse.jetty.jndi.java.javaRootURLContext.lookup(javaRootURLContext.java:106) ~[jetty-jndi-9.3.7.v20160115.jar:9.3.7.v20160115] 
at javax.naming.InitialContext.lookup(InitialContext.java:417) ~[na:1.8.0_73] 
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiObjectTargetSource.afterPropertiesSet(JndiObjectTargetSource.java:97) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiObjectFactoryBean$JndiObjectProxyFactory.createJndiObjectProxy(JndiObjectFactoryBean.java:315) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiObjectFactoryBean$JndiObjectProxyFactory.access$000(JndiObjectFactoryBean.java:304) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:200) ~[spring-context-3.2.13.RELEASE.jar:3.2.13.RELEASE] 

Как я уже сказал, если я использую ту же конфигурацию, что и s из-за того, что у меня нет проблем, и я получаю сервер, поэтому я предполагаю, что проблема должна относиться к моему классу JettyServer, но я не могу найти что-либо в сети, чтобы указать, что я делаю неправильно.

Может ли кто-нибудь заметить что-нибудь очевидное?

ответ

0

В конце я взглянул на исходный код для gradle jetty plugin и заметил, что они добавляли конфигурации немного по-другому. Это работает для меня, и мой сервер теперь работает, как ожидалось:

public class JettyServer { 

    private static final Logger LOGGER = LoggerFactory.getLogger(JettyServer.class); 

    public static void main(final String[] args) throws Exception { 
     LOGGER.debug("Starting jetty server"); 
     int port = 8083; 
     LOGGER.debug("Setting the port to {}", port); 
     final Server server = new Server(port); 
     final WebAppContext root = new WebAppContext(); 
     root.setContextPath("/"); 
     root.setResourceBase("."); 
     EnvConfiguration envConfiguration = new EnvConfiguration(); 
     envConfiguration.setJettyEnvXml(JettyServer.class.getResource("/WEB-INF/jetty-env.xml").toURI().toURL()); 
     //Adding the actual classes instead of just the class names 
     root.setConfigurations(new Configuration[]{envConfiguration, new PlusConfiguration(), new WebXmlConfiguration()}); 
     root.setDescriptor(JettyServer.class.getResource("/WEB-INF/web.xml").toString()); 
     server.setHandler(root); 
     server.start(); 
     server.join(); 
    } 
} 

Я предполагаю, что я должен быть мой проект создан немного неправильно, что означает, что конфигурации по умолчанию не работают. Я не буду принимать этот ответ на данный момент, если кто-то скажет мне другие альтернативы.

Смежные вопросы