java - JBoss Wildfly 中使用 EJB 和 JAR 进行 EAR 部署 - 如何从 EJB 项目中加载文件夹中的所有文件或 JAR 中的资源?

标签 java maven ejb wildfly ear

我想从两个不同的部署中加载和处理 json 模式文件,第一个是带有 JAX-RS 端点的 WAR,第二个是带有 Singleton 的 EAR - EJB + 包含架构文件的资源JAR(我读过,只有将资源文件捆绑在 EAR 内的单独 JAR 中时,才能打包在 EJB 中使用的资源文件) .

开发环境是 eclipse 2019-03 和 JBoss Wildfly 16。

使用 JAX-RS 端点进行 WAR 部署

WAR 部分很好,我有一个 @ApplicationScoped Bean,可以通过 ServletContext 访问位于 src/main/webapp/schemas/ 中的模式文件,请参阅以下代码片段:

@ForWarDeployment
@ApplicationScoped
public class JsonSchemaValidatorWar extends JsonSchemaValidatorBase {
...
@PostConstruct
public void init() {
    Consumer<Path> readSchema = schemaFile -> {
        String schemaName = schemaFile.getName(schemaFile.getNameCount() - 1).toString();
        JsonSchema js = jvs.readSchema(schemaFile);
        map.put(schemaName, js); // this is a concurrent hash map in base class
        log.info("Schema " + schemaName + " added: " + js.toJson());
    };
    URI schemaFolder;
    try {
        schemaFolder = servletContext.getResource("/schemas").toURI();
        try (Stream<Path> paths = Files.walk(Paths.get(schemaFolder))) {
            paths.filter(Files::isRegularFile).forEach(readSchema);
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException("Error loading schema files!", e);
    }
}

第一次请求时的输出:

... (default task-1) Schema person.schema.json added: {"$id": ...

使用 EJB 和资源 JAR 进行 EAR 部署

EJB 部分很棘手,我还没有找到读取所有架构文件的解决方案。

我目前拥有的是一个具有以下结构的多模块 Maven 项目:

- parent
- | ear 
- | ejb3
- | resources

父项目的pom.xml

<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>mdv</groupId>
  <artifactId>json-parent</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>json-ejb3</module>
    <module>json-ear</module>
    <module>json-resources</module>
  </modules>

  <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>

ear 项目的 pom.xml

<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>
    <parent>
        <groupId>mdv</groupId>
        <artifactId>json-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>json-ear</artifactId>
    <packaging>ear</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mdv</groupId>
            <artifactId>json-ejb3</artifactId>
            <version>${project.version}</version>
            <type>ejb</type>
        </dependency>
        <dependency>
            <groupId>mdv</groupId>
            <artifactId>json-resources</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <version>7</version>
                    <defaultLibBundleDir>lib</defaultLibBundleDir>
                    <earSourceDirectory>${basedir}/src/main/resources</earSourceDirectory>
                    <outputFileNameMapping>@{artifactId}@@{dashClassifier?}@.@{extension}@</outputFileNameMapping>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

资源项目的pom.xml

<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>
    <parent>
        <groupId>mdv</groupId>
        <artifactId>json-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>json-resources</artifactId>
</project>

ejb3 项目的 pom.xml

<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>
    <parent>
        <groupId>mdv</groupId>
        <artifactId>json-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>json-ejb3</artifactId>
    <packaging>ejb</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-ejb-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <ejbVersion>3.2</ejbVersion>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
        <!-- contains a json schema processing library and the class JsonSchemaValidatorEjb -->
            <groupId>mdv</groupId>
            <artifactId>json</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

在EJB中加载模式文件的问题

我想在 @ApplicationScoped bean 中加载架构文件以在 Singleton EJB 中使用,对应的类是 JsonSchemaValidatorService:

package mdv;

import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;

import json.ForEjbDeployment;
import json.IJsonSchemaValidator;

@Singleton
@Startup
public class JsonSchemaValidatorService {

    Logger log = Logger.getLogger("JsonSchemaValidatorService");

    @Inject
    @ForEjbDeployment
    IJsonSchemaValidator jsonSchemaValidator;
    // this is where json schema files should be loaded

    public JsonSchemaValidatorService() {
        //
    }

    @PostConstruct
    public void init() {
        log.info("Started JsonSchemaValidatorService.");
        log.info("Loaded schemas in jsonSchemaValidator: " + jsonSchemaValidator.getLoadedSchemas());
    }

}

在EJB环境中加载json模式文件的类是这个bean:

package json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.function.Consumer;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.resource.spi.IllegalStateException;

import org.leadpony.justify.api.JsonSchema;

@ForEjbDeployment
@ApplicationScoped
public class JsonSchemaValidatorEjb extends JsonSchemaValidatorBase {

    Logger log = Logger.getLogger("JsonSchemaValidator");

    public JsonSchemaValidatorEjb() {
        //
    }

    @PostConstruct
    public void init() {
        try {
            // This is where I can't manage to get a list of the json schema files and process them
            final ClassLoader loader = Thread.currentThread().getContextClassLoader();
            try(
                    final InputStream is = loader.getResourceAsStream("schemas");
                    final InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                    final BufferedReader br = new BufferedReader(isr)) {
                log.info("schema files in directory: ");
                br.lines().forEach(x -> log.info(x));
            }
        } catch (Exception e) {
            throw new RuntimeException("Error trying to parse schema files!", e);
        }
    }
}

没有抛出异常,但在提供的目录中也找不到文件,例如“模式”。 EJB启动后的缩短输出为:

[JsonSchemaValidatorService] Started JsonSchemaValidatorService.
[JsonSchemaValidator] schema files in directory: 
[JsonSchemaValidatorService] Loaded schemas in jsonSchemaValidator: {}

部署的ear的文件结构是这样的:

- lib
| - icu4j.jar
| - javax.json-api.jar
| - javax.json.jar
| - json-resources.jar // jar with resources, in this case the schemas
| | - schemas
| | | - person.schema.json
| - json.jar // jar containing @ApplicationScoped beans for war und ejb
| - justify.jar // json schema processing library used
- META-INF
| - maven
| | ...
| - schemas
| | - person.schema.json
| - application.xml
| - MANIFEST.MF
- schemas
| -person.schema.json
- json-ejb3.jar

如您所见,我已成功将 schemas 文件夹和单个 json 架构文件捆绑到多个位置,但这些都不起作用。

这有可能实现吗? 我在 getResourceAsStream("schemas") 中指定的路径是否有误?

目标是在启动时加载所有现有的 json 架构文件,将它们解析为 JsonSchema 对象一次,以便稍后验证它们(顺便说一下,它将是一个消息驱动的 bean)。

最佳答案

最后我找到了一个很好的解决方案,它可以在 Servlet 和 EJB 上下文中工作,并且无需区分它们。

由于我无法从 EJB 中列出 schemas 文件夹内的文件,但可以访问和读取单个文件,所以我想到了使用在构建时自动生成的包含所有 JSON 列表的文件架构文件并使用它来处理架构

将 EJB 移至 WAR 部署

首先,我遵循 @IllyaKysil 的建议,将我的 EJB 从 EAR 部署移动到已经存在且正在运行的 WAR 部署

将架构文件移至 JAR

原始方法在 WAR 和 EAR 部署中都有 JSON 架构文件。我现在在 JAR 项目的 src/main/resources/schemas 文件夹中拥有这些文件,我在 WAR 项目中对它有 Maven 依赖。归档结果结构为:

| jee7-test.war
| - WEB-INF
| | - lib
| | | - json-validator-0.0.1-SNAPSHOT.jar
| | | | - schemas
| | | | | - person.schema.json
| | | | | - schemaList.txt

在构建时生成 schemaList.txt

使用 maven antrun 插件,在 src/main/resources/schemas 中创建一个文件,其中 schemas 目录中的每个文件的扩展名为 .schema.json单独一行:

<plugin>
   <artifactId>maven-antrun-plugin</artifactId>
   <version>1.8</version>
   <executions>
      <execution>
         <phase>generate-sources</phase>
         <configuration>
            <target>
               <fileset id="schemaFiles"
                  dir="src/main/resources/schemas/" includes="*.schema.json" />
               <pathconvert pathsep="${line.separator}"
                  property="schemaFileList" refid="schemaFiles">
                  <map from="${basedir}\src\main\resources\schemas\" to="" />
               </pathconvert>
               <echo
               file="${basedir}\src\main\resources\schemas\schemaList.txt">${schemaFileList}</echo>
            </target>
         </configuration>
         <goals>
            <goal>run</goal>
         </goals>
      </execution>
   </executions>
</plugin>

生成的文件内容为:

person.schema.json

读取 schemaList.txt 并解析 schema

最后一步是读取包含 JSON 架构文件列表的文件,并处理每一行以解析相应的架构文件:

@ApplicationScoped
public class JsonSchemaValidator implements IJsonSchemaValidator {

    protected JsonValidationService jvs = JsonValidationService.newInstance();
    protected ConcurrentHashMap<String, JsonSchema> schemaMap = new ConcurrentHashMap<String, JsonSchema>();
    private Logger log = Logger.getLogger("JsonSchemaValidator");

    public JsonSchemaValidator() {
        //
    }

    private String SCHEMA_FOLDER = "schemas/";
    private String SCHEMA_LIST_FILE = "schemaList.txt";

    @PostConstruct
    public void init() {
        try {
            final ClassLoader loader = Thread.currentThread().getContextClassLoader();
            // load file containing list of JSON schema files
            try (final InputStream is = loader.getResourceAsStream(SCHEMA_FOLDER + SCHEMA_LIST_FILE);
                    final InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                    final BufferedReader br = new BufferedReader(isr)) {
                // each line is a name of a JSON schema file that has to be processed
                br.lines().forEach(line -> readSchema(line, loader));
            }
            log.info("Number of JsonSchema objects in schemaMap: " + schemaMap.size());
            log.info("Keys in schemaMap: ");
            schemaMap.forEachKey(1L, key -> log.info(key));
        } catch (Exception e) {
            throw new RuntimeException("Error trying to parse schema files!", e);
        }
    }

    private void readSchema(String schemaFileName, ClassLoader classLoader) {
        // only use part of the file name to first dot, which leaves me with "person"
        // for "person.schema.json" file name
        String schemaName = schemaFileName.substring(0, schemaFileName.indexOf("."));
        JsonSchema js = jvs.readSchema(classLoader.getResourceAsStream(SCHEMA_FOLDER + schemaFileName));
        // put JsonSchema object in map with schema name as key
        schemaMap.put(schemaName, js);
        log.info("Schema " + schemaName + " added: " + js.toJson());
    }

    @Override
    public List<Problem> validate(String json, String schemaName) {
        List<Problem> result = new ArrayList<Problem>();
        JsonSchema jsonSchema = schemaMap.get(schemaName);
        JsonReader reader = jvs.createReader(new StringReader(json), jsonSchema, ProblemHandler.collectingTo(result));
        reader.read();

        return result;
    }

    @Override
    public Map<String, JsonSchema> getLoadedSchemas() {
        return Collections.unmodifiableMap(schemaMap);
    }
}

结果

现在可以根据 JSON 模式验证输入的 JSON 字符串,而无需一遍又一遍地解析模式

@Inject
IJsonSchemaValidator jsv;
...
List<Problem> problems = jsv.validate(inputJson, "person");

创建 JsonSchemaValidator 实例后记录的输出:

Schema person added: {"$id":"....}
Number of JsonSchema objects in schemaMap: 1
Keys in schemaMap: 
person

关于java - JBoss Wildfly 中使用 EJB 和 JAR 进行 EAR 部署 - 如何从 EJB 项目中加载文件夹中的所有文件或 JAR 中的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528536/

相关文章:

java - 当我可以实现完整的类时,为什么还需要接口(interface)?

java - 数组的 equal 方法如何工作?

Maven Checkstyle configLocation 被忽略?

java - EJB 事务回滚后自动重试

java - 无需 Hibernate 映射即可获取类数据

java - 为什么java ClassLoader中没有unloadClass(String name)方法

java - Spring Boot可执行jar无法访问索引页

java - 在同一个 Maven 项目中创建和使用 Web 服务

java - 具有自定义 SSLSocketFactory 的 T3 客户端

java - EJB、Java JPA、mysql。异常(exception)