raml-java-parser
raml-java-parser copied to clipboard
[Q] How to get only properties directly declared in an object type?
I'm not sure if this should be just a question or a feature request. I tried to find answers in the source code and by reading through existing issues here, without luck so far.
Question
I'd like to know if there's a simple way to get a list of properties that are directly declared (or overridden) in an ObjectTypeDeclaration, without any inherited (or "resolved") properties from parent types.
Example
Given the following mock RAML API
#%RAML 1.0
title: Mock API
types:
WithID:
type: object
properties:
id:
description: Unique object ID.
User:
type: WithID
properties:
login_name:
description: User login name.
...in Java I would like to do something like that:
// Let's assume api is the parsed mock API:
List<TypeDeclaration> types = api.types();
ObjectTypeDeclaration userType = (ObjectTypeDeclaration) types.get(1);
// Is there a method like this one anywhere available?
List<TypeDeclaration> declared = userType.declaredProperties();
for (TypeDeclaration declaredProp : declared) {
System.out.println(declaredProp.name());
}
Expected Output
login_name
Use Case
I'm trying to write a Java code generator for creating Java beans. I'd like to generate beans for RAML resource types using Java inheritance, instead of having duplicated code due to resolved properties.
That means I'd like to transform the RAML type declarations into the following Java code:
WithID.java
public class WithID {
public String id;
}
User.java
public class User extends WithID {
public String login_name;
}
Aha! Link: https://mulesoft-roadmap.aha.io/features/APIRAML-107
Hi @tiguchi right now you can only see the resolve properties. What you can see is the inheritance hierarchy, and check which properties are provided by the super types.
I implemented a workaround that determines the properties declared by a type "A" by diffing them with all properties of the parent types of "A":
public static List<TypeDeclaration> declaredProperties(ObjectTypeDeclaration td) {
List<TypeDeclaration> parentTypes = td.parentTypes();
List<TypeDeclaration> declaredProperties = td.properties();
for (TypeDeclaration parentType : parentTypes) {
if (parentType instanceof ObjectTypeDeclaration) {
/*
* "difference" only returns properties from the "declaredProperties" list
* that do not exist by name in the parent type properties list, or that do have the same
* name but different attributes (e.g. different description, type, items, enum etc.)
*/
declaredProperties = difference(declaredProperties, ((ObjectTypeDeclaration) parentType).properties());
}
}
return declaredProperties;
}
That approach works for me so far.
Still, it would be nice to have a parser API method for getting that kind of information without workaround.