下面列出了com.google.common.io.InputSupplier#org.yaml.snakeyaml.introspector.BeanAccess 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Read the yaml content, and return containerData.
*
* @throws IOException
*/
public static ContainerData readContainer(InputStream input)
throws IOException {
ContainerData containerData;
PropertyUtils propertyUtils = new PropertyUtils();
propertyUtils.setBeanAccess(BeanAccess.FIELD);
propertyUtils.setAllowReadOnlyProperties(true);
Representer representer = new ContainerDataRepresenter();
representer.setPropertyUtils(propertyUtils);
Constructor containerDataConstructor = new ContainerDataConstructor();
Yaml yaml = new Yaml(containerDataConstructor, representer);
yaml.setBeanAccess(BeanAccess.FIELD);
containerData = (ContainerData)
yaml.load(input);
return containerData;
}
/**
* Given a ContainerType this method returns a Yaml representation of
* the container properties.
*
* @param containerType type of container
* @return Yamal representation of container properties
*
* @throws StorageContainerException if the type is unrecognized
*/
public static Yaml getYamlForContainerType(ContainerType containerType)
throws StorageContainerException {
PropertyUtils propertyUtils = new PropertyUtils();
propertyUtils.setBeanAccess(BeanAccess.FIELD);
propertyUtils.setAllowReadOnlyProperties(true);
switch (containerType) {
case KeyValueContainer:
Representer representer = new ContainerDataRepresenter();
representer.setPropertyUtils(propertyUtils);
representer.addClassTag(
KeyValueContainerData.class,
KeyValueContainerData.KEYVALUE_YAML_TAG);
Constructor keyValueDataConstructor = new ContainerDataConstructor();
return new Yaml(keyValueDataConstructor, representer);
default:
throw new StorageContainerException("Unrecognized container Type " +
"format " + containerType, ContainerProtos.Result
.UNKNOWN_CONTAINER_TYPE);
}
}
/**
* Create master key file.
*
* @param file file instance
* @param masterKeyConfiguration master key configuration
*/
public static void createMasterKeyFile(File file, MasterKeyConfiguration masterKeyConfiguration) {
try {
file.createNewFile();
file.deleteOnExit();
FileWriter fileWriter = new FileWriter(file);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Representer representer = new Representer();
representer.addClassTag(MasterKeyConfiguration.class, Tag.MAP);
Yaml yaml = new Yaml(representer, options);
yaml.setBeanAccess(BeanAccess.FIELD);
yaml.dump(masterKeyConfiguration, fileWriter);
} catch (IOException e) {
Assert.fail("Failed to create temp password file");
}
}
public static MxisdConfig loadFromFile(String path) throws IOException {
File f = new File(path).getAbsoluteFile();
log.info("Reading config from {}", f.toString());
Representer rep = new Representer();
rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
rep.getPropertyUtils().setAllowReadOnlyProperties(true);
rep.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
try (FileInputStream is = new FileInputStream(f)) {
MxisdConfig raw = yaml.load(is);
log.debug("Read config in memory from {}", path);
// SnakeYaml set objects to null when there is no value set in the config, even a full sub-tree.
// This is problematic for default config values and objects, to avoid NPEs.
// Therefore, we'll use Gson to re-parse the data in a way that avoids us checking the whole config for nulls.
MxisdConfig cfg = GsonUtil.get().fromJson(GsonUtil.get().toJson(raw), MxisdConfig.class);
log.info("Loaded config from {}", path);
return cfg;
} catch (ParserException t) {
throw new ConfigurationException(t.getMessage(), "Could not parse YAML config file - Please check indentation and that the configuration options exist");
}
}
public void testArrayAsMapValue() {
Yaml yaml2dump = new Yaml();
yaml2dump.setBeanAccess(BeanAccess.FIELD);
A data = createA();
String dump = yaml2dump.dump(data);
// System.out.println(dump);
Yaml yaml2load = new Yaml();
yaml2load.setBeanAccess(BeanAccess.FIELD);
A loaded = (A) yaml2load.load(dump);
assertEquals(data.meta.size(), loaded.meta.size());
Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet();
for (Entry<String, String[]> entry : loadedMeta) {
assertTrue(data.meta.containsKey(entry.getKey()));
Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue());
}
}
public void testArrayAsMapValueWithTypeDespriptor() {
Yaml yaml2dump = new Yaml();
yaml2dump.setBeanAccess(BeanAccess.FIELD);
A data = createA();
String dump = yaml2dump.dump(data);
// System.out.println(dump);
TypeDescription aTypeDescr = new TypeDescription(A.class);
aTypeDescr.putMapPropertyType("meta", String.class, String[].class);
Constructor c = new Constructor();
c.addTypeDescription(aTypeDescr);
Yaml yaml2load = new Yaml(c);
yaml2load.setBeanAccess(BeanAccess.FIELD);
A loaded = (A) yaml2load.load(dump);
assertEquals(data.meta.size(), loaded.meta.size());
Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet();
for (Entry<String, String[]> entry : loadedMeta) {
assertTrue(data.meta.containsKey(entry.getKey()));
Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue());
}
}
public void testArrayAsListValueWithTypeDespriptor() {
Yaml yaml2dump = new Yaml();
yaml2dump.setBeanAccess(BeanAccess.FIELD);
B data = createB();
String dump = yaml2dump.dump(data);
// System.out.println(dump);
TypeDescription aTypeDescr = new TypeDescription(B.class);
aTypeDescr.putListPropertyType("meta", String[].class);
Constructor c = new Constructor();
c.addTypeDescription(aTypeDescr);
Yaml yaml2load = new Yaml(c);
yaml2load.setBeanAccess(BeanAccess.FIELD);
B loaded = (B) yaml2load.load(dump);
Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
public void testErrorMessage() throws Exception {
BeanA1 b = new BeanA1();
b.setId(2l);
b.setName("name1");
Constructor c = new Constructor();
Representer r = new Representer();
PropertyUtils pu = new PropertyUtils();
c.setPropertyUtils(pu);
r.setPropertyUtils(pu);
pu.getProperties(BeanA1.class, BeanAccess.FIELD);
Yaml yaml = new Yaml(c, r);
// yaml.setBeanAccess(BeanAccess.FIELD);
String dump = yaml.dump(b);
BeanA1 b2 = (BeanA1) yaml.load(dump);
assertEquals(b.getId(), b2.getId());
assertEquals(b.getName(), b2.getName());
}
public ChronixSparkLoader() {
Representer representer = new Representer();
representer.getPropertyUtils().setSkipMissingProperties(true);
Constructor constructor = new Constructor(YamlConfiguration.class);
TypeDescription typeDescription = new TypeDescription(ChronixYAMLConfiguration.class);
typeDescription.putMapPropertyType("configurations", Object.class, ChronixYAMLConfiguration.IndividualConfiguration.class);
constructor.addTypeDescription(typeDescription);
Yaml yaml = new Yaml(constructor, representer);
yaml.setBeanAccess(BeanAccess.FIELD);
InputStream in = this.getClass().getClassLoader().getResourceAsStream("test_config.yml");
chronixYAMLConfiguration = yaml.loadAs(in, ChronixYAMLConfiguration.class);
}
public static TransportsConfiguration resolveTransportsNSConfiguration(Object transportsConfig)
throws ConfigurationException {
TransportsConfiguration transportsConfiguration;
if (transportsConfig instanceof Map) {
LinkedHashMap httpConfig = ((LinkedHashMap) ((Map) transportsConfig).get("http"));
if (httpConfig != null) {
String configYaml = new Yaml().dump(httpConfig);
Yaml yaml = new Yaml(new CustomClassLoaderConstructor(TransportsConfiguration.class,
TransportsConfiguration.class.getClassLoader()));
yaml.setBeanAccess(BeanAccess.FIELD);
transportsConfiguration = yaml.loadAs(configYaml, TransportsConfiguration.class);
} else {
transportsConfiguration = new TransportsConfiguration();
}
} else {
throw new ConfigurationException("The first level config under 'transports' namespace should be " +
"a map.");
}
return transportsConfiguration;
}
/**
* Initialises YAML Config Manager by parsing the YAML file
*
* @throws YAMLConfigManagerException Exception is thrown if there are issues in processing thr yaml file
*/
private void init(String yamlContent) throws YAMLConfigManagerException {
try {
CustomClassLoaderConstructor constructor = new CustomClassLoaderConstructor(
RootConfiguration.class, RootConfiguration.class.getClassLoader());
PropertyUtils propertyUtils = new PropertyUtils();
propertyUtils.setSkipMissingProperties(true);
constructor.setPropertyUtils(propertyUtils);
Yaml yaml = new Yaml(constructor);
yaml.setBeanAccess(BeanAccess.FIELD);
this.rootConfiguration = yaml.load(yamlContent);
} catch (Exception e) {
throw new YAMLConfigManagerException("Unable to parse YAML string, '" + yamlContent + "'.", e);
}
}
@Override
public Property getProperty(Class<?> type, String name, BeanAccess bAccess) {
if (bAccess != BeanAccess.FIELD) return super.getProperty(type, name, bAccess);
Map<String, Property> properties = getPropertiesMap(type, bAccess);
Property property = properties.get(Helper.toLowerCase(name));
if (property == null) { // Check if property was missing and notify user if necessary
if (type != UnknownConf.class)
core.getLogger().log(WARN, "Unknown configuration property: %s @ %s", name, type.getSimpleName());
return new OutdatedMissingProperty(name);
}
if (!property.isWritable()) // Throw exception from super method
throw new YAMLException("Unable to find writable property '" + name + "' on class: " + type.getName());
return property;
}
OneYaml() {
super(newConstructor(), newRepresenter());
/*
* Use property here as yaml will be read by human and we want to make
* it consistent with presented in UI
*/
setBeanAccess(BeanAccess.PROPERTY);
}
public void save(Writer writer) {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(FlowStyle.AUTO);
options.setIndent(4);
Representer representer = new Representer();
representer.getPropertyUtils().setBeanAccess(BeanAccess.DEFAULT);
new Yaml(options).dump(this, writer);
}
public JavaBeanLoader(LoaderOptions options, BeanAccess beanAccess) {
if (options == null) {
throw new NullPointerException("LoaderOptions must be provided.");
}
if (options.getRootTypeDescription() == null) {
throw new NullPointerException("TypeDescription must be provided.");
}
Constructor constructor = new Constructor(options.getRootTypeDescription());
loader = new Yaml(constructor, options, new Representer(), new DumperOptions(),
new Resolver());
loader.setBeanAccess(beanAccess);
}
@Override
protected Set<Property> createPropertySet(Class<?> type, BeanAccess bAccess) {
if (Federations.class.equals(type)) {
// Serializing on Field order for Federations.
Set<Property> fieldOrderedProperties = new LinkedHashSet<>(getPropertiesMap(type, BeanAccess.FIELD).values());
Set<Property> defaultOrderPropertySet = super.createPropertySet(type, bAccess);
Set<Property> filtered = Sets.difference(fieldOrderedProperties, defaultOrderPropertySet);
fieldOrderedProperties.removeAll(filtered);
return fieldOrderedProperties;
} else {
return super.createPropertySet(type, bAccess);
}
}
@Override
protected Set<Property> createPropertySet(Class<?> type, BeanAccess beanAccess) {
Set<Property> properties = new TreeSet<>();
Collection<Property> props = getPropertiesMap(type, beanAccess).values();
for (Property property : props) {
if (include(property)) {
properties.add(property);
}
}
return properties;
}
@Test
public void createPropertySetWithFieldBeanAccess() throws Exception {
Set<Property> properties = propertyUtils.createPropertySet(TestBean.class, BeanAccess.FIELD);
assertThat(properties.size(), is(2));
Iterator<Property> iterator = properties.iterator();
assertThat(iterator.next().getName(), is(longPropertyName));
assertThat(iterator.next().getName(), is("transientProperty"));
}
@Test
public void allowReadOnlyProperties() throws IntrospectionException {
propertyUtils.setAllowReadOnlyProperties(true);
Set<Property> properties = propertyUtils.createPropertySet(UnwriteableTestBean.class, BeanAccess.DEFAULT);
assertThat(properties.size(), is(1));
assertThat(properties.iterator().next().getName(), is(longPropertyName));
}
private void processSynapseConfig(MxisdConfig cfg) {
String synapseRegFile = cfg.getAppsvc().getRegistration().getSynapse().getFile();
if (StringUtils.isBlank(synapseRegFile)) {
log.info("No synapse registration file path given - skipping generation...");
return;
}
SynapseRegistrationYaml syncCfg = SynapseRegistrationYaml.parse(cfg.getAppsvc(), cfg.getMatrix().getDomain());
Representer rep = new Representer();
rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
Yaml yaml = new Yaml(rep);
// SnakeYAML set the type of object on the first line, which can fail to be parsed on synapse
// We therefore need to split the resulting string, remove the first line, and then write it
List<String> lines = new ArrayList<>(Arrays.asList(yaml.dump(syncCfg).split("\\R+")));
if (StringUtils.equals(lines.get(0), "!!" + SynapseRegistrationYaml.class.getCanonicalName())) {
lines.remove(0);
}
try (FileOutputStream os = new FileOutputStream(synapseRegFile)) {
IOUtils.writeLines(lines, System.lineSeparator(), os, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Unable to write synapse appservice registration file", e);
}
}
public void testYaml() {
Yaml beanLoader = new Yaml();
beanLoader.setBeanAccess(BeanAccess.FIELD);
BlogBean rehydrated = (BlogBean) beanLoader.loadAs(
Util.getLocalResource("issues/issue55_2.txt"), BlogBean.class);
assertEquals(4, rehydrated.getPosts().size());
}
public void testYaml() {
Blog original = createTestBlog();
Yaml yamlDumper = constructYamlDumper();
String serialized = yamlDumper.dumpAsMap(original);
// System.out.println(serialized);
assertEquals(Util.getLocalResource("issues/issue55_1.txt"), serialized);
Yaml blogLoader = new Yaml();
blogLoader.setBeanAccess(BeanAccess.FIELD);
Blog rehydrated = blogLoader.loadAs(serialized, Blog.class);
checkTestBlog(rehydrated);
}
public void testYamlDefaultWithFeildAccess() {
Yaml yaml = new Yaml();
yaml.setBeanAccess(BeanAccess.FIELD);
Blog original = createTestBlog();
String serialized = yaml.dump(original);
assertEquals(Util.getLocalResource("issues/issue55_1_rootTag.txt"), serialized);
Blog rehydrated = (Blog) yaml.load(serialized);
checkTestBlog(rehydrated);
}
public void testYaml() {
Yaml beanLoader = new Yaml();
beanLoader.setBeanAccess(BeanAccess.FIELD);
BlogField rehydrated = beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"),
BlogField.class);
assertEquals(4, rehydrated.getPosts().size());
}
public void testLoad() {
Yaml yaml = new Yaml();
yaml.setBeanAccess(BeanAccess.FIELD);
String doc = Util.getLocalResource("issues/issue73-1.txt");
Blog blog = (Blog) yaml.load(doc);
// System.out.println(blog);
assertEquals("Test Me!", blog.getName());
assertEquals(2, blog.numbers.size());
assertEquals(2, blog.getPosts().size());
for (Post post : blog.getPosts()) {
assertEquals(Post.class, post.getClass());
}
}
public void testYaml() {
String serialized = Util.getLocalResource("issues/issue73-2.txt");
// System.out.println(serialized);
Yaml beanLoader = new Yaml();
beanLoader.setBeanAccess(BeanAccess.FIELD);
Blog rehydrated = beanLoader.loadAs(serialized, Blog.class);
checkTestBlog(rehydrated);
}
private void check(String doc) {
Yaml yamlLoader = new Yaml();
yamlLoader.setBeanAccess(BeanAccess.FIELD);
Blog blog = (Blog) yamlLoader.load(doc);
assertEquals("Test Me!", blog.getName());
assertEquals(2, blog.numbers.size());
assertEquals(2, blog.getPosts().size());
for (Post post : blog.getPosts()) {
assertEquals(Post.class, post.getClass());
}
}
public void testArrayAsListValue() {
Yaml yaml2dump = new Yaml();
yaml2dump.setBeanAccess(BeanAccess.FIELD);
B data = createB();
String dump = yaml2dump.dump(data);
// System.out.println(dump);
Yaml yaml2load = new Yaml();
yaml2load.setBeanAccess(BeanAccess.FIELD);
B loaded = (B) yaml2load.load(dump);
Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
public void testNoTags() {
Yaml yaml2dump = new Yaml();
yaml2dump.setBeanAccess(BeanAccess.FIELD);
B data = createB();
String dump = yaml2dump.dumpAs(data, Tag.MAP, FlowStyle.AUTO);
// System.out.println(dump);
assertEquals("meta:\n- [whatever]\n- [something, something else]\n", dump);
//
Constructor constr = new Constructor(B.class);
Yaml yaml2load = new Yaml(constr);
yaml2load.setBeanAccess(BeanAccess.FIELD);
B loaded = (B) yaml2load.load(dump);
Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
public ConfigSerializer() {
final DumperOptions options = new DumperOptions();
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(new ConfigConstructor(), new ConfigRepresenter(), options);
yaml.setBeanAccess(BeanAccess.FIELD);
}