Search in sources :

Example 16 with NotificationException

use of org.xwiki.notifications.NotificationException in project xwiki-platform by xwiki.

the class DefaultNotificationRSSRenderer method renderNotification.

@Override
public SyndEntry renderNotification(CompositeEvent eventNotification) throws NotificationException {
    SyndEntry entry = new SyndEntryImpl();
    SyndContent entryDescription = new SyndContentImpl();
    // The users contained in the CompositeEvent are already stored in a Set, they are therefore necessarily unique
    List<SyndPerson> eventAuthors = new ArrayList<SyndPerson>();
    // Convert every author of the CompositeEvent to a SyndPerson and add it to the new entry
    for (DocumentReference author : eventNotification.getUsers()) {
        SyndPerson person = new SyndPersonImpl();
        person.setName(author.getName());
        eventAuthors.add(person);
    }
    entry.setAuthors(eventAuthors);
    // Define the GUID of the event
    entry.setUri(String.join("-", eventNotification.getEventIds()));
    // Set the entry title
    entry.setTitle(this.contextualLocalizationManager.getTranslationPlain(eventNotification.getEvents().get(0).getTitle(), eventNotification.getEvents().get(0).getDocumentTitle()));
    // Render the description (the main part) of the feed entry
    try {
        this.scriptContextManager.getCurrentScriptContext().setAttribute(COMPOSITE_EVENT_BUILDING_NAME, eventNotification, ScriptContext.ENGINE_SCOPE);
        // Try to get a template associated with the composite event
        Template template = this.templateManager.getTemplate(String.format("notification/rss/%s.vm", eventNotification.getType().replaceAll("\\/", ".")));
        // If no template is found, fallback on the default one
        if (template == null) {
            template = this.templateManager.getTemplate("notification/rss/default.vm");
        }
        XDOM descriptionXDOM = this.templateManager.execute(template);
        WikiPrinter printer = new DefaultWikiPrinter();
        blockRenderer.render(descriptionXDOM, printer);
        // Add the description to the entry
        entryDescription.setType("text/html");
        entryDescription.setValue(printer.toString());
        entry.setDescription(entryDescription);
    } catch (Exception e) {
        throw new NotificationException(String.format("Unable to render the description of the event [%s].", eventNotification), e);
    } finally {
        this.scriptContextManager.getCurrentScriptContext().removeAttribute(COMPOSITE_EVENT_BUILDING_NAME, ScriptContext.ENGINE_SCOPE);
    }
    // Dates are sorted in descending order in a CompositeEvent, the first date is then the most recent one
    entry.setUpdatedDate(eventNotification.getDates().get(0));
    return entry;
}
Also used : XDOM(org.xwiki.rendering.block.XDOM) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) SyndEntry(com.rometools.rome.feed.synd.SyndEntry) SyndContentImpl(com.rometools.rome.feed.synd.SyndContentImpl) ArrayList(java.util.ArrayList) NotificationException(org.xwiki.notifications.NotificationException) WikiPrinter(org.xwiki.rendering.renderer.printer.WikiPrinter) DefaultWikiPrinter(org.xwiki.rendering.renderer.printer.DefaultWikiPrinter) NotificationException(org.xwiki.notifications.NotificationException) Template(org.xwiki.template.Template) SyndPerson(com.rometools.rome.feed.synd.SyndPerson) SyndPersonImpl(com.rometools.rome.feed.synd.SyndPersonImpl) SyndContent(com.rometools.rome.feed.synd.SyndContent) SyndEntryImpl(com.rometools.rome.feed.synd.SyndEntryImpl) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 17 with NotificationException

use of org.xwiki.notifications.NotificationException in project xwiki-platform by xwiki.

the class DefaultModelBridge method saveNotificationsPreferences.

