построить источник данных postgresql в рое диких мух

Я хочу использовать postgresql в wildfly-swarm через объявление источника данных. Моя проблема заключается в сообщении об ошибке NamingNotFoundException. Поиск из InitialContext выдает эту ошибку.

Мой проект-defaults.yml (в папке src/main/resources/project-defaults.yml):

 swarm:
  datasources:
    data-sources:
        ExampleDS:
          driver-name: pgsql
          connection-url: jdbc:postgresql://testdb
          user-name: sa
          password: sa
          jta: true
          use-java-context: true
          min-pool-size: 8
    jdbc-drivers:
      pgsql:
        driver-class-name: org.postgresql.Driver
        xa-datasource-class-name: org.postgresql.xa.PGXADataSource
        driver-module-name: org.postgresql

Мой класс для работы с источниками данных:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.postgresql.Driver;

@Path("helloworld")
public class HelloWorldEndpoint
{
    private final String str_db_source = "java:jboss/datasources/ExampleDS";

    @GET
    public String sayHello()
    {
        String str_ret = "hello Dockerworld from swarm";
        try
        {
            System.out.println("Starte DB Insert");
            dowork();
        }
        catch (SQLException ex) {        Logger.getLogger(HelloWorldEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }  
        return str_ret;
    }

    private void dowork() throws SQLException
    {
        try
        {
            Class.forName("org.postgresql.Driver");
        }
        catch (ClassNotFoundException ex)
        {
 Logger.getLogger(HelloWorldEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
        InitialContext ctx_PrgSql = null;
        java.sql.Connection pcon = null;
        try
        {
            ctx_PrgSql = new InitialContext();
            DataSource ds_PrgSql = (DataSource) ctx_PrgSql.lookup(java:jboss/datasources/ExampleDS);
            if (ds_PrgSql == null)
            {            Logger.getLogger(HelloWorldEndpoint.class.getName()).log(Level.SEVERE, "Keine Datasource");
            }
            pcon = ds_PrgSql.getConnection();
            PreparedStatement pgps;
            //sql insert + params
            pgps.execute();
            pgps.close();
        }
        catch (NamingException ex)
        {               Logger.getLogger(HelloWorldEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            this.close_Context(ctx_PrgSql);
            this.close_Connection(pcon);
        }
        System.out.println("DB Insert beendet");
    }

    /**
     * schließt Context
     *
     * @param ctx_obj
     */
    private void close_Context(Context ctx_obj)
    {
        try
        {
            if (ctx_obj != null)
            {
                ctx_obj.close();
            }
        }
        catch (NamingException ex)
        {          Logger.getLogger(HelloWorldEndpoint.class.getName()).log(Level.WARNING, null, ex);
        }
    }

    /**
     * schließt Connection
     *
     * @param con_obj
     */
    private void close_Connection(Connection con_obj)
    {
        try
        {
            if (con_obj != null)
            {
                con_obj.close();
            }
        }
        catch (SQLException ex)
        {                Logger.getLogger(HelloWorldEndpoint.class.getName()).log(Level.WARNING, null, ex);
        }
    }
}

и мой pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test.wildfly-swarm-docker</groupId>
    <artifactId>dock-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <version.wildfly.swarm>1.0.0.Final</version.wildfly.swarm>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.postgresql>42.2.2</version.postgresql>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.wildfly.swarm</groupId>
                <artifactId>bom</artifactId>
                <version>${version.wildfly.swarm}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>helloworld</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>project-default.yml</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.wildfly.swarm</groupId>
                <artifactId>wildfly-swarm-plugin</artifactId>
                <version>${version.wildfly.swarm}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.wildfly.swarm</groupId>
            <artifactId>undertow</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wildfly.swarm</groupId>
            <artifactId>jaxrs</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wildfly.swarm</groupId>
            <artifactId>datasources</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>${version.postgresql}</version>
        </dependency>
    </dependencies>


</project>

Я работаю с документацией из http://docs.wildfly-swarm.io/2018.4.1/

все сообщение об ошибке:

2018-04-17 10:46:51,263 SEVERE [HelloWorldEndpoint] (default task-1) null: javax.naming.NameNotFoundException: datasources/ExampleDS -- service jboss.naming.context.java.jboss.datasources.ExampleDS
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:106)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:207)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:184)
at org.jboss.as.naming.InitialContext$DefaultInitialContext.lookup(InitialContext.java:237)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:193)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:189)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at HelloWorldEndpoint.dowork(HelloWorldEndpoint.java:62)
at HelloWorldEndpoint.sayHello(HelloWorldEndpoint.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:139)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:295)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:249)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:236)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:395)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:202)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.swarm.generated.FaviconErrorHandler.handleRequest(FaviconErrorHandler.java:62)
at io.undertow.server.handlers.PathHandler.handleRequest(PathHandler.java:94)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

person Andreas    schedule 17.04.2018    source источник


Ответы (1)


Если вы добавите зависимость Maven к драйверу JDBC PostgreSQL (что вы и сделаете), WildFly Swarm автоматически определит драйвер JDBC, поэтому вам не нужно делать это вручную. Имя драйвера будет postgresql, как вы можете найти здесь: http://docs.wildfly-swarm.io/2018.4.1/#_autodetectable_drivers

Затем, чтобы объявить источник данных, этого вполне достаточно (скопируйте с http://docs.wildfly-swarm.io/2018.4.1/#_example_datasource_definitions):

swarm:
  datasources:
    data-sources:
      MyDS:
        driver-name: postgresql
        connection-url: jdbc:postgresql://localhost:5432/postgresdb
        user-name: admin
        password: admin
        valid-connection-checker-class-name: org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker
        validate-on-match: true
        background-validation: false
        exception-sorter-class-name: org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter

Я знаю, что это работает, и это проще, чем то, что вы делаете. Но то, что вы делаете, тоже должно работать, поэтому не могли бы вы вставить все сообщение об ошибке, которое вы видите?

person Ladicek    schedule 17.04.2018
comment
Благодаря переименованию вышеуказанные URL-адреса больше не работают. Теперь docs.thorntail.io/2018.4.1/#_autodetectable_drivers и docs.thorntail.io/2018.4.1/#_example_datasource_definitions - person ofrommel; 22.01.2019