Like Java API
Last modified by Eleni Cojocariu on 2026/08/12 13:56
Reference
org.xwiki.like.LikeManager is the Component role behind the whole feature: inject it to read or write likes from Java. A user is always passed as a UserReference and a liked entity as an EntityReference. Every method that reads or writes likes throws a LikeException when the store fails or when the user lacks the like right; getLikeRight() and the two clearCache methods do not throw.
| Method | Returns | Description |
|---|---|---|
| saveLike(source, target) | long | Records a like and returns the new like count of the target. |
| removeLike(source, target) | boolean | Removes a like and returns whether one was actually removed. |
| isLiked(source, target) | boolean | Whether that user already liked that entity. |
| getEntityLikes(target) | long | The number of likes of an entity. |
| getLikers(target, offset, limit) | List<UserReference> | The users who liked an entity, most recently updated first. |
| getUserLikes(source, offset, limit) | List<EntityReference> | The entities a user liked, most recently updated first. |
| countUserLikes(source) | long | How many likes a user performed. |
| getLikeRight() | Right | The like right, as registered when the Component initialized. |
| clearCache(target) | void | Drops the cached count and the per-user entries of one entity. |
| clearCache() | void | Empties both caches. |
@Inject
private LikeManager likeManager;
@Inject
@Named("document")
private UserReferenceResolver<DocumentReference> userReferenceResolver;
public long like(DocumentReference user, DocumentReference page) throws LikeException
{
return this.likeManager.saveLike(this.userReferenceResolver.resolve(user), page);
}Events
LikeEvent and UnlikeEvent, both in org.xwiki.like.events, are sent through the Observation Manager once a like has been stored or removed.
| Listener argument | Value |
|---|---|
| source | The UserReference of the user who liked or unliked. |
| data | The EntityReference that was liked or unliked. |
@Component
@Named("MyLikeListener")
@Singleton
public class MyLikeListener extends AbstractEventListener
{
public MyLikeListener()
{
super("MyLikeListener", new LikeEvent(), new UnlikeEvent());
}
@Override
public void onEvent(Event event, Object source, Object data)
{
UserReference liker = (UserReference) source;
EntityReference liked = (EntityReference) data;
}
}Configuration
org.xwiki.like.LikeConfiguration reads the settings an administrator edits in the Like preferences: isEnabled(), alwaysDisplayButton() and getLikeCacheCapacity().
FAQ
What does removeLike() return when there was no like to remove?
It returns false and sends no UnlikeEvent.