org.vaadin.spring.events.EventBus - java examples

Here are the examples of the java api org.vaadin.spring.events.EventBus taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

8 Examples 7

19 View Complete Implementation : AbstractListenerWrapper.java
Copyright Apache License 2.0
Author : peholmst
/**
 * Base implementation of {@link org.vaadin.spring.events.internal.ListenerCollection.Listener} that implements
 * the {@link #supports(org.vaadin.spring.events.Event)}  method. An event is supported if:
 * <ul>
 * <li>The payload type of the listener is either the same type as, or a supertype of, the payload type of the event</li>
 * <li>The listener allows propagating events, or the event was originally published on event bus that the listener was subscribed to</li>
 * </ul>
 *
 * @author Petter Holmström ([email protected])
 */
abstract clreplaced AbstractListenerWrapper implements ListenerCollection.Listener {

    private static final long serialVersionUID = 6211420845165980671L;

    private final EventBus owningEventBus;

    private final Object listenerTarget;

    private final boolean includingPropagatingEvents;

    private final String topic;

    AbstractListenerWrapper(EventBus owningEventBus, Object listenerTarget, String topic, boolean includingPropagatingEvents) {
        this.owningEventBus = owningEventBus;
        this.topic = topic;
        this.listenerTarget = listenerTarget;
        this.includingPropagatingEvents = includingPropagatingEvents;
    }

    /**
     * Gets the payload type of the listener.
     */
    protected abstract Clreplaced<?> getPayloadType();

    /**
     * Gets the target object that this listener is wrapping.
     */
    public Object getListenerTarget() {
        return listenerTarget;
    }

    @Override
    public boolean supports(Event<?> event) {
        final Clreplaced<?> eventPayloadType = event.getPayload().getClreplaced();
        return (event.getTopic().equals(topic) || topic == null) && getPayloadType().isreplacedignableFrom(eventPayloadType) && (includingPropagatingEvents || event.getEventBus().equals(owningEventBus));
    }
}

18 View Complete Implementation : ApplicationContextEventBroker.java
Copyright Apache License 2.0
Author : peholmst
/**
 * An {@link org.springframework.context.ApplicationListener} that will forward all received events to an {@link org.vaadin.spring.events.EventBus}.
 *
 * @author Petter Holmström ([email protected])
 */
public clreplaced ApplicationContextEventBroker implements ApplicationListener<ApplicationEvent> {

    private Log logger = LogFactory.getLog(getClreplaced());

    private final EventBus eventBus;

    public ApplicationContextEventBroker(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        logger.debug(String.format("Propagating application event [%s] to event bus [%s]", event, this));
        eventBus.publish(event.getSource(), event);
    }
}

17 View Complete Implementation : SecuredNavigator.java
Copyright Apache License 2.0
Author : markoradinovic
public clreplaced SecuredNavigator extends Navigator {

    private static final long serialVersionUID = -1550472603474329940L;

    final Security security;

    final SpringViewProvider viewProvider;

    final EventBus eventBus;

    public SecuredNavigator(UI ui, ViewDisplay display, SpringViewProvider viewProvider, Security security, EventBus eventBus) {
        super(ui, display);
        this.security = security;
        this.viewProvider = viewProvider;
        this.eventBus = eventBus;
        addProvider(this.viewProvider);
    }

    /*
	 * (non-Javadoc)
	 * @see com.vaadin.navigator.Navigator#navigateTo(java.lang.String)
	 */
    @Override
    public void navigateTo(String navigationState) {
        if (ViewToken.VALID_TOKENS.contains(navigationState)) {
            /* This method in clreplaced should be public
			 * private boolean isViewBeanNameValidForCurrentUI(String beanName)
			 * 
			 *  workaround
			 */
            if (viewProvider.getView(navigationState) == null) {
                /*
				 * Handle entering UI from bookmark
				 */
                String uriFragment = extractViewToken();
                if (uriFragment.equals(navigationState)) {
                    super.navigateTo(ViewToken.HOME);
                } else {
                    /*
	            	 * View is probably @Secured
	            	 */
                    eventBus.publish(EventScope.UI, UI.getCurrent(), new AccessDeniedEvent(navigationState));
                }
            } else {
                super.navigateTo(navigationState);
            }
        } else {
            // invalid ViewToken
            super.navigateTo(ViewToken.HOME);
        }
    }

    private String extractViewToken() {
        String uriFragment = Page.getCurrent().getUriFragment();
        if (uriFragment != null && !uriFragment.isEmpty() && uriFragment.length() > 1) {
            return uriFragment.substring(1);
        } else {
            return "";
        }
    }
}

