Mi piacerebbe avere file YAML con un include, simili a questa domanda, ma con Snakeyaml: How can I include an YAML file inside another?Includere file YAML da snakeyaml
Ad esempio:
%YAML 1.2
---
!include "load.yml"
!include "load2.yml"
Sto avendo un sacco di guai con esso. Ho definito il Costruttore e posso farlo importare un documento, ma non due. L'errore che ottengo è:
Exception in thread "main" expected '<document start>', but found Tag
in 'reader', line 5, column 1:
!include "load2.yml"
^
Con un comprendono, Snakeyaml è felice che trova un EOF ed elabora l'importazione. Con due, non è felice (sopra).
La mia fonte è java:
package yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.AbstractConstruct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.Tag;
public class Main {
final static Constructor constructor = new MyConstructor();
private static class ImportConstruct extends AbstractConstruct {
@Override
public Object construct(Node node) {
if (!(node instanceof ScalarNode)) {
throw new IllegalArgumentException("Non-scalar !import: " + node.toString());
}
final ScalarNode scalarNode = (ScalarNode)node;
final String value = scalarNode.getValue();
File file = new File("src/imports/" + value);
if (!file.exists()) {
return null;
}
try {
final InputStream input = new FileInputStream(new File("src/imports/" + value));
final Yaml yaml = new Yaml(constructor);
return yaml.loadAll(input);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
return null;
}
}
private static class MyConstructor extends Constructor {
public MyConstructor() {
yamlConstructors.put(new Tag("!include"), new ImportConstruct());
}
}
public static void main(String[] args) {
try {
final InputStream input = new FileInputStream(new File("src/imports/example.yml"));
final Yaml yaml = new Yaml(constructor);
Object object = yaml.load(input);
System.out.println("Loaded");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
finally {
}
}
}
domanda è, qualcuno ha fatto una cosa simile con Snakeyaml? Qualche idea su cosa potrei fare male?
p.s. grazie per aver postato questa domanda; mi ha dato un vantaggio per il supporto di un tag '! include'. –