org.yaml.snakeyaml.introspector.Property Java Examples

The following examples show how to use org.yaml.snakeyaml.introspector.Property. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException
{
	if (type.equals(Ruby.class) || type.equals(KCode.class) || type.equals(RubyProc.class))
	{
		return Collections.emptySet();
	}
	Set<Property> set = super.getProperties(type);
	if (CommandElement.class.isAssignableFrom(type) || type.equals(EnvironmentElement.class))
	{
		// drop runtime, invoke, and invoke block properties
		Set<Property> toRemove = new HashSet<Property>();
		for (Property prop : set)
		{
			if ("invokeBlock".equals(prop.getName()) || "runtime".equals(prop.getName()) //$NON-NLS-1$ //$NON-NLS-2$
					|| "invoke".equals(prop.getName())) //$NON-NLS-1$
			{
				toRemove.add(prop);
			}
		}

		set.removeAll(toRemove);
	}
	return set;
}
 
Example #2
Source File: SkipEmptyRepresenter.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("RedundantIfStatement")
private boolean isInvalidType(Property property, Object propertyValue) {
    if (propertyValue == null) {
        return true;
    }
    if (propertyValue instanceof List && ((List) propertyValue).isEmpty()) {
        return true;
    }
    if (propertyValue instanceof Map && ((Map) propertyValue).isEmpty()) {
        return true;
    }
    if (propertyValue instanceof Boolean && !((Boolean) propertyValue) && !Objects.equals(property.getName(), "failed")) {
        return true;
    }
    return false;
}
 
Example #3
Source File: ContainerDataYaml.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
protected Set<Property> getProperties(Class<? extends Object> type)
    throws IntrospectionException {
  Set<Property> set = super.getProperties(type);
  Set<Property> filtered = new TreeSet<Property>();

  // When a new Container type is added, we need to add what fields need
  // to be filtered here
  if (type.equals(KeyValueContainerData.class)) {
    List<String> yamlFields = KeyValueContainerData.getYamlFields();
    // filter properties
    for (Property prop : set) {
      String name = prop.getName();
      if (yamlFields.contains(name)) {
        filtered.add(prop);
      }
    }
  }
  return filtered;
}
 
Example #4
Source File: OutdatedConfigurationPropertyUtils.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: ConfigurationRepresenter.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
@Override // Skip null values for configuration generating
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object value, Tag customTag) {
    if (value != null) {
        NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, value, customTag);
        Node valueNode = tuple.getValueNode();

        // Avoid using tags for enums
        if (customTag == null && valueNode.getNodeId() == NodeId.scalar && value instanceof Enum<?>) {
            valueNode.setTag(Tag.STR);
        }

        return tuple;
    } else {
        return null;
    }
}
 
Example #6
Source File: CompactConstructor.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Provide the name of the property which is used when the entries form a
 * sequence. The property must be a List.
 * 
 * @throws IntrospectionException
 */
protected String getSequencePropertyName(Class<?> bean) throws IntrospectionException {
    Set<Property> properties = getPropertyUtils().getProperties(bean);
    for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) {
        Property property = iterator.next();
        if (!List.class.isAssignableFrom(property.getType())) {
            iterator.remove();
        }
    }
    if (properties.size() == 0) {
        throw new YAMLException("No list property found in " + bean);
    } else if (properties.size() > 1) {
        throw new YAMLException(
                "Many list properties found in "
                        + bean
                        + "; Please override getSequencePropertyName() to specify which property to use.");
    }
    return properties.iterator().next().getName();
}
 
Example #7
Source File: YamlRepresenter.java    From multiapps with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
    if (ObjectUtils.isEmpty(propertyValue)) {
        return null;
    }
    Field field = getField(javaBean.getClass(), property.getName());
    String nodeName = field.isAnnotationPresent(YamlElement.class) ? field.getAnnotation(YamlElement.class)
                                                                          .value()
        : property.getName();

    if (field.isAnnotationPresent(YamlAdapter.class)) {
        return getAdaptedTuple(propertyValue, field, nodeName);
    }

    NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
    return new NodeTuple(representData(nodeName), defaultNode.getValueNode());
}
 
