Java Code Examples for com.vaadin.ui.UI

The following examples show how to use com.vaadin.ui.UI. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: designer-tutorials   Source File: MainLayout.java    License: Apache License 2.0 6 votes vote down vote up
public MainLayout() {
    Navigator navigator = new Navigator(UI.getCurrent(), contentPanel);
    navigator.addView(StatsView.VIEW_NAME, StatsView.class);
    navigator.addView(PluginsView.VIEW_NAME, PluginsView.class);
    navigator.addView(PermissionsView.VIEW_NAME, PermissionsView.class);

    menuButton1.addClickListener(event -> doNavigate(StatsView.VIEW_NAME));
    menuButton2
            .addClickListener(event -> doNavigate(PluginsView.VIEW_NAME));
    menuButton3.addClickListener(
            event -> doNavigate(PermissionsView.VIEW_NAME));

    if (navigator.getState().isEmpty()) {
        navigator.navigateTo(StatsView.VIEW_NAME);
    } else {
        navigator.navigateTo(navigator.getState());
    }
}
 
Example 2
Source Project: cuba   Source File: UrlTools.java    License: Apache License 2.0 6 votes vote down vote up
public void replaceState(String navigationState, UI ui) {
    checkNotNullArgument(navigationState, "Navigation state cannot be null");

    if (headless()) {
        log.debug("Unable to replace navigation state in headless mode");
        return;
    }

    String state = !navigationState.isEmpty()
            ? "#" + navigationState
            : "";

    Page page = ui.getPage();
    if (!state.isEmpty()) {
        page.replaceState(state);
    } else {
        page.replaceState(getEmptyFragmentUri(page));
    }
}
 
Example 3
Source Project: hawkbit   Source File: TargetTable.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void openConfirmationWindowForAssignments(final Target target,
        final List<DistributionSet> distributionSets) {

    final String confirmationMessage = getConfirmationMessage(target, distributionSets);
    final String caption = getI18n().getMessage(CAPTION_ENTITY_ASSIGN_ACTION_CONFIRMBOX);
    final String okLabel = getI18n().getMessage(UIMessageIdProvider.BUTTON_OK);
    final String cancelLabel = getI18n().getMessage(UIMessageIdProvider.BUTTON_CANCEL);

    confirmDialog = new ConfirmationDialog(caption, confirmationMessage, okLabel, cancelLabel, ok -> {
        if (ok && isMaintenanceWindowValid(maintenanceWindowLayout, getNotification())) {
            saveAllAssignments(Collections.singletonList(target), distributionSets, managementUIState,
                    actionTypeOptionGroupLayout, maintenanceWindowLayout, deploymentManagement, getNotification(),
                    getEventBus(), getI18n(), this);
        }
    }, createAssignmentTab(actionTypeOptionGroupLayout, maintenanceWindowLayout, saveButtonToggle(), getI18n(),
            uiProperties), UIComponentIdProvider.DIST_SET_TO_TARGET_ASSIGNMENT_CONFIRM_ID);

    UI.getCurrent().addWindow(confirmDialog.getWindow());
    confirmDialog.getWindow().bringToFront();
}
 
Example 4
@Override
protected void postInitView() {
    super.postInitView();

    view.getPopupActionHandlers().setMassActionHandler(new DefaultMassEditActionHandler(this) {
        @Override
        protected void onSelectExtra(String id) {
            if (ViewItemAction.MAIL_ACTION.equals(id)) {
                UI.getCurrent().addWindow(new MailFormWindow());
            }
        }

        @Override
        protected String getReportTitle() {
            return UserUIContext.getMessage(ComponentI18nEnum.LIST);
        }

        @Override
        protected Class<?> getReportModelClassType() {
            return SimpleComponent.class;
        }
    });
}
 
Example 5
Source Project: context-menu   Source File: ContextMenu.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void beforeClientResponse(boolean initial) {
    super.beforeClientResponse(initial);
    UI uI = getUI();
    if (uI != null && uI.getConnectorTracker().isDirty(this)) {

        /*
         * This should also be used by MenuBar, upgrading it from Vaadin 6
         * to Vaadin 7 communication mechanism. Thus to be moved e.g. to the
         * AbstractMenu.
         */
        ContextMenuState menuSharedState = getState();
        itemById = new HashMap<>();
        menuSharedState.menuItems = convertItemsToState(getItems(),
                itemById);
    }
}
 