17 View Complete Implementation : ScopedEventBus.java
Copyright Apache License 2.0
Author : peholmst
/**
 * Implementation of {@link org.vaadin.spring.events.EventBus} that publishes events with one specific
 * {@link org.vaadin.spring.events.EventScope}.
 * A scoped event bus can also have a parent event bus, in which case all events published on the parent bus will
 * propagate to the scoped event bus as well.
 *
 * @author Petter Holmström ([email protected])
 */
public abstract clreplaced ScopedEventBus implements EventBus, Serializable {

    private static final long serialVersionUID = -582697574672947883L;

    private final Logger logger = LoggerFactory.getLogger(getClreplaced());

    private final EventScope eventScope;

    private final ListenerCollection listeners = new ListenerCollection();

    private EventBus parentEventBus;

    private EventBusListener<Object> parentListener = new EventBusListener<Object>() {

        private static final long serialVersionUID = -8276470908536582989L;

        @Override
        public void onEvent(final Event<Object> event) {
            logger.debug("Propagating event [{}] from parent event bus [{}] to event bus [{}]", event, parentEventBus, ScopedEventBus.this);
            listeners.publish(event);
        }
    };

    /**
     * @param scope the scope of the events that this event bus handles.
     */
    public ScopedEventBus(EventScope scope) {
        this(scope, null);
    }

    /**
     * @param scope          the scope of the events that this event bus handles.
     * @param parentEventBus the parent event bus to use, may be {@code null};
     */
    public ScopedEventBus(EventScope scope, EventBus parentEventBus) {
        eventScope = scope;
        this.parentEventBus = parentEventBus;
        if (parentEventBus != null) {
            if (AopUtils.isJdkDynamicProxy(parentEventBus)) {
                logger.debug("Parent event bus [{}] is proxied, trying to get the real EventBus instance", parentEventBus);
                try {
                    this.parentEventBus = (EventBus) ((Advised) parentEventBus).getTargetSource().getTarget();
                } catch (Exception e) {
                    logger.error("Could not get target EventBus from proxy", e);
                    throw new RuntimeException("Could not get parent event bus", e);
                }
            }
            logger.debug("Using parent event bus [{}]", this.parentEventBus);
            this.parentEventBus.subscribe(parentListener);
        }
    }

    @PreDestroy
    void destroy() {
        logger.trace("Destroying event bus [{}] and removing all listeners", this);
        listeners.clear();
        if (parentEventBus != null) {
            parentEventBus.unsubscribe(parentListener);
        }
    }

    @Override
    public EventScope getScope() {
        return eventScope;
    }

    @Override
    public <T> void publish(Object sender, T payload) {
        publish("", sender, payload);
    }

    @Override
    public <T> void publish(String topic, Object sender, T payload) {
        logger.debug("Publishing payload [{}] from sender [{}] on event bus [{}] in topic  [{}]", payload, sender, this, topic);
        listeners.publish(new Event<T>(this, sender, payload, topic));
    }

    @Override
    public <T> void publish(EventScope scope, Object sender, T payload) throws UnsupportedOperationException {
        publish(scope, "", sender, payload);
    }

    @Override
    public <T> void publish(EventScope scope, String topic, Object sender, T payload) throws UnsupportedOperationException {
        logger.debug("Trying to publish payload [{}] from sender [{}] using scope [{}] on event bus [{}] in topic [{}]", payload, sender, scope, this, topic);
        if (eventScope.equals(scope)) {
            publish(topic, sender, payload);
        } else if (parentEventBus != null) {
            parentEventBus.publish(scope, topic, sender, payload);
        } else {
            logger.warn("Could not publish payload with scope [{}] on event bus [{}]", scope, this);
            throw new UnsupportedOperationException("Could not publish event with scope " + scope);
        }
    }

    @Override
    public <T> void subscribe(EventBusListener<T> listener) {
        subscribe(listener, true);
    }

    @Override
    public <T> void subscribeWithWeakReference(EventBusListener<T> listener) {
        subscribeWithWeakReference(listener, true);
    }

    @Override
    public <T> void subscribe(EventBusListener<T> listener, String topic) {
        logger.trace("Subscribing listener [{}] to event bus [{}]", listener, this);
        listeners.add(new EventBusListenerWrapper(this, listener, topic, true));
    }

    @Override
    public <T> void subscribe(EventBusListener<T> listener, boolean includingPropagatingEvents) {
        logger.trace("Subscribing listener [{}] to event bus [{}], includingPropagatingEvents = {}", listener, this, includingPropagatingEvents);
        listeners.add(new EventBusListenerWrapper(this, listener, null, includingPropagatingEvents));
    }

    @Override
    public <T> void subscribeWithWeakReference(EventBusListener<T> listener, String topic) {
        logger.trace("Subscribing listener [{}] to event bus [{}] with weak reference", listener, this);
        listeners.addWithWeakReference(new EventBusListenerWrapper(this, listener, topic, true));
    }

    @Override
    public <T> void subscribeWithWeakReference(EventBusListener<T> listener, boolean includingPropagatingEvents) {
        logger.trace("Subscribing listener [{}] to event bus [{}] with weak reference, includingPropagatingEvents = {}", listener, this, includingPropagatingEvents);
        listeners.addWithWeakReference(new EventBusListenerWrapper(this, listener, null, includingPropagatingEvents));
    }

    @Override
    public void subscribe(Object listener) {
        subscribe(listener, true);
    }

    @Override
    public void subscribe(Object listener, String topic) {
        subscribe(listener, topic, true, false);
    }

    @Override
    public void subscribeWithWeakReference(Object listener, String topic) {
        subscribe(listener, topic, true, false);
    }

    @Override
    public void subscribeWithWeakReference(Object listener) {
        subscribeWithWeakReference(listener, true);
    }

    @Override
    public void subscribe(Object listener, boolean includingPropagatingEvents) {
        subscribe(listener, null, includingPropagatingEvents, false);
    }

    @Override
    public void subscribeWithWeakReference(Object listener, boolean includingPropagatingEvents) {
        subscribe(listener, null, includingPropagatingEvents, true);
    }

    private void subscribe(final Object listener, final String topic, final boolean includingPropagatingEvents, final boolean weakReference) {
        logger.trace("Subscribing listener [{}] to event bus [{}], includingPropagatingEvents = {}, weakReference = {}", listener, this, includingPropagatingEvents, weakReference);
        final int[] foundMethods = new int[1];
        ClreplacedUtils.visitClreplacedHierarchy(clazz -> {
            for (Method m : clazz.getDeclaredMethods()) {
                if (m.isAnnotationPresent(EventBusListenerMethod.clreplaced)) {
                    if (m.getParameterTypes().length == 1) {
                        logger.trace("Found listener method [{}] in listener [{}]", m.getName(), listener);
                        MethodListenerWrapper l = new MethodListenerWrapper(ScopedEventBus.this, listener, topic, includingPropagatingEvents, m);
                        if (weakReference) {
                            listeners.addWithWeakReference(l);
                        } else {
                            listeners.add(l);
                        }
                        foundMethods[0]++;
                    } else {
                        throw new IllegalArgumentException("Listener method " + m.getName() + " does not have the required signature");
                    }
                }
            }
        }, listener.getClreplaced());
        if (foundMethods[0] == 0) {
            logger.warn("Listener [{}] did not contain a single listener method!", listener);
        }
    }

    @Override
    public <T> void unsubscribe(EventBusListener<T> listener) {
        unsubscribe((Object) listener);
    }

    @Override
    public void unsubscribe(final Object listener) {
        logger.trace("Unsubscribing listener [{}] from event bus [{}]", listener, this);
        listeners.removeAll(l -> (l instanceof AbstractListenerWrapper) && (((AbstractListenerWrapper) l).getListenerTarget() == listener));
    }

    /**
     * Gets the parent of this event bus. Events published on the parent bus will also
     * propagate to the listeners of this event bus.
     *
     * @return the parent event bus, or {@code null} if this event bus has no parent.
     */
    protected EventBus getParentEventBus() {
        return parentEventBus;
    }

    @Override
    public String toString() {
        return String.format("%s[id=%x, eventScope=%s, parentEventBus=%s]", getClreplaced().getSimpleName(), System.idenreplacedyHashCode(this), eventScope, parentEventBus);
    }

    /**
     * Default implementation of {@link org.vaadin.spring.events.EventBus.ApplicationEventBus}.
     */
    public static clreplaced DefaultApplicationEventBus extends ScopedEventBus implements ApplicationEventBus {

        public DefaultApplicationEventBus() {
            super(EventScope.APPLICATION);
        }
    }

    /**
     * Default implementation of {@link org.vaadin.spring.events.EventBus.SessionEventBus}.
     */
    public static clreplaced DefaultSessionEventBus extends ScopedEventBus implements SessionEventBus {

        public DefaultSessionEventBus(ApplicationEventBus parentEventBus) {
            super(EventScope.SESSION, parentEventBus);
        }
    }

    /**
     * Default implementation of {@link org.vaadin.spring.events.EventBus.UIEventBus}.
     */
    public static clreplaced DefaultUIEventBus extends ScopedEventBus implements UIEventBus {

        public DefaultUIEventBus(SessionEventBus parentEventBus) {
            super(EventScope.UI, parentEventBus);
        }
    }
}

