Java Code Examples for com.vaadin.server.VaadinRequest

The following are top voted examples for showing how to use com.vaadin.server.VaadinRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AllAboutGridWebinar   File: AllAboutGridUI.java   Source Code and License 7 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    Grid grid = new Grid();

    initializeGrid(grid);
    grid.setWidth("700px");
    grid.setHeight("500px");

    applyDemoHacks(grid);

    layout.addComponent(grid);
}
 
Example 2
Project: spring-boot-plugins-example   File: VaadinUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	final VerticalLayout root = new VerticalLayout();
	root.setSizeFull();
	root.setMargin(true);
	root.setSpacing(true);
	setContent(root);
	MHorizontalLayout horizontalLayout = new MHorizontalLayout();
	for (MenuEntry menuEntry : menuEntries) {
		horizontalLayout.addComponent(new MButton(menuEntry.getName(), event -> {
			navigator.navigateTo(menuEntry.getNavigationTarget());
		}));
	}
	root.addComponent(horizontalLayout);
	springViewDisplay = new Panel();
	springViewDisplay.setSizeFull();
	root.addComponent(springViewDisplay);
	root.setExpandRatio(springViewDisplay, 1.0f);

}
 
Example 3
Project: svgexamples   File: MyUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    setNavigator(new Navigator(this, (View view) -> {
        tabs.setSelectedTab((Component) view);
    }));

    registerExample(SvgInVaadin.class);
    registerExample(SimplyAsAnImageOrIcon.class);
    registerExample(FileExample.class);
    registerExample(AnimationExample.class);
    registerExample(Java2DExample.class);
    registerExample(JungExample.class);

    getNavigator().setErrorView(SvgInVaadin.class);
    tabs.addSelectedTabChangeListener(e -> {
        if (e.isUserOriginated()) {
            getNavigator().navigateTo(e.getTabSheet().getSelectedTab().getClass().getSimpleName());
        }
    });
    String state = getNavigator().getState();
    getNavigator().navigateTo(state);

    tabs.addStyleName(ValoTheme.TABSHEET_PADDED_TABBAR);
    setContent(tabs);
}
 
Example 4
Project: spring-boot-vaadin-rabbitmq-pipeline-demo   File: NavigatorUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    final VerticalLayout rootLayout = new VerticalLayout();
    rootLayout.setSizeFull();
    setContent(rootLayout);

    final CssLayout navigationBar = new CssLayout();
    navigationBar.addStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    navigationBar.addComponent(createNavigationButton("Demo View (Default)",
            Constants.VIEW_DEFAULT));
    navigationBar.addComponent(createNavigationButton("Stream View",
            Constants.VIEW_STREAM));
    rootLayout.addComponent(navigationBar);

    springViewDisplay = new Panel();
    springViewDisplay.setSizeFull();
    
    rootLayout.addComponent(springViewDisplay);
    rootLayout.setExpandRatio(springViewDisplay, 1.0f);

}
 
Example 5
Project: vaadin-binders   File: BinderUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    // crate a binder for a form, specifying the data class that will be used in binding
    Binder<ImageData> binder = new Binder<>(ImageData.class);

    // specify explicit binding in order to add validation and converters
    binder.forMemberField(imageSize)
            // input should not be null or empty
            .withValidator(string -> string != null && !string.isEmpty(), "Input values should not be empty")
            // convert String to Integer, throw ValidationException if String is in incorrect format
            .withConverter(new StringToIntegerConverter("Input value should be an integer"))
            // validate converted integer: it should be positive
            .withValidator(integer -> integer > 0, "Input value should be a positive integer");

    // tell binder to bind use all fields from the current class, but considering already existing bindings
    binder.bindInstanceFields(this);

    // crate data object with predefined imageName and imageSize
    ImageData imageData = new ImageData("Lorem ipsum", 2);

    // fill form with predefined data from data object and
    // make binder to automatically update the object from the form, if no validation errors are present
    binder.setBean(imageData);

    binder.addStatusChangeListener(e -> {
        // the real image drawing will not be considered in this article

        if (e.hasValidationErrors() || !e.getBinder().isValid()) {
            Notification.show("Form contains validation errors, no image will be drawn");
        } else {
            Notification.show(String.format("I will draw image with \"%s\" text and width %d\n",
                    imageData.getText(), imageData.getSize()));
        }
    });

    // add a form to layout
    setContent(new VerticalLayout(text, imageSize));
}
 
Example 6
Project: esup-ecandidat   File: OnDemandFileDownloader.java   Source Code and License 6 votes vote down vote up
@Override
public boolean handleConnectorRequest(VaadinRequest request,
		VaadinResponse response, String path) throws IOException {		
	final BusyIndicatorWindow busyIndicatorWindow = new BusyIndicatorWindow();
	final UI ui = UI.getCurrent();
	ui.access(() -> ui.addWindow(busyIndicatorWindow));
	try {
		//on charge le fichier
		getStreamSource().loadOndemandFile();
		if (getStreamSource().getStream()==null){
			return true;
		}
		getResource().setFilename(getStreamSource().getFileName());
		return super.handleConnectorRequest(request, response, path);
	}catch(Exception e){
		return true;
	}
	finally {
		busyIndicatorWindow.close();
	}		
}
 