Example 6
Source Project: hawkbit   Source File: ActionHistoryGrid.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Show confirmation window and if ok then only, force quit action.
 *
 * @param actionId
 *            as Id if the action needs to be forced.
 */
private void confirmAndForceQuitAction(final Long actionId) {
    /* Display the confirmation */
    final ConfirmationDialog confirmDialog = new ConfirmationDialog(
            i18n.getMessage("caption.forcequit.action.confirmbox"),
            i18n.getMessage("message.forcequit.action.confirm"), i18n.getMessage(UIMessageIdProvider.BUTTON_OK),
            i18n.getMessage(UIMessageIdProvider.BUTTON_CANCEL), ok -> {
                if (!ok) {
                    return;
                }
                final boolean cancelResult = forceQuitActiveAction(actionId);
                if (cancelResult) {
                    populateAndUpdateTargetDetails(selectedTarget);
                    notification.displaySuccess(i18n.getMessage("message.forcequit.action.success"));
                } else {
                    notification.displayValidationError(i18n.getMessage("message.forcequit.action.failed"));
                }
            }, FontAwesome.WARNING, UIComponentIdProvider.CONFIRMATION_POPUP_ID, null);
    UI.getCurrent().addWindow(confirmDialog.getWindow());

    confirmDialog.getWindow().bringToFront();
}
 
Example 7
Source Project: hawkbit   Source File: UploadProgressInfoWindow.java    License: Eclipse Public License 1.0 6 votes vote down vote up
UploadProgressInfoWindow(final UIEventBus eventBus, final ArtifactUploadState artifactUploadState,
        final VaadinMessageSource i18n) {
    this.artifactUploadState = artifactUploadState;
    this.i18n = i18n;

    setPopupProperties();
    createStatusPopupHeaderComponents();

    mainLayout = new VerticalLayout();
    mainLayout.setSpacing(Boolean.TRUE);
    mainLayout.setSizeUndefined();
    setPopupSizeInMinMode();

    uploads = getGridContainer();
    grid = createGrid();
    setGridColumnProperties();

    mainLayout.addComponents(getCaptionLayout(), grid);
    mainLayout.setExpandRatio(grid, 1.0F);
    setContent(mainLayout);
    eventBus.subscribe(this);
    ui = UI.getCurrent();
}
 
Example 8
/**
 * Click politician test.
 */
@Test
public void clickPoliticianTest() {
	final ComplianceCheckPageItemRendererClickListener listener = new ComplianceCheckPageItemRendererClickListener();
	final UI uiMock = Mockito.mock(UI.class);
	UI.setCurrent(uiMock);
	
	final Navigator navigatorMock = Mockito.mock(Navigator.class);
	Mockito.when(uiMock.getNavigator()).thenReturn(navigatorMock);		
			
	final RendererClickEvent event = Mockito.mock(RendererClickEvent.class);
	Mockito.when(event.getItem()).thenReturn(new PoliticianComplianceCheckImpl(new ViewRiksdagenPolitician().withPersonId("personid"), null, null, null));
		
	listener.click(event);
	
	Mockito.verify(navigatorMock, times(1)).navigateTo("politician/personid");
}
 
Example 9
Source Project: hawkbit   Source File: ArtifactDetailsLayout.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@EventBusListenerMethod(scope = EventScope.UI)
void onEvent(final SoftwareModuleEvent softwareModuleEvent) {
    if (softwareModuleEvent.getEventType() == BaseEntityEventType.SELECTED_ENTITY) {
        UI.getCurrent().access(() -> {
            if (softwareModuleEvent.getEntity() != null) {
                populateArtifactDetails(softwareModuleEvent.getEntity());
            } else {
                populateArtifactDetails(null, null);
            }
        });
    }
    if (isArtifactChangedEvent(softwareModuleEvent) && areEntityIdsNotEmpty(softwareModuleEvent)) {
        UI.getCurrent().access(() -> findSelectedSoftwareModule().ifPresent(selectedSoftwareModule -> {
            if (hasSelectedSoftwareModuleChanged(softwareModuleEvent.getEntityIds(), selectedSoftwareModule)) {
                populateArtifactDetails(selectedSoftwareModule);
            }
        }));
    }
}
 