17 View Complete Implementation : ApplicationContextEventBrokerTest.java
Copyright Apache License 2.0
Author : peholmst
@Test
public void testOnApplicationEvent() {
    ApplicationEvent event = new ApplicationEvent(this) {

        private static final long serialVersionUID = 7475015652750718692L;

        @Override
        public Object getSource() {
            return "mySource";
        }
    };
    EventBus eventBus = mock(EventBus.clreplaced);
    new ApplicationContextEventBroker(eventBus).onApplicationEvent(event);
    verify(eventBus).publish("mySource", event);
}

16 View Complete Implementation : MainUI.java
Copyright Apache License 2.0
Author : markoradinovic
@VaadinUI
@replacedle("Vaadin4Spring Security Demo")
@Theme("valo")
@SuppressWarnings("serial")
public clreplaced MainUI extends UI {

    @Autowired
    SpringViewProvider springViewProvider;

    @Autowired
    EventBus eventBus;

    @Autowired
    Security security;

    @Autowired
    MainLayout mainLayout;

    @Override
    protected void init(VaadinRequest request) {
        setLocale(new Locale.Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build());
        SecuredNavigator securedNavigator = new SecuredNavigator(MainUI.this, mainLayout, springViewProvider, security, eventBus);
        securedNavigator.addViewChangeListener(mainLayout);
        setContent(mainLayout);
        setErrorHandler(new SpringSecurityErrorHandler());
    /*
         * Handling redirections
         */
    // RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
    // if (sessionStrategy.getAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE) != null) {
    // VaadinRedirectObject redirectObject = (VaadinRedirectObject) sessionStrategy.getAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE);
    // sessionStrategy.removeAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE);
    // 
    // navigator.navigateTo(redirectObject.getRedirectViewToken());
    // 
    // if (redirectObject.getErrorMessage() != null) {
    // Notification.show("Error", redirectObject.getErrorMessage(), Type.ERROR_MESSAGE);
    // }
    // 
    // }
    }
}