Example 7
Project: esup-ecandidat   File: OnDemandPdfBrowserOpener.java   Source Code and License 6 votes vote down vote up
@Override
public boolean handleConnectorRequest(VaadinRequest request,
		VaadinResponse response, String path) throws IOException {		
	final BusyIndicatorWindow busyIndicatorWindow = new BusyIndicatorWindow();
	final UI ui = UI.getCurrent();
	ui.access(() -> ui.addWindow(busyIndicatorWindow));
	try {
		getStreamSource().loadOndemandFile();
		if (getStreamSource().getStream()==null){
			return true;
		}
		getDownloadStreamSource().setMIMEType("application/pdf");
		getDownloadStreamSource().getStream().setParameter(
                "Content-Disposition",
                "attachment; filename="+getStreamSource().getFileName());
		return super.handleConnectorRequest(request, response, path);
	}catch(Exception e){
		return true;
	}finally {
		busyIndicatorWindow.close();
	}		
}
 
Example 8
Project: tinypounder   File: TinyPounderMainUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
  VaadinSession.getCurrent().getSession().setMaxInactiveInterval(-1);
  Page.getCurrent().setTitle("Tiny Pounder (" + VERSION + ")");

  setupLayout();
  addKitControls();
  updateKitControls();
  initVoltronConfigLayout();
  initVoltronControlLayout();
  initRuntimeLayout();
  addExitCloseTab();
  updateServerGrid();

  // refresh consoles if any
  consoleRefresher = scheduledExecutorService.scheduleWithFixedDelay(
      () -> access(() -> runningServers.values().forEach(RunningServer::refreshConsole)),
      2, 2, TimeUnit.SECONDS);
}
 
Example 9
Project: material-theme-fw8   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    root = new CssLayout(appBar, navigationDrawer, content);
    root.setPrimaryStyleName("root");
    root.setSizeFull();
    Responsive.makeResponsive(root);
    setContent(root);

    appBar.getNaviIcon().addClickListener(event -> navigationDrawer.toggle());

    content.setPrimaryStyleName("content");
    content.setSizeFull();

    initNavigationItems();
    initDummyContent();
}
 
Example 10
Project: md-stepper   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
  rootLayout = getRootLayout();
  setContent(rootLayout);

  Label title = getTitleLabel();

  StepperPropertiesLayout layout = new StepperPropertiesLayout();
  layout.addStepperCreateListener(this);
  layout.setWidth(300, Unit.PIXELS);

  Spacer spacer = new Spacer();
  spacer.setWidth(100, Unit.PIXELS);

  rootLayout.addComponent(title, 0, 0, 2, 0);
  rootLayout.addComponent(spacer, 1, 1);
  rootLayout.addComponent(layout, 0, 1);
  rootLayout.setComponentAlignment(title, Alignment.MIDDLE_CENTER);

  layout.start();
}
 
Example 11
Project: vaadin-javaee-jaas-example   File: JaasExampleUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout contentArea = new VerticalLayout();
    contentArea.setMargin(false);
    setContent(contentArea);

    final Navigator navigator = new Navigator(this, contentArea);
    navigator.addProvider(viewProvider);
    navigator.setErrorView(InaccessibleErrorView.class);

    String defaultView = Page.getCurrent().getUriFragment();
    if (defaultView == null || defaultView.trim().isEmpty()) {
        defaultView = SecureView.VIEW_NAME;
    }

    if (isUserAuthenticated(vaadinRequest)) {
        navigator.navigateTo(defaultView);
    } else {
        navigator.navigateTo(LoginView.VIEW_NAME + "/" + defaultView);
    }
}
 
Example 12
Project: bean-grid   File: TestUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	setSizeFull();

	VerticalLayout layout = new VerticalLayout();
	layout.setSizeFull();
	layout.setMargin(true);

	testGrid.setSizeFull();
	testGrid.getEditor().setEnabled(true);

	testGrid.setItems(getCustomers());

	layout.addComponent(testGrid);

	setContent(layout);
}
 
Example 13
Project: vaadin-karaf   File: MyUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
	final VerticalLayout layout = new VerticalLayout();

	final TextField name = new TextField();
	name.setCaption("Type your name here:");

	Button button = new Button("Click Me");
	button.addClickListener(e -> {
		layout.addComponent(new Label("Thanks " + name.getValue() + ", it works!"));
	});

	layout.addComponents(name, button);

	setContent(layout);
}
 
Example 14
Project: live-image-editor   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    Label title = new Label("Live Image Editor add-on for Vaadin");
    title.addStyleName(ValoTheme.LABEL_H2);
    title.addStyleName(ValoTheme.LABEL_COLORED);

    instructions.setContentMode(ContentMode.HTML);
    instructions.setWidth(600, Unit.PIXELS);

    upload.addSucceededListener(this::uploadSucceeded);

    imageEditor.setWidth(100, Unit.PERCENTAGE);
    imageEditor.setBackgroundColor(0, 52, 220);

    VerticalLayout layout = new VerticalLayout(title, upload, instructions, imageEditor, send, result, editedImage);
    layout.setSizeUndefined();
    layout.setMargin(true);
    layout.setSpacing(true);
    setContent(layout);

    setupUploadStep();
}
 
Example 15
Project: imotSpot   File: DashboardUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(final VaadinRequest request) {
    setLocale(Locale.US);

    DashboardEventBus.register(this);
    Responsive.makeResponsive(this);
    addStyleName(ValoTheme.UI_WITH_MENU);

    updateContent();

    // Some views need to be aware of browser resize events so a
    // BrowserResizeEvent gets fired to the event bus on every occasion.
    Page.getCurrent().addBrowserWindowResizeListener(
            new BrowserWindowResizeListener() {
                @Override
                public void browserWindowResized(
                        final BrowserWindowResizeEvent event) {
                    DashboardEventBus.post(new BrowserResizeEvent());
                }
            });
}
 