@Override
public void saveNotificationsPreferences(DocumentReference targetDocument, List<NotificationPreference> notificationPreferences) throws NotificationException {
    try {
        XWikiContext context = contextProvider.get();
        XWiki xwiki = context.getWiki();
        XWikiDocument document = xwiki.getDocument(targetDocument, context);
        for (NotificationPreference notificationPreference : notificationPreferences) {
            // Ensure that the notification preference has an event type to save
            if (!notificationPreference.getProperties().containsKey(NotificationPreferenceProperty.EVENT_TYPE)) {
                continue;
            }
            // Try to find the corresponding XObject for the notification preference
            BaseObject preferenceObject = this.findNotificationPreference(document, notificationPreference);
            // If no preference exist, then create one
            if (preferenceObject == null) {
                preferenceObject = new BaseObject();
                preferenceObject.setXClassReference(NOTIFICATION_PREFERENCE_CLASS);
                document.addXObject(preferenceObject);
            }
            preferenceObject.set(EVENT_TYPE_FIELD, notificationPreference.getProperties().get(NotificationPreferenceProperty.EVENT_TYPE), context);
            preferenceObject.set(FORMAT_FIELD, notificationPreference.getFormat().name().toLowerCase(), context);
            preferenceObject.set(NOTIFICATION_ENABLED_FIELD, (notificationPreference.isNotificationEnabled() ? 1 : 0), context);
            Date startDate = null;
            if (notificationPreference.isNotificationEnabled()) {
                startDate = notificationPreference.getStartDate();
                if (startDate == null) {
                    // Fallback to the previous value if date is empty
                    startDate = preferenceObject.getDateValue(START_DATE_FIELD);
                    if (startDate == null) {
                        // Fallback to now
                        startDate = new Date();
                    }
                }
            }
            preferenceObject.set(START_DATE_FIELD, startDate, context);
        }
        // Make this change a minor edit so it's not displayed, by default, in notifications
        xwiki.saveDocument(document, "Update notification preferences.", true, context);
    } catch (XWikiException e) {
        throw new NotificationException(String.format("Failed to save the notification preference into [%s]", targetDocument));
    }
}
Also used : NotificationPreference(org.xwiki.notifications.preferences.NotificationPreference) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) NotificationException(org.xwiki.notifications.NotificationException) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) Date(java.util.Date) XWikiException(com.xpn.xwiki.XWikiException) BaseObject(com.xpn.xwiki.objects.BaseObject)

Example 18 with NotificationException

use of org.xwiki.notifications.NotificationException in project xwiki-platform by xwiki.

the class NotificationPreferenceScriptService method setStartDate.

/**
 * Set the start date for every notification preference of the given user.
 *
 * @param userId id of the user
 * @param startDate the date before which we ignore notifications
 * @throws NotificationException if an error occurs
 */
public void setStartDate(String userId, Date startDate) throws NotificationException {
    try {
        DocumentReference user = documentReferenceResolver.resolve(userId);
        this.authorizationManager.checkAccess(Right.EDIT, user);
        notificationPreferenceManager.setStartDateForUser(user, startDate);
    } catch (AccessDeniedException e) {
        throw new NotificationException(String.format("Unable to save the start date of the notifications for the user [%s]", userId), e);
    }
}
Also used : AccessDeniedException(org.xwiki.security.authorization.AccessDeniedException) NotificationException(org.xwiki.notifications.NotificationException) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 19 with NotificationException

use of org.xwiki.notifications.NotificationException in project xwiki-platform by xwiki.

the class NotificationPreferenceScriptService method saveNotificationPreferences.