Example 10
Source Project: XACML   Source File: JPAUtils.java    License: MIT License 5 votes vote down vote up
public static Datatype	findDatatype(int datatypeId) {
	JPAContainer<Datatype> datatypes =  ((XacmlAdminUI)UI.getCurrent()).getDatatypes();
	
	for (Object id : datatypes.getItemIds()) {
		Datatype d = datatypes.getItem(id).getEntity();
		if (d.getId() == datatypeId) {
			return d;
		}
	}		
	return null;
}
 
Example 11
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());
}
 
Example 12
Source Project: vertx-vaadin   Source File: VaadinVerticle.java    License: MIT License 5 votes vote down vote up
private void readUiFromEnclosingClass(JsonObject vaadinConfig) {
    Class<?> enclosingClass = getClass().getEnclosingClass();

    if (enclosingClass != null && UI.class.isAssignableFrom(enclosingClass)) {
        vaadinConfig.put(VaadinSession.UI_PARAMETER, enclosingClass.getName());
    }
}
 
Example 13
Source Project: jdal   Source File: VaadinUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Exit application
 */
public static void exit() {
	VaadinSession.getCurrent().getSession().removeAttribute(
			HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
	UI.getCurrent().close();
	VaadinSession.getCurrent().close();
	Page page = Page.getCurrent();
	page.setLocation(VaadinService.getCurrentRequest().getContextPath() + "/logout"); 
}
 
Example 14
Source Project: vertx-vaadin   Source File: SockJSPushHandler.java    License: MIT License 5 votes vote down vote up
private static UI findUiUsingSocket(PushSocket socket, Collection<UI> uIs) {
    for (UI ui : uIs) {
        PushConnection pushConnection = ui.getPushConnection();
        if (pushConnection instanceof SockJSPushConnection &&
            ((SockJSPushConnection) pushConnection).getSocket() == socket) {
            return ui;
        }
    }
    return null;
}
 
Example 15
Source Project: XACML   Source File: JPAUtils.java    License: MIT License 5 votes vote down vote up
public static Category	findCategory(Identifier cat) {
	JPAContainer<Category> categories = ((XacmlAdminUI)UI.getCurrent()).getCategories();
	for (Object id : categories.getItemIds()) {
		Category c = categories.getItem(id).getEntity();
		if (c.getIdentifer().equals(cat)) {
			return c;
		}
	}
	return null;
}
 
Example 16
Source Project: hawkbit   Source File: TargetFilterQueryButtons.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@EventBusListenerMethod(scope = EventScope.UI)
void onEvent(final CustomFilterUIEvent filterEvent) {
  if (filterEvent == CustomFilterUIEvent.CREATE_TARGET_FILTER_QUERY ||
      filterEvent == CustomFilterUIEvent.UPDATED_TARGET_FILTER_QUERY ||
      filterEvent == CustomFilterUIEvent.REMOVE_TARGET_FILTERQUERY) {
    UI.getCurrent().access(this::refreshContainer);
  }
  if (filterEvent == CustomFilterUIEvent.REMOVE_TARGET_FILTERQUERY) {
    customTargetTagFilterButtonClick.clearAppliedTargetFilterQuery();
  } else if (filterEvent == CustomFilterUIEvent.UPDATED_TARGET_FILTER_QUERY) {
    this.eventBus.publish(this, ManagementUIEvent.REFRESH_TARGETS_ON_FILTER_UPDATE);
  }
}
 
Example 17
Source Project: cuba   Source File: DefaultApp.java    License: Apache License 2.0 5 votes vote down vote up
protected void redirectAfterLogout(String loggedOutUrl) {
    if (!Strings.isNullOrEmpty(loggedOutUrl)) {
        AppUI currentUi = AppUI.getCurrent();
        // it can be null if we handle request in a custom RequestHandler
        if (currentUi != null) {
            currentUi.setContent(null);
            currentUi.getPage().setLocation(loggedOutUrl);
        } else {
            VaadinResponse response = VaadinService.getCurrentResponse();
            try {
                ((VaadinServletResponse) response).getHttpServletResponse().
                        sendRedirect(loggedOutUrl);
            } catch (IOException e) {
                log.error("Error on send redirect to client", e);
            }
        }

        VaadinSession vaadinSession = VaadinSession.getCurrent();
        for (UI ui : vaadinSession.getUIs()) {
            if (ui != currentUi) {
                ui.access(() -> {
                    ui.setContent(null);
                    ui.getPage().setLocation(loggedOutUrl);
                });
            }
        }
    }
}
 
Example 18
Source Project: cuba   Source File: App.java    License: Apache License 2.0 5 votes vote down vote up
public List<AppUI> getAppUIs() {
    List<AppUI> list = new ArrayList<>();
    for (UI ui : VaadinSession.getCurrent().getUIs()) {
        if (ui instanceof AppUI)
            list.add((AppUI) ui);
        else
            log.warn("Invalid UI in the session: {}", ui);
    }
    return list;
}
 
Example 19
Source Project: hawkbit   Source File: DistributionSetTable.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@EventBusListenerMethod(scope = EventScope.UI)
void onDistributionSetUpdateEvents(final DistributionSetUpdatedEventContainer eventContainer) {
    @SuppressWarnings("unchecked")
    final List<Long> visibleItemIds = (List<Long>) getVisibleItemIds();
    updateVisableTableEntries(eventContainer.getEvents(), visibleItemIds);
    handleSelectedAndUpdatedDs(eventContainer.getEvents());
}
 
Example 20
@Override
protected Component initContent() {
    ticketField = new MTextField().withReadOnly(true).withWidth(WebThemes.FORM_CONTROL_WIDTH);
    MHorizontalLayout layout = new MHorizontalLayout();
    MButton browseBtn = new MButton(VaadinIcons.ELLIPSIS_H)
            .withListener(clickEvent -> UI.getCurrent().addWindow(new TicketSelectionWindow(TicketRelationSelectField.this)))
            .withStyleName(WebThemes.BUTTON_OPTION, WebThemes.BUTTON_SMALL_PADDING);
    layout.with(ticketField, browseBtn);
    return layout;
}
 
Example 21
Source Project: hawkbit   Source File: TargetTable.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@EventBusListenerMethod(scope = EventScope.UI)
void onEvent(final TargetFilterEvent filterEvent) {
    UI.getCurrent().access(() -> {
        if (checkFilterEvent(filterEvent)) {
            refreshFilter();
            getEventBus().publish(this, ManagementUIEvent.TARGET_TABLE_FILTER);
        }
    });
}
 
Example 22
Source Project: cuba   Source File: CubaUI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if users can interact with the component - there are no modal windows that prevent user action.
 *
 * @param component component
 * @return whether it accessible or not
 */
public boolean isAccessibleForUser(Component component) {
    Collection<Window> windows = this.getWindows();
    if (windows.isEmpty()) {
        // there are no windows - all components are accessible
        return true;
    }

    boolean hasModalWindows = windows.stream().anyMatch(Window::isModal);
    if (!hasModalWindows) {
        // there are no modal windows - all components are accessible
        return true;
    }

    Component windowOrUI = CubaUIUtils.getWindowOrUI(component);
    if (windowOrUI == null) {
        // something went wrong
        return false;
    }

    if (windowOrUI instanceof UI) {
        // there are modal windows, component belongs to UI
        return false;
    }

    if (windowOrUI instanceof Window) {
        Window currentWindow = (Window) windowOrUI;

        if (!currentWindow.isModal()) {
            // there are modal windows, component belongs to non-modal window
            return false;
        }

        // CAUTION we cannot sort windows in UI, because they are ordered only on client side
    }

    // we cannot reliably check if access is permitted
    return true;
}
 
Example 23
Source Project: grpc-by-example-java   Source File: ChatUI.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {

  final UI currentUI = getCurrent();
  final StreamObserver<Chat.ChatMessage> observer = stub.chat(new StreamObserver<Chat.ChatMessageFromServer>() {
    @Override
    public void onNext(Chat.ChatMessageFromServer chatMessageFromServer) {
      currentUI.access(() -> layout.addComponent(new Label(String.format("%s: %s" ,
                                                                         chatMessageFromServer.getMessage().getFrom() ,
                                                                         chatMessageFromServer.getMessage().getMessage()))));
    }

    @Override
    public void onError(Throwable throwable) {
      logger.log(Level.SEVERE , "gRPC Error" , throwable);
    }

    @Override
    public void onCompleted() {
      logger.info("gRPC Call Completed");
    }
  });

  button.addClickListener(e -> {

    final String nameValue = name.getValue();
    final String messageValue = message.getValue();

    observer.onNext(Chat.ChatMessage.newBuilder()
                                    .setFrom(nameValue)
                                    .setMessage(messageValue)
                                    .build());
  });

}
 
Example 24
Source Project: XACML   Source File: JPAUtils.java    License: MIT License 5 votes vote down vote up
public static Datatype	findDatatype(Identifier dt) {
	JPAContainer<Datatype> datatypes =  ((XacmlAdminUI)UI.getCurrent()).getDatatypes();
	
	for (Object id : datatypes.getItemIds()) {
		Datatype d = datatypes.getItem(id).getEntity();
		if (d.getIdentifer().equals(dt)) {
			return d;
		}
	}		
	return null;
}
 
Example 25
/**
 * Default implementation to handle an entity event.
 *
 * @param baseEntityEvent
 *            the event
 */
protected void onBaseEntityEvent(final BaseUIEntityEvent<T> baseEntityEvent) {
    final BaseEntityEventType eventType = baseEntityEvent.getEventType();
    if (BaseEntityEventType.SELECTED_ENTITY == eventType || BaseEntityEventType.UPDATED_ENTITY == eventType
            || BaseEntityEventType.REMOVE_ENTITY == eventType) {
        UI.getCurrent().access(() -> populateData(baseEntityEvent.getEntity()));
    } else if (BaseEntityEventType.MINIMIZED == eventType) {
        UI.getCurrent().access(() -> setVisible(true));
    } else if (BaseEntityEventType.MAXIMIZED == eventType) {
        UI.getCurrent().access(() -> setVisible(false));
    }
}
 
Example 26
Source Project: hawkbit   Source File: RolloutListGrid.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles the RolloutEvent to refresh Grid.
 *
 */
@EventBusListenerMethod(scope = EventScope.UI)
void onEvent(final RolloutEvent event) {
    switch (event) {
    case FILTER_BY_TEXT:
    case CREATE_ROLLOUT:
    case UPDATE_ROLLOUT:
    case SHOW_ROLLOUTS:
        refreshContainer();
        break;
    default:
        break;
    }
}
 
Example 27
Source Project: hawkbit   Source File: AbstractTagToken.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected void onBaseEntityEvent(final BaseUIEntityEvent<T> baseEntityEvent) {
    if (BaseEntityEventType.SELECTED_ENTITY != baseEntityEvent.getEventType()) {
        return;
    }
    UI.getCurrent().access(() -> {
        final T entity = baseEntityEvent.getEntity();
        if (entity != null) {
            selectedEntity = entity;
            repopulateTags();
        }
    });
}
 
Example 28
Source Project: XACML   Source File: JPAUtils.java    License: MIT License 5 votes vote down vote up
private static void buildFunctionMaps() {
	mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
	mapID2Function = new HashMap<String, FunctionDefinition>();
	JPAContainer<FunctionDefinition> functions = ((XacmlAdminUI)UI.getCurrent()).getFunctionDefinitions();
	for (Object id : functions.getItemIds()) {
		FunctionDefinition value = functions.getItem(id).getEntity();
		mapID2Function.put(value.getXacmlid(), value);
		if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
			mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
		}
		mapDatatype2Function.get(value.getDatatypeBean()).add(value);
	}
}
 
Example 29
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);
}
 
Example 30
Source Project: hawkbit   Source File: TargetTableHeader.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addNewItem(final ClickEvent event) {
    targetAddUpdateWindow.resetComponents();
    final Window addTargetWindow = targetAddUpdateWindow.createNewWindow();
    addTargetWindow.setCaption(i18n.getMessage("caption.create.new", i18n.getMessage("caption.target")));
    UI.getCurrent().addWindow(addTargetWindow);
    addTargetWindow.setVisible(Boolean.TRUE);
}