Example 16
Project: garantia   File: LoginUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	log.info("Levanto la pagina UI");
	
	final VerticalLayout root = new VerticalLayout();
       root.setSizeFull();
       root.setMargin(true);
       root.setSpacing(true);
       setContent(root);
	
       final Panel viewContainer = new Panel();
       viewContainer.setSizeFull();
       root.addComponent(viewContainer);
       root.setExpandRatio(viewContainer, 1.0f);
       
       Navigator navigator = new Navigator(this, viewContainer);
       //Navigator navigator = new Navigator(this, this);
       navigator.addProvider(viewProvider);
       
       log.info("Termina de levantar la pagina UI");

}
 
Example 17
Project: vaadin-vertx-samples   File: VertxVaadinService.java   Source Code and License 6 votes vote down vote up
@Override
public String getStaticFileLocation(VaadinRequest request) {
    String staticFileLocation;
    // if property is defined in configurations, use that
    staticFileLocation = getDeploymentConfiguration().getResourcesPath();
    if (staticFileLocation != null) {
        return staticFileLocation;
    }

    VertxVaadinRequest vertxRequest = (VertxVaadinRequest) request;
    String requestedPath = vertxRequest.getRequest().path()
        .substring(
            Optional.ofNullable(vertxRequest.getRoutingContext().mountPoint())
                .map(String::length).orElse(0)
        );
    return VaadinServletService.getCancelingRelativePath(requestedPath);
}
 
Example 18
Project: vaadin-vertx-samples   File: VertxVaadinService.java   Source Code and License 6 votes vote down vote up
@Override
public String getMainDivId(VaadinSession session, VaadinRequest request, Class<? extends UI> uiClass) {
    String appId = request.getPathInfo();
    if (appId == null || "".equals(appId) || "/".equals(appId)) {
        appId = "ROOT";
    }
    appId = appId.replaceAll("[^a-zA-Z0-9]", "");
    // Add hashCode to the end, so that it is still (sort of)
    // predictable, but indicates that it should not be used in CSS
    // and
    // such:
    int hashCode = appId.hashCode();
    if (hashCode < 0) {
        hashCode = -hashCode;
    }
    appId = appId + "-" + hashCode;
    return appId;
}
 
Example 19
Project: vaadin-vertx-samples   File: SimpleUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {

    VertxVaadinRequest req = (VertxVaadinRequest) request;
    Cookie cookie = new Cookie("myCookie", "myValue");
    cookie.setMaxAge(120);
    cookie.setPath(req.getContextPath());
    VaadinService.getCurrentResponse().addCookie(cookie);

    Label sessionAttributeLabel = new MLabel().withCaption("Session listener");


    String deploymentId = req.getService().getVertx().getOrCreateContext().deploymentID();

    setContent(new MVerticalLayout(
        new Header("Vert.x Vaadin Sample").setHeaderLevel(1),
        new Label(String.format("Verticle %s deployed on Vert.x", deploymentId)),
        new Label("Session created at " + Instant.ofEpochMilli(req.getWrappedSession().getCreationTime())),
        sessionAttributeLabel
    ).withFullWidth());
}
 
Example 20
Project: vaadin-vertx-samples   File: DashboardUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(final VaadinRequest request) {
    setLocale(Locale.US);

    DashboardEventBus.register(this);
    Responsive.makeResponsive(this);
    addStyleName(ValoTheme.UI_WITH_MENU);

    updateContent();

    // Some views need to be aware of browser resize events so a
    // BrowserResizeEvent gets fired to the event bus on every occasion.
    Page.getCurrent().addBrowserWindowResizeListener(
            new BrowserWindowResizeListener() {
                @Override
                public void browserWindowResized(
                        final BrowserWindowResizeEvent event) {
                    DashboardEventBus.post(new BrowserResizeEvent());
                }
            });
}
 
Example 21
Project: dungeonstory-java   File: DungeonStoryUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    Responsive.makeResponsive(this);
    getPage().setTitle("DungeonStory");

    if (Configuration.getInstance().isMock()) {
        accessControl = new BasicAccessControl();
    } else {
        accessControl = new DsAccessControl();
    }

    setupEventBus();

    if (!accessControl.isUserSignedIn()) {
        setContent(new LoginScreen(accessControl, this::showMainView));
    } else {
        showMainView();
    }

    setLocale(vaadinRequest.getLocale());

    ImageFactory.getInstance();
}
 
Example 22
Project: GridFastNavigation   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    
    initMessageTable();
    
    final Grid grid = new Grid();
    initGrid(grid);
    initNavigation(grid);
    
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.addComponent(grid);
    layout.addComponent(messageTable);
    layout.setSizeFull();
    setContent(layout);
}
 
