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

时间:2019-06-10 14:40:26

标签: java maven ejb wildfly ear

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

JBoss Wildfly 16的开发环境将在2019-03年蚀过。

使用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);
    }
}

第一个请求的输出:

  

...(默认任务1)已添加架构person.schema.json:{“ $ 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>

用于耳朵项目的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: {}

部署的耳朵的文件结构是这样的:

- 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)。

2 个答案:

答案 0 :(得分:1)

最后,我找到了一个不错的解决方案,该解决方案在Servlet和EJB上下文中都可以使用,并且不需要区分它们。

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

将EJB迁移到WAR部署

首先,我遵循@IllyaKysil的建议,将EJB从EAR部署迁移到已经存在且可以正常使用的WAR部署

将架构文件移动到JAR

原始方法在WAR和EAR部署中都具有JSON模式文件。现在,我将文件保存在JAR项目的src/main/resources/schemas文件夹中,而我在WAR项目中对此有一定的依赖性。存档的结果结构为:

| 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并解析架构

最后一步是读取包含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

答案 1 :(得分:0)

How to list the files inside a JAR file?中回答了遍历模式的方法。

鉴于此,这些资源没有理由不能与EJB位于同一jar中。如果您需要从EAR中的其他jar或WAR访问它们,则仅需要将它们放在EAR / lib目录中的单独jar中。

除非您正在做一些时髦的事情,否则您不必担心jboss-deployment-structure.xml

此外,您无法从EAR本身内部读取资源,例如ear/META-INF/schemas。这算是时髦,您仍然需要上面指出的解决方案进行迭代。