Example #8
Source File: AdvancedRepresenterTest.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
@Test
public void notNullMapProperty() {
  bean.setMapProperty(ImmutableMap.<String, Long>builder().put("first", 1L).put("second", 2L).build());
  Property property = new MethodProperty(getPropertyDescriptor("mapProperty"));
  NodeTuple nodeTuple = representer.representJavaBeanProperty(bean, property, bean.getMapProperty(), null);
  assertThat(nodeTuple, is(notNullValue()));
  assertThat(nodeTuple.getKeyNode(), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) nodeTuple.getKeyNode()).getValue(), is("map-property"));
  assertThat(nodeTuple.getValueNode(), is(instanceOf(MappingNode.class)));
  assertThat(((MappingNode) nodeTuple.getValueNode()).getValue().size(), is(2));
  assertThat(((MappingNode) nodeTuple.getValueNode()).getValue().get(0), is(instanceOf(NodeTuple.class)));
  assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(0).getKeyNode()).getValue(),
      is("first"));
  assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(0).getValueNode()).getValue(),
      is("1"));
  assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(1).getKeyNode()).getValue(),
      is("second"));
  assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(1).getValueNode()).getValue(),
      is("2"));
}
 
Example #9
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
protected String getSequencePropertyName(Class<?> bean) {
    Set<Property> properties = getPropertyUtils().getProperties(bean);
    for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) {
        Property property = iterator.next();
        if (!List.class.isAssignableFrom(property.getType())) {
            iterator.remove();
        }
    }
    if (properties.size() == 0) {
        throw new YAMLException("No list property found in " + bean);
    } else if (properties.size() > 1) {
        throw new YAMLException(
                "Many list properties found in "
                        + bean
                        + "; Please override getSequencePropertyName() to specify which property to use.");
    }
    return properties.iterator().next().getName();
}
 
Example #10
Source File: PropertyManager.java    From jesterj with Apache License 2.0 6 votes vote down vote up
@Override
protected Set<Property> getProperties(Class<?> type) throws IntrospectionException {
  Set<Property> set = super.getProperties(type);
  Set<Property> filtered = new TreeSet<>();

  BeanInfo beanInfo = Introspector.getBeanInfo(type);
  PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  Map<String, PropertyDescriptor> propMap = Arrays.asList(propertyDescriptors).stream().collect(Collectors.toMap(PropertyDescriptor::getName, Function.identity()));
  for (Property prop : set) {
    PropertyDescriptor pd = propMap.get(prop.getName());
    if (pd != null) {
      Method readMethod = pd.getReadMethod();
      AUTIL.runIfMethodAnnotated(readMethod, () -> filtered.add(prop), false, Transient.class);
    }
  }
  return filtered;
}
 
Example #11
Source File: YamlTranslator.java    From mdw with Apache License 2.0 6 votes vote down vote up
protected Representer getRepresenter() {
    return new Representer() {
        @Override
        protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException {
            Set<Property> props = super.getProperties(type);
            Property toRemove = null;
            for (Property prop : props) {
                if (prop.getName().equals("metaClass")) {
                    toRemove = prop;
                    break;
                }
            }
            if (toRemove != null)
                props.remove(toRemove);
            return props;
        }
    };
}
 
Example #12
Source File: YamlPropertyRepresenter.java    From karamel with Apache License 2.0 6 votes vote down vote up
@Override
protected Set<Property> getProperties(Class<? extends Object> type)
        throws IntrospectionException {
  List<String> order = null;
  if (type.isAssignableFrom(YamlCluster.class)) {
    order = CLUSTER_ORDER;
  } else if (type.isAssignableFrom(YamlGroup.class)) {
    order = GROUP_ORDER;
  }
  if (order != null) {
    Set<Property> standard = super.getProperties(type);
    Set<Property> sorted = new TreeSet<>(new PropertyComparator(order));
    sorted.addAll(standard);
    return sorted;
  } else {
    return super.getProperties(type);
  }
}
 
Example #13
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
		Tag customTag)
{
	if (javaBean instanceof AbstractElement)
	{
		if ("path".equals(property.getName()) || "buildPath".equals(property.getName())) //$NON-NLS-1$ //$NON-NLS-2$
		{
			String path = (String) propertyValue;
			IPath relative = Path.fromOSString(path).makeRelativeTo(
					Path.fromOSString(bundleDirectory.getAbsolutePath()));
			propertyValue = relative.toOSString();
		}
	}
	return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
 
Example #14
Source File: YamlPropertyRepresenter.java    From karamel with Apache License 2.0 5 votes vote down vote up
private int compareByName(Property o1, Property o2, String name) {
  if (o1.getName().equals(name)) {
    return -1;
  } else if (o2.getName().equals(name)) {
    return 1;
  }
  return 0;// compare further
}
 
Example #15
Source File: YamlPropertyRepresenter.java    From karamel with Apache License 2.0 5 votes vote down vote up
public int compare(Property o1, Property o2) {
  // important go first

  for (String name : order) {
    int c = compareByName(o1, o2, name);
    if (c != 0) {
      return c;
    }
  }
  // all the rest
  return o1.compareTo(o2);
}
 
Example #16
Source File: YamlPropertyRepresenter.java    From karamel with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
        Object propertyValue, Tag customTag) {
  if (propertyValue == null) {
    return null;
  } else {
    return super
            .representJavaBeanProperty(javaBean, property, propertyValue, customTag);
  }
}
 