Example 23
Project: cuba   File: AppUI.java   Source Code and License 6 votes vote down vote up
public void processExternalLink(VaadinRequest request) {
    WrappedSession wrappedSession = request.getWrappedSession();

    String action = (String) wrappedSession.getAttribute(LAST_REQUEST_ACTION_ATTR);

    if (webConfig.getLinkHandlerActions().contains(action)) {
        //noinspection unchecked
        Map<String, String> params =
                (Map<String, String>) wrappedSession.getAttribute(LAST_REQUEST_PARAMS_ATTR);
        params = params != null ? params : Collections.emptyMap();

        try {
            LinkHandler linkHandler = AppBeans.getPrototype(LinkHandler.NAME, app, action, params);
            if (app.connection.isConnected() && linkHandler.canHandleLink()) {
                linkHandler.handle();
            } else {
                app.linkHandler = linkHandler;
            }
        } catch (Exception e) {
            error(new com.vaadin.server.ErrorEvent(e));
        }
    }
}
 
Example 24
Project: cuba   File: ConnectionImpl.java   Source Code and License 6 votes vote down vote up
@Nullable
protected String getUserRemoteAddress() {
    VaadinRequest currentRequest = VaadinService.getCurrentRequest();

    String userRemoteAddress = null;

    if (currentRequest != null) {
        String xForwardedFor = currentRequest.getHeader("X_FORWARDED_FOR");
        if (StringUtils.isNotBlank(xForwardedFor)) {
            String[] strings = xForwardedFor.split(",");
            String userAddressFromHeader = StringUtils.trimToEmpty(strings[strings.length - 1]);

            if (StringUtils.isNotEmpty(userAddressFromHeader)) {
                userRemoteAddress = userAddressFromHeader;
            } else {
                userRemoteAddress = currentRequest.getRemoteAddr();
            }
        } else {
            userRemoteAddress = currentRequest.getRemoteAddr();
        }
    }

    return userRemoteAddress;
}
 
Example 25
Project: relproxy_examples   File: VaadinUIDelegateImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void init(VaadinRequest request) {
					
	final WrappedSession session = request.getWrappedSession();
	
	final VerticalLayout layout = new VerticalLayout();
	layout.setMargin(true);
	parent.setContent(layout);

	Button button = new Button("Click Me");
	button.addClickListener(new Button.ClickListener() {

		public void buttonClick(ClickEvent event) {
			
			Integer counter = (Integer)session.getAttribute("counter");		
			if (counter == null) { counter = 0; }
			counter++;
			session.setAttribute("counter", counter);		
			
			layout.addComponent(new Label("Thank you for clicking, counter:" + counter));			
		}
	});

	layout.addComponent(button);			
}
 
Example 26
Project: hawkbit   File: AbstractHawkbitLoginUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(final VaadinRequest request) {
    SpringContextHelper.setContext(context);

    params = UriComponentsBuilder.fromUri(Page.getCurrent().getLocation()).build().getQueryParams();

    if (params.containsKey(DEMO_PARAMETER)) {
        login(uiProperties.getDemo().getTenant(), uiProperties.getDemo().getUser(),
                uiProperties.getDemo().getPassword(), false);
    }

    setContent(buildContent());

    filloutUsernameTenantFields();
    readCookie();
}
 
Example 27
Project: FontAwesomeRenderer   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {

	// Show it in the middle of the screen
	final VerticalLayout layout = new VerticalLayout();
	layout.setStyleName("demoContentLayout");
	layout.setSizeFull();
	setContent(layout);

	Grid grid = new Grid();

	grid.addColumn("name", String.class).setHeaderCaption("Name");
	grid.addColumn("icon", String.class)
			.setHeaderCaption("icon")
			.setRenderer(new FontIconRenderer(e -> Notification.show(e.toString())));

	grid.getDefaultHeaderRow().join("name", "icon").setText("Brand");

	grid.addRow("Android", FontAwesome.ANDROID.getHtml());
	grid.addRow("Ios", FontAwesome.APPLE.getHtml());
	grid.addRow("Who cares", FontAwesome.WINDOWS.getHtml());
	layout.addComponent(grid);

}
 
Example 28
Project: vaadin-jcrop   File: Jcrop.java   Source Code and License 6 votes vote down vote up
/**
 * initalize a unique RequestHandler
 */
private void initRequestHandler() {
	if (this.requestHandlerUri == null) {
		this.requestHandlerUri = UUID.randomUUID()
				.toString();
		VaadinSession.getCurrent()
				.addRequestHandler(new RequestHandler() {

					@Override
					public boolean handleRequest(final VaadinSession session, final VaadinRequest request, final VaadinResponse response)
							throws IOException {
						if (String.format("/%s", Jcrop.this.requestHandlerUri)
								.equals(request.getPathInfo())) {
							Jcrop.this.resource.getStream()
									.writeResponse(request, response);
							return true;
						} else {
							return false;
						}
					}
				});
	}
}
 
Example 29
Project: KrishnasSpace   File: VaadinUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	final VerticalLayout mainLayout = new VerticalLayout();
	HorizontalLayout horizontalLayout = new HorizontalLayout();
	CssLayout viewLayout = new CssLayout();
	Page.getCurrent().setTitle("Vaadin Demo");
	mainLayout.setSizeFull();
	viewLayout.setSizeFull();
	mainLayout.setMargin(true);
	setContent(mainLayout);
	mainLayout.addComponent(horizontalLayout);
	mainLayout.addComponent(viewLayout);
	mainLayout.setExpandRatio(viewLayout, 1f);
	Navigator navigator = new Navigator(this, viewLayout);
	setNavigator(navigator);
	setupHeader(horizontalLayout);
	Map<String, Class<? extends MyView>> myViews = getViewProvider();
	navigator.addView("", new HomeView(myViews.keySet()));
	navigator.addProvider(new CachedViewProvider(myViews));
}
 
