Skip to content

Commit

Permalink
restapi: prefer parentType over subclasses in getParent
Browse files Browse the repository at this point in the history
Currently LinkHelper#getParent may return subclasses even if the
parentType exists in the methods list.

This makes the returned resource unpredicatble as the method list does
not have any guaranteed order.

To fix this, this patch tries to match parentType first, and only if it
is not in the list it will fallback to a subclass.

Bug-Url: https://bugzilla.redhat.com/2080728
Signed-off-by: Benny Zlotnik <bzlotnik@redhat.com>
  • Loading branch information
bennyz committed May 2, 2022
1 parent 67af763 commit 5416638
Showing 1 changed file with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -225,18 +225,26 @@ private static void unsetInlineResource(BaseResource model, Class<?> type) {
* @return the parent object, or null if not set
*/
private static <R extends BaseResource> BaseResource getParent(R model, Class<?> parentType) {
Object assignedFromParent = null;

// Try to match a method whose parent matches parentType first, only fallback to a subclass if parentType was
// not found in the list.
for (Method method : getRelevantMethods(model.getClass())) {
try {
Object potentialParent = method.invoke(model);
if (potentialParent != null && potentialParent.getClass().equals(parentType)) {
return (BaseResource) potentialParent;
}
if (potentialParent != null && parentType.isAssignableFrom(potentialParent.getClass())) {
return (BaseResource)potentialParent;
assignedFromParent = potentialParent;
}
} catch (Exception e) {
log.error("Error invoking method when adding links to an API entity", e);
continue;
}
}
return null;

return (BaseResource) assignedFromParent;
}

/**
Expand Down

0 comments on commit 5416638

Please sign in to comment.