Example #17
Source File: YamlOrderedSkipEmptyRepresenter.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(Property o1, Property o2) {
    Integer index1 = order.get(o1.getName());
    Integer index2 = order.get(o2.getName());

    if (Objects.isNull(index1) || Objects.isNull(index2)) {
        return 0;
    }

    return index1.compareTo(index2);
}
 
Example #18
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected void applySequence(Object bean, List<?> value) {
    try {
        Property property = getPropertyUtils().getProperty(bean.getClass(),
                getSequencePropertyName(bean.getClass()));
        property.set(bean, value);
    } catch (Exception e) {
        throw new YAMLException(e);
    }
}
 
Example #19
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected void setProperties(Object bean, Map<String, Object> data) throws Exception {
    if (data == null) {
        throw new NullPointerException("Data for Compact Object Notation cannot be null.");
    }
    for (Map.Entry<String, Object> entry : data.entrySet()) {
        String key = entry.getKey();
        Property property = getPropertyUtils().getProperty(bean.getClass(), key);
        try {
            property.set(bean, entry.getValue());
        } catch (IllegalArgumentException e) {
            throw new YAMLException("Cannot set property='" + key + "' with value='"
                    + data.get(key) + "' (" + data.get(key).getClass() + ") in " + bean);
        }
    }
}
 
Example #20
Source File: Representer.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * Represent one JavaBean property.
 *
 * @param javaBean
 *            - the instance to be represented
 * @param property
 *            - the property of the instance
 * @param propertyValue
 *            - value to be represented
 * @param customTag
 *            - user defined Tag
 * @return NodeTuple to be used in a MappingNode. Return null to skip the
 *         property
 */
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
        Object propertyValue, Tag customTag) {
    ScalarNode nodeKey = (ScalarNode) representData(property.getName());
    // the first occurrence of the node must keep the tag
    boolean hasAlias = this.representedObjects.containsKey(propertyValue);

    Node nodeValue = representData(propertyValue);

    if (propertyValue != null && !hasAlias) {
        NodeId nodeId = nodeValue.getNodeId();
        if (customTag == null) {
            if (nodeId == NodeId.scalar) {
                if (propertyValue instanceof Enum<?>) {
                    nodeValue.setTag(Tag.STR);
                }
            } else {
                if (nodeId == NodeId.mapping) {
                    if (property.getType() == propertyValue.getClass()) {
                        if (!(propertyValue instanceof Map<?, ?>)) {
                            if (!nodeValue.getTag().equals(Tag.SET)) {
                                nodeValue.setTag(Tag.MAP);
                            }
                        }
                    }
                }
                checkGlobalTag(property, nodeValue, propertyValue);
            }
        }
    }

    return new NodeTuple(nodeKey, nodeValue);
}
 
Example #21
Source File: Representer.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * Tag logic:<br>
 * - explicit root tag is set in serializer <br>
 * - if there is a predefined class tag it is used<br>
 * - a global tag with class name is always used as tag. The JavaBean parent
 * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
 * when the property class is the same as runtime class
 *
 * @param properties
 *            JavaBean getters
 * @param javaBean
 *            instance for Node
 * @return Node to get serialized
 */
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
    Tag tag;
    Tag customTag = classTags.get(javaBean.getClass());
    tag = customTag != null ? customTag : new Tag(javaBean.getClass());
    // flow style will be chosen by BaseRepresenter
    MappingNode node = new MappingNode(tag, value, null);
    representedObjects.put(javaBean, node);
    boolean bestStyle = true;
    for (Property property : properties) {
        Object memberValue = property.get(javaBean);
        Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue
                .getClass());
        NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue,
                customPropertyTag);
        if (tuple == null) {
            continue;
        }
        if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {
            bestStyle = false;
        }
        Node nodeValue = tuple.getValueNode();
        if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
            bestStyle = false;
        }
        value.add(tuple);
    }
    if (defaultFlowStyle != FlowStyle.AUTO) {
        node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
    } else {
        node.setFlowStyle(bestStyle);
    }
    return node;
}
 