Example 30
Project: StockScreener   File: StockScreenerControlUI.java   Source Code and License 6 votes vote down vote up
@Override
	protected void init(VaadinRequest request) {
		processBtn.addClickListener( e -> { 
			Notification.show("Starting run");
			mainController.launchAnalysis(new AnalysisResultListenerImpl());
		});
		loadHistoricalQuotesBtn.addClickListener(e -> {
			Notification.show("Collecting historical Quotes");
			mainController.loadHistoricalQuotes();
		});
//		initContent0();
//		initContent1();
		initContent2();
		
		initScreen0Grid();
		initControlGrid();
		main.addComponents(screen0Grid,controlGrid);
		main.setWidth("100%");
	}
 
Example 31
Project: Vaadin-Prime-Count   File: Application.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(final VaadinRequest vaadinRequest)
{
    assert null != vaadinRequest : "Parameter 'vaadinRequest' of method 'init' must not be null";

    LOGGER.info("Let's count some primes!");

    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);
    final PrimeCountUserStory userStory = new PrimeCountUserStory(this);
    layout.addComponent(userStory);
    
    /**
     * Add-on developers should note that this method is only meant for
     * the application developer.
     * An add-on should not set the poll interval directly, rather
     * instruct the user to set it.
     */
    setPollInterval(11000);
}
 
Example 32
Project: vanilla   File: DesktopUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {

    Table table = new Table();
    beanItemContainer = new BeanItemContainer<>(Product.class, productService.getAllProducts());
    table.setContainerDataSource(beanItemContainer);
    table.setRowHeaderMode(Table.RowHeaderMode.INDEX);
    table.setColumnHeaders("ID", "Name", "Price", "Stock Count");

    Button button = new Button("Add");
    button.addClickListener(new AddButtonClickListener());

    CustomLayout customLayout = new CustomLayout("desktop");
    customLayout.setSizeFull();
    customLayout.addComponent(table, "product-table");
    customLayout.addComponent(button, "add-product");
    setContent(customLayout);

    Notification.show("Welcome to " + ProductUI.BRAND.concat(" ").concat(ProductUI.DESCRIPTION));
}
 
Example 33
Project: vanilla   File: SimpleUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            layout.addComponent(new Label("Thank you for clicking"));
        }
    });
    layout.addComponent(button);

}
 
Example 34
Project: vanilla   File: ProductUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {

    Component header = buildHeader();
    Component footer = buildFooter();
    Component center = buildCenter();

    VerticalLayout mainLayout = new VerticalLayout();
    mainLayout.setSizeFull();
    mainLayout.addComponent(header);
    mainLayout.addComponent(center);
    mainLayout.addComponent(footer);
    mainLayout.setExpandRatio(center, 1f);
    setContent(mainLayout);

    Notification.show("Welcome to " + BRAND.concat(" ").concat(DESCRIPTION));
}
 
Example 35
Project: springbootcamp   File: ApplicationUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {

  final VerticalLayout layout = new VerticalLayout();
  layout.setMargin(true);
  layout.setSpacing(true);
  layout.addComponent(labelTime);
  setContent(layout);

  eventBus.on(Selectors.$(TOPIC), new Consumer<reactor.bus.Event<LocalTime>>() {
    @Override
    public void accept(reactor.bus.Event<LocalTime> event) {
      access(() -> labelTime.setValue(event.getData().format(dateTimeFormatter)));
    }
  });
}
 
Example 36
Project: flightservice   File: FlightServiceUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {

	Panel panel = new Panel();
	panel.setSizeFull();

	Navigator navigator = new Navigator(this, panel);
	navigator.addView(NavigationState.HOME, HomeView.class);
	navigator.addView(NavigationState.AIRPORT_LIST, AirportListView.class);
	navigator.addView(NavigationState.FLIGHT_MAINTENANCE, FlightMaintenanceView.class);
	navigator.addView(NavigationState.FLIGHT_BOOKING, FlightBookingView.class);
	navigator.addView(NavigationState.BOOKING_CANCELLATION, BookingCancellationView.class);
	navigator.navigateTo(NavigationState.HOME);

	VerticalLayout verticalLayout = new VerticalLayout();
	verticalLayout.setSizeFull();
	verticalLayout.addComponent(createMenu());
	verticalLayout.addComponent(panel);
	verticalLayout.setExpandRatio(panel, 1);
	setContent(verticalLayout);
}
 
Example 37
Project: osgi-bridge-and-fragmentedui-demo   File: VaadinOSGiUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {

	setPollInterval(1000);
	hl = new HorizontalSplitPanel();
	hl.setSizeFull();
	setContent(hl);

	buttonsOnTheLeft = new VerticalLayout();
	buttonsOnTheLeft.setSizeUndefined();

	hl.setFirstComponent(buttonsOnTheLeft);
	hl.setSplitPosition(25, Unit.PERCENTAGE);

	ServiceTracker<FragmentFactory, FragmentFactory> tracker = new ServiceTracker<FragmentFactory, FragmentFactory>(
			VaadinActivator.context, FragmentFactory.class, this);
	tracker.open();
	
	addDetachListener(new DetachListener() {
		
		@Override
		public void detach(DetachEvent event) {
			tracker.close();
		}
	});
}
 