private void saveNotificationPreferences(String json, String providerHint, EntityReference target, NotificationPreferenceCategory category) throws NotificationException {
    /*
            The JSON we get is a "snapshot" of the states of the buttons the user has in front of her eyes when she is
            managing her preferences.

            We did that so we can save several preferences in the same time without making too much requests (for
            example when the user enable an application, it actually enable all the app's event types).

            However, this snapshot also "freeze" the default preferences, ie the preferences set at the wiki level and
            that the user has not changed.

            Example:
            1. Wiki Administrator enables the application A by default, and doesn't touch the settings for the
               application B.
            2. John Doe disables the application A on HIS profile. He doesn't touch the setting for the application B.
               A "snapshot" of his preferences is saved.
            3. Wiki Administrator enables the application B by default.
            4. On the John Doe's preferences, application B is still disabled, because of the snapshot done on step 2.

            I don't think this situation is good. If a user did not EXPLICITLY change a setting, the default settings
            should be applied.

            For this reason, this code will only save the settings THAT ARE DIFFERENT FROM THE DEFAULT (INHERITED).

            Since this logic is totally related to the way the UI is built, I think it does not deserve its own
            component or API. In a way, it should even be internal.
        */
    List<NotificationPreference> existingPreferences = Collections.emptyList();
    if (target instanceof DocumentReference) {
        existingPreferences = notificationPreferenceManager.getAllPreferences((DocumentReference) target);
    } else if (target instanceof WikiReference) {
        existingPreferences = notificationPreferenceManager.getAllPreferences((WikiReference) target);
    }
    // Instantiate a new copy of TargetableNotificationPreferenceBuilder because this component is not thread-safe.
    TargetableNotificationPreferenceBuilder targetableNotificationPreferenceBuilder = targetableNotificationPreferenceBuilderProvider.get();
    List<NotificationPreference> toSave = new ArrayList<>();
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> preferences = objectMapper.reader().forType(List.class).readValue(json);
        for (Map<String, Object> item : preferences) {
            String eventType = (String) item.get("eventType");
            NotificationFormat format = NotificationFormat.valueOf(((String) item.get("format")).toUpperCase());
            boolean enabled = (Boolean) item.get("enabled");
            targetableNotificationPreferenceBuilder.prepare();
            targetableNotificationPreferenceBuilder.setEnabled(enabled);
            targetableNotificationPreferenceBuilder.setFormat(format);
            targetableNotificationPreferenceBuilder.setProviderHint(providerHint);
            targetableNotificationPreferenceBuilder.setProperties(Collections.singletonMap(NotificationPreferenceProperty.EVENT_TYPE, eventType));
            targetableNotificationPreferenceBuilder.setTarget(target);
            targetableNotificationPreferenceBuilder.setCategory(category);
            TargetableNotificationPreference newPreference = targetableNotificationPreferenceBuilder.build();
            // This part is explained by the long comment below
            NotificationPreference correspondingPreference = getCorrespondingPreference(existingPreferences, newPreference);
            if (correspondingPreference == null || correspondingPreference.isNotificationEnabled() != newPreference.isNotificationEnabled()) {
                toSave.add(newPreference);
            }
        }
        notificationPreferenceManager.savePreferences(toSave);
    } catch (Exception e) {
        throw new NotificationException("Failed to save preferences for notifications given as JSON.", e);
    }
}
Also used : TargetableNotificationPreferenceBuilder(org.xwiki.notifications.preferences.TargetableNotificationPreferenceBuilder) ArrayList(java.util.ArrayList) NotificationException(org.xwiki.notifications.NotificationException) NotificationException(org.xwiki.notifications.NotificationException) AccessDeniedException(org.xwiki.security.authorization.AccessDeniedException) NotificationPreference(org.xwiki.notifications.preferences.NotificationPreference) TargetableNotificationPreference(org.xwiki.notifications.preferences.TargetableNotificationPreference) NotificationFormat(org.xwiki.notifications.NotificationFormat) ArrayList(java.util.ArrayList) List(java.util.List) WikiReference(org.xwiki.model.reference.WikiReference) TargetableNotificationPreference(org.xwiki.notifications.preferences.TargetableNotificationPreference) Map(java.util.Map) DocumentReference(org.xwiki.model.reference.DocumentReference) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 20 with NotificationException

use of org.xwiki.notifications.NotificationException in project xwiki-platform by xwiki.

the class DefaultNotificationPreferenceManager method getProviders.

private List<NotificationPreferenceProvider> getProviders() throws NotificationException {
    try {
        // Get every registered notification provider
        List<NotificationPreferenceProvider> providers = componentManager.getInstanceList(NotificationPreferenceProvider.class);
        // We handle conflicts between similar preferences by sorting the providers by order. Since
        // notificationPreferences is a set, only the first occurrence of a preference is stored.
        Collections.sort(providers, (o1, o2) -> o2.getProviderPriority() - o1.getProviderPriority());
        return providers;
    } catch (ComponentLookupException e) {
        throw new NotificationException("Unable to fetch the notifications preferences providers from the component manager", e);
    }
}
Also used : NotificationException(org.xwiki.notifications.NotificationException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) NotificationPreferenceProvider(org.xwiki.notifications.preferences.NotificationPreferenceProvider)

Aggregations

NotificationException (org.xwiki.notifications.NotificationException)24 DocumentReference (org.xwiki.model.reference.DocumentReference)14 XWikiContext (com.xpn.xwiki.XWikiContext)10 XWikiException (com.xpn.xwiki.XWikiException)9 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)9 XWiki (com.xpn.xwiki.XWiki)8 BaseObject (com.xpn.xwiki.objects.BaseObject)8 ArrayList (java.util.ArrayList)6 List (java.util.List)4 NotificationFormat (org.xwiki.notifications.NotificationFormat)4 NotificationFilterPreference (org.xwiki.notifications.filters.NotificationFilterPreference)4 NotificationPreference (org.xwiki.notifications.preferences.NotificationPreference)4 Date (java.util.Date)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)3 NotificationFilter (org.xwiki.notifications.filters.NotificationFilter)3 SyndEntry (com.rometools.rome.feed.synd.SyndEntry)2 Map (java.util.Map)2 CompositeEvent (org.xwiki.notifications.CompositeEvent)2