特定の形式のファイルを読み取る OSGi でサービスを構築しようとしています。
サービス インターフェイスは次のようになります。
public interface FileReaderService {
/**
* Reads the given file.
* @param filePath Path of the file to read
* @return the data object built from the file
* @throws IOException if there is an error while reading the file
*/
Data readFile(Path filePath) throws IOException;
/**
* Detects if the format of the provided file is supported.
* @param filePath the file to check
* @return true if the format of the file is supported, false otherwise
* @throws IOException if there is an error while reading the file
*/
boolean isFormatSupported(Path filePath) throws IOException;
}
Data オブジェクトは、読み取るファイルのデータ構造を定義するクラスです (同じ種類のデータが含まれているはずです)。
アイデアは、次のようなさまざまなサービスの実装を持つことです。
public class TxtFileReader implements FileReaderService {
@Override
public Data readFile(Path filePath) throws IOException {
// Do something smart with the file
return data;
}
}
@Override
public boolean isFormatSupported(Path filePath) throws IOException {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.txt");
return matcher.matches(filePath);
}
}
XmlFileReader、MdFileReader など、他の実装もある可能性があります。
最後に、次のような FileReaderFactory が必要です。
@Component
public class FileReaderFactory implements FileReaderService {
private List<FileReaderService> availableServices = new ArrayList<>();
@Override
public Data readFile(Path filePath) throws IOException {
for (FileReaderService reader : availableServices) {
if (reader.isFormatSupported(filePath)) {
return reader.readFile(filePath);
}
}
return null;
}
@Override
public boolean isFormatSupported(Path filePath) throws IOException {
for (FileReaderService reader : availableServices) {
if (reader.isFormatSupported(filePath)) {
return true;
}
}
return false;
}
}
私が望むのは、DS が FileReaderServices をファクトリ リストに動的に挿入することです。提供されるサービスの数に応じて、特定のファイル形式をサポートする (またはサポートしない) ことになります。
したがって、私の質問は次のとおりです。
1) これは DS で実行可能ですか?
2) はいの場合、DS 注釈を使用してそれを行うにはどうすればよいですか?
3) そうでない場合、どのようにしますか?
ありがとう
編集:クリスチャンの解決策を試しましたが、うまくいきませんでした(まだ)。完全なコードは、 https ://github.com/neopium/FileReader からダウンロードできます。