Example 38
Project: root   File: WoundManagementUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {	

	initializeEnvironment(request);
	
	getEnvironment().setCurrentUriFragment("login");
	getPage().setUriFragment(getEnvironment().getCurrentUriFragment());
	
	getPage().addUriFragmentChangedListener(
               new UriFragmentChangedListener() {
           public void uriFragmentChanged(
                   UriFragmentChangedEvent source) {
               enter(source.getUriFragment());
            }
        });

        // Read the initial URI fragment
        enter(getPage().getUriFragment());
}
 
Example 39
Project: viritin   File: Java8LocaleNegotiationStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public Locale negotiate(List<Locale> supportedLocales,
        VaadinRequest vaadinRequest) {
    String languages = vaadinRequest.getHeader("Accept-Language");
    try {
        // Use reflection here, so the code compiles with jdk 1.7
        Class<?> languageRange = Class
                .forName("java.util.Locale$LanguageRange");
        Method parse = languageRange.getMethod("parse", String.class);
        Object priorityList = parse.invoke(null, languages);
        Method lookup = Locale.class.getMethod("lookup", List.class,
                Collection.class);
        return (Locale) lookup.invoke(null, priorityList, supportedLocales);
    } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException e) {
        throw new RuntimeException(
                "Java8LocaleNegotiontionStrategy need java 1.8 or newer.",
                e);
    }

}
 
Example 40
Project: viritin   File: Issue309PojoForm.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    AbstractForm<Pojo> form = new AbstractForm<Pojo>(Pojo.class) {

        private static final long serialVersionUID = 1251886098275380006L;
        IntegerField myInteger = new IntegerField("My Integer");

        @Override
        protected Component createContent() {
            FormLayout layout = new FormLayout(myInteger, getToolbar());
            return layout;
        }
    };

    form.setResetHandler((Pojo entity) -> {
        form.setEntity(null);
    });

    form.setEntity(new Pojo());
    setContent(form);
}
 
Example 41
Project: viritin   File: Issue298IntegerField.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    Model model = new Model();
    model.setValue(0);

    this.value.addValueChangeListener((evt) -> System.out.println("value is: " + evt.getValue()));

    this.value.setValue(1);

    // expect to see 'value is: 1' here
    this.binder.bindInstanceFields(this);
    this.binder.setBean(model);

    // expect to see 'value is: 1' here
    this.value.setValue(2);

    // expect to see 'value is: 2' here but exception is thrown instead

    setContent(this.value);
}
 
Example 42
Project: archetype-application-example   File: MockAppUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    Responsive.makeResponsive(this);
    setLocale(vaadinRequest.getLocale());
    getPage().setTitle("MockApp");
    if (!accessControl.isUserSignedIn()) {
        setContent(new LoginScreen(accessControl, new LoginListener() {
            @Override
            public void loginSuccessful() {
                showMainView();
            }
        }));
    } else {
        showMainView();
    }
}
 
Example 43
Project: dropwizard-vaadin   File: MainUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setHeight(100f,Unit.PERCENTAGE);
    setContent(layout);

    Button button = new Button("click!", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            int count = (int) Objects.firstNonNull(getSession().getAttribute("count"), 0);
            getSession().setAttribute("count", ++count);

            layout.addComponent(new Label("clicked: " + count ));
        }
    });

    layout.addComponent(button);
}
 
Example 44
Project: vaadinator   File: TimesheetUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	// TODO: remove test-entry into contet
	context.put(CONTEXT_LOGIN_USER, "sebastian");
	// create
	NavigationManager m = new NavigationManager();
	m.setMaintainBreadcrumb(true);
	TimesheetChangePresenter pres = obtainPresenterFactory(request.getContextPath()).createTimesheetChangePresenter(null);
	// Load the july timesheet into the presenter
	CouchDbTimesheetService tsService = new CouchDbTimesheetService();
	List<Timesheet> tsList = tsService.listAllTimesheet(new HashMap<String, Object>(context));
	for (Timesheet ts : tsList) {
		if (ts.getMonth() == 7 && ts.getYear() == 2014) {
			pres.setTimesheet(ts);
			break;
		}
	}
	// TODO: have list presenter before (instead of one)
	m.setCurrentComponent((Component) pres.getView().getComponent());
	setContent(m);
	// and go
	pres.startPresenting();
}
 
Example 45
Project: LazyList   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	infiniteList = createInfiniteList();
	finiteList = createFiniteList();
	shortList = createShortList();

	HorizontalLayout buttons = new HorizontalLayout();
	infinite = new Button("Infinite", this);
	finite = new Button("Finite", this);
	couple = new Button("Short", this);
	buttons.addComponent(infinite);
	buttons.addComponent(finite);
	buttons.addComponent(couple);
	Panel navigationArea = new Panel();
	navigationArea.setContent(buttons);

	layout = new VerticalLayout();
	layout.addComponent(navigationArea);
	layout.addComponent(infiniteList);
	layout.setSizeFull();
	layout.setExpandRatio(infiniteList, 1);

	setContent(layout);
}
 
Example 46
Project: vaadin4spring   File: SecurityContextVaadinRequestListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onRequestEnd(VaadinRequest request, VaadinResponse response, VaadinSession session) {
    try {
        if (session != null) {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            logger.trace("Storing security context {} in VaadinSession {}", securityContext, session);
            session.lock();
            try {
                session.setAttribute(SECURITY_CONTEXT_SESSION_ATTRIBUTE, securityContext);
            } finally {
                session.unlock();
            }
        } else {
            logger.trace("No VaadinSession available for storing the security context");
        }
    } finally {
        logger.trace("Clearing security context");
        SecurityContextHolder.clearContext();
    }
}
 