12 View Complete Implementation : MainLayout.java
Copyright Apache License 2.0
Author : markoradinovic
@UIScope
@VaadinComponent
@SuppressWarnings("serial")
public clreplaced MainLayout extends VerticalLayout implements ViewDisplay, ClickListener, ViewChangeListener {

    private Panel viewContainer;

    private HorizontalLayout navbar;

    private Button btnHome;

    private Button btnUser;

    private Button btnAdmin;

    private Button btnAdminHidden;

    private Button btnSignIn;

    private Button btnSignUp;

    private Button btnLogout;

    private String key = UUID.randomUUID().toString();

    @Autowired
    Security security;

    @Autowired
    SpringViewProvider springViewProvider;

    @Autowired
    EventBus eventBus;

    @PostConstruct
    public void postConstuct() {
        setSizeFull();
        eventBus.subscribe(this);
        navbar = new HorizontalLayout();
        navbar.setWidth("100%");
        navbar.setMargin(true);
        navbar.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);
        addComponent(navbar);
        final Label brand = new Label("Vaadin4Spring Security Demo");
        brand.addStyleName(ValoTheme.LABEL_H2);
        brand.addStyleName(ValoTheme.LABEL_NO_MARGIN);
        navbar.addComponent(brand);
        navbar.setComponentAlignment(brand, Alignment.MIDDLE_LEFT);
        navbar.setExpandRatio(brand, 1);
        btnHome = new Button("Home", FontAwesome.HOME);
        btnHome.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        btnHome.setData(ViewToken.HOME);
        btnHome.addClickListener(this);
        navbar.addComponent(btnHome);
        btnUser = new Button("User home", FontAwesome.USER);
        btnUser.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        btnUser.setData(ViewToken.USER);
        btnUser.addClickListener(this);
        navbar.addComponent(btnUser);
        btnAdmin = new Button("Admin home", FontAwesome.USER_MD);
        btnAdmin.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        btnAdmin.setData(ViewToken.ADMIN);
        btnAdmin.addClickListener(this);
        navbar.addComponent(btnAdmin);
        btnAdminHidden = new Button("Admin secret", FontAwesome.EYE_SLASH);
        btnAdminHidden.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        btnAdminHidden.setData(ViewToken.ADMIN_HIDDEN);
        btnAdminHidden.addClickListener(this);
        navbar.addComponent(btnAdminHidden);
        btnSignIn = new Button("Sign in", FontAwesome.SIGN_IN);
        btnSignIn.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        btnSignIn.setData(ViewToken.SIGNIN);
        btnSignIn.addClickListener(this);
        navbar.addComponent(btnSignIn);
        btnSignUp = new Button("Sign up", FontAwesome.PENCIL_SQUARE_O);
        btnSignUp.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        btnSignUp.setData(ViewToken.SIGNUP);
        btnSignUp.addClickListener(this);
        navbar.addComponent(btnSignUp);
        btnLogout = new Button("Logout", FontAwesome.SIGN_OUT);
        btnLogout.setData("-");
        btnLogout.addStyleName(ValoTheme.BUTTON_BORDERLESS);
        navbar.addComponent(btnLogout);
        btnLogout.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                logout();
            }
        });
        viewContainer = new Panel();
        viewContainer.setSizeFull();
        addComponent(viewContainer);
        setExpandRatio(viewContainer, 1);
    }

    @PreDestroy
    public void preDestroy() {
        eventBus.unsubscribe(this);
    }

    @Override
    public void showView(View view) {
        if (security.hasAuthority("ROLE_USER")) {
            displayUserNavbar();
        } else if (security.hasAuthority("ROLE_ADMIN")) {
            displayAdminNavbar();
        } else {
            displayAnonymousNavbar();
        }
        if (view instanceof MvpPresenterView) {
            viewContainer.setContent(((MvpPresenterView) view).getViewComponent());
        }
    }

    private void logout() {
        AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken(key, "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
        final SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authenticationToken);
        UI.getCurrent().getNavigator().navigateTo(ViewToken.HOME);
        eventBus.publish(EventScope.UI, this, new UserSignedOutEvent());
    }

    @Override
    public void buttonClick(ClickEvent event) {
        UI.getCurrent().getNavigator().navigateTo((String) event.getButton().getData());
    }

    @Override
    public boolean beforeViewChange(ViewChangeEvent event) {
        return true;
    }

    @Override
    public void afterViewChange(ViewChangeEvent event) {
        for (int i = 0; i < navbar.getComponentCount(); i++) {
            if (navbar.getComponent(i) instanceof Button) {
                final Button btn = (Button) navbar.getComponent(i);
                btn.removeStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
                String view = (String) btn.getData();
                if (event.getViewName().equals(view)) {
                    btn.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
                }
            }
        }
    }

    private void displayAnonymousNavbar() {
        btnAdminHidden.setVisible(false);
        btnLogout.setVisible(false);
        btnSignIn.setVisible(true);
        btnSignUp.setVisible(true);
    }

    private void displayUserNavbar() {
        btnAdminHidden.setVisible(false);
        btnLogout.setVisible(true);
        btnSignIn.setVisible(false);
        btnSignUp.setVisible(false);
    }

    private void displayAdminNavbar() {
        btnAdminHidden.setVisible(true);
        btnLogout.setVisible(true);
        btnSignIn.setVisible(false);
        btnSignUp.setVisible(false);
    }

    @EventBusListenerMethod
    public void onAccessDenied(org.vaadin.spring.events.Event<AccessDeniedEvent> event) {
        // TODO Redirect to login,
        if (event.getPayload().getCause() != null) {
            Notification.show("Access is denied.", "Service can be invoked only by Admin users.", Type.ERROR_MESSAGE);
        } else {
            if (event.getPayload().getViewToken().equals(ViewToken.USER)) {
                Notification.show("Access is denied.", "You must sign in before accessing User home.", Type.ERROR_MESSAGE);
            } else {
                Notification.show("Access is denied.", "You must sign in as Admin user before accessing Admin home.", Type.ERROR_MESSAGE);
            }
        }
    }
}

11 View Complete Implementation : SpringSecurityErrorHandler.java
Copyright Apache License 2.0
Author : markoradinovic
public static void doDefault(ErrorEvent event) {
    Throwable t = event.getThrowable();
    if (t instanceof SocketException) {
        // Most likely client browser closed socket
        getLogger().info("SocketException in CommunicationManager." + " Most likely client (browser) closed socket.");
        return;
    }
    t = findRelevantThrowable(t);
    /*
         * Handle SpringSecurity 
         */
    if (t instanceof AccessDeniedException) {
        EventBus eventBus = SpringApplicationContext.getEventBus();
        eventBus.publish(EventScope.UI, eventBus, new AccessDeniedEvent(t));
        getLogger().log(Level.FINE, "Access is denied", t);
        return;
    }
    // Finds the original source of the error/exception
    AbstractComponent component = findAbstractComponent(event);
    if (component != null) {
        // Shows the error in AbstractComponent
        ErrorMessage errorMessage = AbstractErrorMessage.getErrorMessageForException(t);
        component.setComponentError(errorMessage);
    }
    // also print the error on console
    getLogger().log(Level.SEVERE, "", t);
}