Example #22
Source File: AdvancedRepresenterTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyMapProperty() {
  bean.setMapProperty(ImmutableMap.of());
  Property property = new MethodProperty(getPropertyDescriptor("mapProperty"));
  NodeTuple nodeTuple = representer.representJavaBeanProperty(bean, property, bean.getMapProperty(), null);
  assertThat(nodeTuple, is(nullValue()));
}
 
Example #23
Source File: AbstractPropertyUtils.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) {
    if (bAccess == BeanAccess.FIELD) {
        Map<String, Property> properties = new LinkedHashMap<>();
        findProperties(type, properties);
        propertiesCache.put(type, properties);
        return properties;
    } else return super.getPropertiesMap(type, bAccess);
}
 
Example #24
Source File: YamlOrderedSkipEmptyRepresenter.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    List<NodeTuple> value = new ArrayList<>(properties.size());
    Tag tag;
    Tag customTag = classTags.get(javaBean.getClass());
    tag = customTag != null ? customTag : new Tag(javaBean.getClass());
    MappingNode node = new MappingNode(tag, value, FlowStyle.BLOCK);
    representedObjects.put(javaBean, node);

    List<Property> orderProperties = new ArrayList<>(properties);
    orderProperties.sort(sorter);

    for (Property property : orderProperties) {
        Object memberValue = property.get(javaBean);
        Tag customPropertyTag = memberValue == null ? null
            : classTags.get(memberValue.getClass());
        NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue,
            customPropertyTag);
        if (tuple == null) {
            continue;
        }

        value.add(tuple);
    }

    return node;
}
 
Example #25
Source File: AdvancedRepresenterTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyCollectionProperty() {
  bean.setCollectionProperty(ImmutableList.of());
  Property property = new MethodProperty(getPropertyDescriptor("collectionProperty"));
  NodeTuple nodeTuple = representer.representJavaBeanProperty(bean, property, bean.getCollectionProperty(), null);
  assertThat(nodeTuple, is(nullValue()));
}
 
Example #26
Source File: AdvancedRepresenterTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void notNullCollectionProperty() {
  bean.setCollectionProperty(ImmutableList.<String>builder().add("1").add("2").build());
  Property property = new MethodProperty(getPropertyDescriptor("collectionProperty"));
  NodeTuple nodeTuple = representer.representJavaBeanProperty(bean, property, bean.getCollectionProperty(), null);
  assertThat(nodeTuple, is(notNullValue()));
  assertThat(nodeTuple.getKeyNode(), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) nodeTuple.getKeyNode()).getValue(), is("collection-property"));
  assertThat(nodeTuple.getValueNode(), is(instanceOf(SequenceNode.class)));
  assertThat(((SequenceNode) nodeTuple.getValueNode()).getValue().size(), is(2));
  assertThat(((SequenceNode) nodeTuple.getValueNode()).getValue().get(0), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) ((SequenceNode) nodeTuple.getValueNode()).getValue().get(0)).getValue(), is("1"));
  assertThat(((SequenceNode) nodeTuple.getValueNode()).getValue().get(1), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) ((SequenceNode) nodeTuple.getValueNode()).getValue().get(1)).getValue(), is("2"));
}
 
Example #27
Source File: YamlParser.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Prevents writing null values out to index.yaml, not a part of JodaTimeRepresenter necessarily
 * but included here as we are setting up a {@link Representer}
 */
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean,
                                              Property property,
                                              Object propertyValue,
                                              Tag customTag)
{
  // if value of property is null, ignore it.
  if (propertyValue == null) {
    return null;
  }
  else {
    return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
  }
}
 
Example #28
Source File: AdvancedPropertyUtilsTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #29
Source File: AdvancedPropertyUtilsTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #30
Source File: StaticFieldsTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    MappingNode node = super.representJavaBean(properties, javaBean);
    if (javaBean instanceof JavaBeanWithStaticState) {
        List<NodeTuple> value = node.getValue();
        value.add(new NodeTuple(representData("color"),
                representData(JavaBeanWithStaticState.color)));
        value.add(new NodeTuple(representData("type"),
                representData(JavaBeanWithStaticState.getType())));
    }
    return node;
}