Example 47
Project: vaadin4spring   File: AbstractSideBarUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    getPage().setTitle("Vaadin4Spring Side Bar Sample");
    final HorizontalLayout rootLayout = new HorizontalLayout();
    rootLayout.setSizeFull();
    setContent(rootLayout);

    final VerticalLayout viewContainer = new VerticalLayout();
    viewContainer.setSizeFull();

    final Navigator navigator = new Navigator(this, viewContainer);
    navigator.setErrorView(new ErrorView());
    navigator.addProvider(viewProvider);
    setNavigator(navigator);

    rootLayout.addComponent(getSideBar());
    rootLayout.addComponent(viewContainer);
    rootLayout.setExpandRatio(viewContainer, 1.0f);
}
 
Example 48
Project: vaadin4spring   File: SingleSecuredUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    getPage().setTitle("Vaadin Managed Security Demo");
    // Let's register a custom error handler to make the 'access denied' messages a bit friendlier.
    setErrorHandler(new DefaultErrorHandler() {
        @Override
        public void error(com.vaadin.server.ErrorEvent event) {
            if (SecurityExceptionUtils.isAccessDeniedException(event.getThrowable())) {
                Notification.show("Sorry, you don't have access to do that.");
            } else {
                super.error(event);
            }
        }
    });
    if (vaadinSecurity.isAuthenticated()) {
        showMainScreen();
    } else {
        showLoginScreen(request.getParameter("goodbye") != null);
    }
}
 
Example 49
Project: activelink   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
	final VerticalLayout layout = new VerticalLayout();
	layout.setMargin(true);
	setContent(layout);

	ActiveLink link = new ActiveLink("Click Me", new ExternalResource(
			"http://blog.porotype.com"));
	link.addListener(new LinkActivatedListener() {

		@Override
		public void linkActivated(LinkActivatedEvent event) {
			MouseEventDetails d = event.getMouseEventDetails();
			String caption = "Link " + d.getButtonName() + "-clicked";
			String msg = "Ctrl: " + d.isCtrlKey() + " Shift: "
					+ d.isShiftKey() + " Alt: " + d.isAltKey() + " Meta: "
					+ d.isMetaKey();
			Notification.show(caption, msg, Type.WARNING_MESSAGE);
			System.err.println(caption + " " + msg);
		}
	});
	layout.addComponent(link);
}
 
Example 50
Project: gantt   File: DemoUI.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    ganttListener = null;
    createGantt();

    MenuBar menu = controlsMenuBar();
    Panel controls = createControls();

    Component wrapper = UriFragmentWrapperFactory.wrapByUriFragment(UI.getCurrent().getPage().getUriFragment(),
            gantt);
    if (wrapper instanceof GanttListener) {
        ganttListener = (GanttListener) wrapper;
    }

    final VerticalLayout layout = new VerticalLayout();
    layout.setStyleName("demoContentLayout");
    layout.setMargin(false);
    layout.setSizeFull();
    layout.addComponent(menu);
    layout.addComponent(controls);
    layout.addComponent(wrapper);
    layout.setExpandRatio(wrapper, 1);

    setContent(layout);
}
 
Example 51
Project: gazpachoquest   File: QuestionnairesUI.java   Source Code and License 6 votes vote down vote up
@Override
public void init(VaadinRequest request) {
    logger.info("New Vaadin UI created");
    String invitation = request.getParameter("invitation");
    logger.info("Invitation: {} of sessions : {}", invitation);
    setSizeFull();
    GazpachoViewDisplay viewDisplay = new GazpachoViewDisplay();
    setContent(viewDisplay);

    navigator = new Navigator(this, (ViewDisplay) viewDisplay);
    navigator.addProvider(viewProvider);
    navigator.setErrorProvider(new GazpachoErrorViewProvider());

    if (isUserSignedIn()) {
        navigator.navigateTo(QuestionnaireView.NAME);
    } else {
        navigator.navigateTo(LoginView.NAME);
    }
}
 
Example 52
Project: boot-examples   File: Application.java   Source Code and License 6 votes vote down vote up
@Override
protected void init(VaadinRequest vaadinRequest) {
    getPage().setTitle("Root UI");

    Table table = new Table("Customer Table");

    table.addContainerProperty("firstName", String.class, null);
    table.addContainerProperty("lastName", String.class, null);
    table.addContainerProperty("id", Long.class, null);

    for (Customer c : this.customerRepository.findAll())
        table.addItem(new Object[]{c.getFirstName(), c.getLastName(), c.getId()}, c.getId());

    table.setSizeFull();
    table.setColumnHeader("firstName", "First Name");
    table.setColumnHeader("lastName", "First Name");
    setContent(table);
}
 
Example 53
Project: server-side-selectors   File: VisitableComponentsTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void shouldVisitOnUI() {
  final UI ui = new UI() {
    @Override
    protected void init(VaadinRequest request) {
    }
  };
  VisitableComponents visitableComponents = new VisitableComponents(ui);
  final ComponentVisitor componentVisitor = mock(ComponentVisitor.class);
  checking(new Expectations() {{
    oneOf(componentVisitor).startComponent(ui); will(returnValue(null));
    oneOf(componentVisitor).endComponent(ui);
  }});
  visitableComponents.acceptVisitor(componentVisitor);
  assertIsSatisfied();
}
 
Example 54
Project: server-side-selectors   File: VisitableComponentsTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void shouldVisitOnUIEvenExpectChilds() {
  final UI ui = new UI() {
    @Override
    protected void init(VaadinRequest request) {
    }
  };
  VisitableComponents visitableComponents = new VisitableComponents(ui);
  final ComponentVisitor componentVisitor = mock(ComponentVisitor.class);
  checking(new Expectations() {{
    oneOf(componentVisitor).startComponent(ui); will(returnValue(componentVisitor));
    oneOf(componentVisitor).endComponent(ui);
  }});
  visitableComponents.acceptVisitor(componentVisitor);
  assertIsSatisfied();
}
 
Example 55
Project: server-side-selectors   File: VisitableComponentsTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void shouldVisitUIAndButton() {
  final UI ui = new UI() {
    @Override
    protected void init(VaadinRequest request) {
    }
  };

  final Button button = new Button();
  ui.setContent(button);

  VisitableComponents visitableComponents = new VisitableComponents(ui);

  final ComponentVisitor componentVisitor = mock(ComponentVisitor.class);
  checking(new Expectations() {{
    oneOf(componentVisitor).startComponent(ui); will(returnValue(componentVisitor));
    oneOf(componentVisitor).startComponent(button); will(returnValue(componentVisitor));
    oneOf(componentVisitor).endComponent(button);
    oneOf(componentVisitor).endComponent(ui);
  }});
  visitableComponents.acceptVisitor(componentVisitor);
  assertIsSatisfied();
}
 
Example 56
Project: hypothesis   File: ProcessUIPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize(VaadinRequest request) {
	log.debug("ProcessUIPresenter initialization");

	super.initialize(request);

	// TODO try to set token by uri fragment and implement
	// UriFragmentChangeListener
	initParameters(request);

	if (tokenString != null) {
		log.debug(TOKEN_PARAMETER + "=" + tokenString);
		lastTokenString = tokenString;

		followToken(tokenString);

		ui.setLoadingIndicatorVisible(false);
	} else {
		log.debug(TOKEN_PARAMETER + "=(null)");
		lastTokenString = null;
		fireError(Messages.getString("Message.Error.InvalidAccess"));
	}
}
 
Example 57
Project: hypothesis   File: ProcessUIPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void refresh(VaadinRequest request) {
	initParameters(request);

	if (tokenString != null) {
		if (!tokenString.equalsIgnoreCase(lastTokenString)) {
			lastTokenString = tokenString;

			processManager.requestBreakTest();

			followToken(tokenString);
		} else {
			log.debug("ProcessUI refreshed");
		}
	} else {
		log.debug(TOKEN_PARAMETER + "=(null)");
		lastTokenString = null;
		fireError(Messages.getString("Message.Error.InvalidAccess"));
	}
}
 
Example 58
Project: hypothesis   File: LocaleManager.java   Source Code and License 6 votes vote down vote up
public static void initializeLocale(VaadinRequest request) {
	WrappedSession session = request.getWrappedSession();
	HttpSession httpSession = ((WrappedHttpSession) session).getHttpSession();
	ServletContext servletContext = httpSession.getServletContext();

	String defaultLanguage = servletContext.getInitParameter(LOCALE_CONFIG_DEFAULT_LANGUAGE);
	defaultLocale = new Locale(defaultLanguage);

	String language = request.getParameter(LOCALE_PARAM_LANGUAGE);

	if (null == language) {
		currentLocale = defaultLocale;
	} else {
		currentLocale = new Locale(language);
	}

	Messages.initMessageSource(currentLocale);
}
 
Example 59
Project: panifex-platform   File: PageletAwareUITest.java   Source Code and License 6 votes vote down vote up
@Test
public void testInitMatchedPagelet() throws Exception {
    // variables
    String path = "/test";

    // mocks
    VaadinPageletTracker pageletTracker = createMock(VaadinPageletTracker.class);
    VaadinPagelet pagelet = createMock(VaadinPagelet.class);
    VaadinRequest request = createMock(VaadinRequest.class);

    // expect getting url path from request
    expect(request.getPathInfo()).andReturn(path);

    // expect matching path to pagelet
    expect(pageletTracker.matchPathToPagelet(path)).andReturn(pagelet);

    // expect servicing request
    pagelet.service(request);

    // perform test
    replayAll();
    PageletAwareUI ui = new PageletAwareUI(pageletTracker);
    ui.init(request);
    verifyAll();
}
 
Example 60
Project: panifex-platform   File: PageletAwareUITest.java   Source Code and License 6 votes vote down vote up
@Test
public void testInitNotMatchedPagelet() throws Exception {
    // variables
    String path = "/test";

    // mocks
    VaadinPageletTracker pageletTracker = createMock(VaadinPageletTracker.class);
    VaadinRequest request = createMock(VaadinRequest.class);

    // expect getting url path from request
    expect(request.getPathInfo()).andReturn(path);

    // expect matching path to pagelet
    expect(pageletTracker.matchPathToPagelet(path)).andReturn(null);

    // except returning HTTP 404
    VaadinResponse response = createMock(VaadinResponse.class);
    expect(CurrentInstance.get(VaadinResponse.class)).andReturn(response);
    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found");

    // perform test
    replayAll();
    PageletAwareUI ui = new PageletAwareUI(pageletTracker);
    ui.init(request);
    verifyAll();
}