Java 类com.vaadin.server.Page 实例源码

项目:electron-java-app    文件:MainUI.java   
private void initElectronApi() {
    JavaScript js = getPage().getJavaScript();
    js.addFunction("appMenuItemTriggered", arguments -> {
        if (arguments.length() == 1 && arguments.get(0) instanceof JsonString) {
            String menuId = arguments.get(0).asString();
            if ("About".equals(menuId)) {
                onMenuAbout();
            } else if ("Exit".equals(menuId)) {
                onWindowExit();
            }
        }
    });
    js.addFunction("appWindowExit", arguments -> onWindowExit());

    Page.Styles styles = getPage().getStyles();
    try {
        InputStream resource = MainUI.class.getResourceAsStream(
                "/org/strangeway/electronvaadin/resources/electron.css");
        styles.add(IOUtils.toString(resource, StandardCharsets.UTF_8));
    } catch (IOException ignored) {
    }
}
项目:holon-vaadin7    文件:NavigatorActuator.java   
/**
 * Invoked when authentication is missing or failed using {@link AuthContext} during {@link Authenticate} annotation
 * processing.
 * @param authc Authenticate annotation
 * @param navigationState Navigation state
 * @throws ViewNavigationException If cannot be performed any redirection using {@link Authenticate#redirectURI()}
 */
protected void onAuthenticationFailed(final Authenticate authc, final String navigationState)
        throws ViewNavigationException {
    // redirect
    String redirectURI = AnnotationUtils.getStringValue(authc.redirectURI());
    if (redirectURI != null) {
        // check view scheme
        String viewNavigationState = getViewNavigationState(redirectURI);
        if (viewNavigationState != null) {
            try {
                suspendAuthenticationCheck = true;
                navigator.navigateTo(viewNavigationState);
            } finally {
                suspendAuthenticationCheck = false;
            }
        } else {
            // try to open the URI as an URL
            Page.getCurrent().open(redirectURI, null);
        }
    } else {
        throw new ViewNavigationException(navigationState, "Authentication required");
    }
}
项目:holon-vaadin7    文件:NotificationValidationStatusHandler.java   
@Override
public void validationStatusChange(ValidationStatusEvent<?> statusChangeEvent) {
    if (statusChangeEvent.isInvalid()) {

        String error = showAllErrors
                ? statusChangeEvent.getErrorMessages().stream().collect(Collectors.joining("<br/>"))
                : statusChangeEvent.getErrorMessage();

        if (error == null || error.trim().equals("")) {
            error = "Validation error";
        }

        if (notification != null) {
            notification.setCaption(error);
            notification.show(Page.getCurrent());
        } else {
            Notification.show(error, Type.ERROR_MESSAGE);
        }

    }
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * Change le rôle de l'utilisateur courant
 * 
 * @param username
 *            le nom de l'utilisateur a prendre
 */
public void switchToUser(String username) {
    Assert.hasText(username, applicationContext.getMessage("assert.hasText", null, UI.getCurrent().getLocale()));

    /* Vérifie que l'utilisateur existe */
    try {
        UserDetails details = userDetailsService.loadUserByUsername(username);
        if (details == null || details.getAuthorities() == null || details.getAuthorities().size() == 0) {
            Notification.show(applicationContext.getMessage("admin.switchUser.usernameNotFound",
                    new Object[] { username }, UI.getCurrent().getLocale()), Notification.Type.WARNING_MESSAGE);
            return;
        }
    } catch (UsernameNotFoundException unfe) {
        Notification.show(applicationContext.getMessage("admin.switchUser.usernameNotFound",
                new Object[] { username }, UI.getCurrent().getLocale()), Notification.Type.WARNING_MESSAGE);
        return;
    }
    String switchToUserUrl = MethodUtils.formatSecurityPath(loadBalancingController.getApplicationPath(false),
            ConstanteUtils.SECURITY_SWITCH_PATH) + "?" + SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY + "="
            + username;
    Page.getCurrent().open(switchToUserUrl, null);
}
项目:osc-core    文件:MainUI.java   
private void buildMainView() {
    buildHeader();
    buildMainLayout();
    this.root.setExpandRatio(this.mainLayout, 1);

    this.registration = this.ctx.registerService(BroadcastListener.class, this, null);

    // adding view change listener to navigator
    addViewChangeListener();
    String uriFragment = Page.getCurrent().getUriFragment();
    if (StringUtils.isBlank(uriFragment)) {
        uriFragment = VIEW_FRAGMENT_ALERTS;
    }
    String sanitizedFragment = StringUtils.remove(uriFragment, '!').replace('+', ' ');
    this.nav.navigateTo(sanitizedFragment);

}
项目:osc-core    文件:ViewUtil.java   
public static void showJobNotification(Long jobId, ServerApi server) {
    HashMap<String, Object> paramMap = null;
    if (jobId != null) {
        paramMap = new HashMap<>();
        paramMap.put(JOB_ID_PARAM_KEY, jobId);
    }

    String jobLinkUrl = createInternalUrl(MainUI.VIEW_FRAGMENT_JOBS, paramMap, server);
    if (jobLinkUrl != null) {
        if (jobId == null) {
            new Notification("Info", "<a href=\"" + jobLinkUrl + "\">" + " Go To Job View" + "</a>",
                    Notification.Type.TRAY_NOTIFICATION, true).show(Page.getCurrent());
        } else {
            new Notification("Info", "Job <a href=\"" + jobLinkUrl + "\">" + jobId + "</a> started.",
                    Notification.Type.TRAY_NOTIFICATION, true).show(Page.getCurrent());
        }
    } else {
        new Notification("Info", "Job started.", Notification.Type.TRAY_NOTIFICATION, true).show(Page.getCurrent());
    }
}
项目:tinypounder    文件:TinyPounderMainUI.java   
@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);
}
项目:vaadin-javaee-jaas-example    文件:JaasExampleUI.java   
@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);
    }
}
项目:holon-vaadin    文件:NavigatorActuator.java   
/**
 * Invoked when authentication is missing or failed using {@link AuthContext} during {@link Authenticate} annotation
 * processing.
 * @param authc Authenticate annotation
 * @param navigationState Navigation state
 * @throws ViewNavigationException If cannot be performed any redirection using {@link Authenticate#redirectURI()}
 */
protected void onAuthenticationFailed(final Authenticate authc, final String navigationState)
        throws ViewNavigationException {
    // redirect
    String redirectURI = AnnotationUtils.getStringValue(authc.redirectURI());
    if (redirectURI != null) {
        // check view scheme
        String viewNavigationState = getViewNavigationState(redirectURI);
        if (viewNavigationState != null) {
            try {
                suspendAuthenticationCheck = true;
                navigator.navigateTo(viewNavigationState);
            } finally {
                suspendAuthenticationCheck = false;
            }
        } else {
            // try to open the URI as an URL
            Page.getCurrent().open(redirectURI, null);
        }
    } else {
        throw new ViewNavigationException(navigationState, "Authentication required");
    }
}
项目:holon-vaadin    文件:NotificationValidationStatusHandler.java   
@Override
public void validationStatusChange(ValidationStatusEvent<?> statusChangeEvent) {
    if (statusChangeEvent.isInvalid()) {

        String error = showAllErrors
                ? statusChangeEvent.getErrorMessages().stream().collect(Collectors.joining("<br/>"))
                : statusChangeEvent.getErrorMessage();

        if (error == null || error.trim().equals("")) {
            error = "Validation error";
        }

        if (notification != null) {
            notification.setCaption(error);
            notification.show(Page.getCurrent());
        } else {
            Notification.show(error, Type.ERROR_MESSAGE);
        }

    }
}
项目:history-api-navigation    文件:HistoryApiNavigationStateManagerTest.java   
@Test
public void testSetNavigator()
{
    navigationStateManager.setNavigator(null);
    Mockito.verifyZeroInteractions(popStateListenerRegistration);
    Mockito.verifyZeroInteractions(page);

    Mockito.when(page.addPopStateListener(ArgumentMatchers.any(Page.PopStateListener.class)))
            .thenReturn(popStateListenerRegistration);
    navigationStateManager.setNavigator(navigator);
    Mockito.verify(page)
            .addPopStateListener(ArgumentMatchers.any(Page.PopStateListener.class));

    navigationStateManager.setNavigator(null);
    Mockito.verify(popStateListenerRegistration).remove();
}
项目:bbplay    文件:LanguageComboBox.java   
public LanguageComboBox(Locale locale) {
    super(I18n.t("language"));
    setStyleName("languages");
    setContainerDataSource(createDataSource());
    setItemCaptionPropertyId("caption");
    setItemIconPropertyId("icon");
    setImmediate(true);
    setNullSelectionAllowed(false);

    setInitialValue(locale);

    addValueChangeListener(event -> {
        BBPlay.setLanguage(((Locale) event.getProperty().getValue()).getLanguage());
        Page.getCurrent().reload();
    });

}
项目:imotSpot    文件:AddingImot.java   
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
    imageCounter++;
    savePath = "../uploads/" + filename;
    imageName = filename;
    FileOutputStream fos = null; // Stream to write to
    try {
        // Open the file for writing.
        file = new File(savePath);
        fos = new FileOutputStream(file);

    } catch (final java.io.FileNotFoundException e) {
        new Notification("Could not open file",
                e.getMessage(),
                Notification.Type.ERROR_MESSAGE).show(Page.getCurrent());
        return null;
    }

    return fos; // Return the output stream to write to
}
项目:imotSpot    文件:ScheduleView.java   
private void injectMovieCoverStyles() {
        // Add all movie cover images as classes to CSSInject
        String styles = "";
//        for (Movie m : DashboardUI.getDataProvider().getMovies()) {
//            WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
//
//            String bg = "url(VAADIN/themes/" + UI.getCurrent().getTheme()
//                    + "/img/event-title-bg.png), url(" + m.getThumbUrl() + ")";
//
//            // IE8 doesn't support multiple background images
//            if (webBrowser.isIE() && webBrowser.getBrowserMajorVersion() == 8) {
//                bg = "url(" + m.getThumbUrl() + ")";
//            }
//
//            styles += ".v-calendar-event-" + m.getId()
//                    + " .v-calendar-event-content {background-image:" + bg
//                    + ";}";
//        }

        Page.getCurrent().getStyles().add(styles);
    }
项目:imotSpot    文件:DashboardUI.java   
@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());
                }
            });
}
项目:vaadin-vertx-samples    文件:ScheduleView.java   
private void injectMovieCoverStyles() {
    // Add all movie cover images as classes to CSSInject
    String styles = "";
    for (Movie m : DashboardUI.getDataProvider().getMovies()) {
        WebBrowser webBrowser = Page.getCurrent().getWebBrowser();

        String bg = "url(VAADIN/themes/" + UI.getCurrent().getTheme()
                + "/img/event-title-bg.png), url(" + m.getThumbUrl() + ")";

        // IE8 doesn't support multiple background images
        if (webBrowser.isIE() && webBrowser.getBrowserMajorVersion() == 8) {
            bg = "url(" + m.getThumbUrl() + ")";
        }

        styles += ".v-calendar-event-" + m.getId()
                + " .v-calendar-event-content {background-image:" + bg
                + ";}";
    }

    Page.getCurrent().getStyles().add(styles);
}
项目:vaadin-vertx-samples    文件:LoginView.java   
public LoginView() {
    setSizeFull();

    Component loginForm = buildLoginForm();
    addComponent(loginForm);
    setComponentAlignment(loginForm, Alignment.MIDDLE_CENTER);

    Notification notification = new Notification(
            "Welcome to Dashboard Demo");
    notification
            .setDescription("<span>This application is not real, it only demonstrates an application built with the <a href=\"https://vaadin.com\">Vaadin framework</a>.</span> <span>No username or password is required, just click the <b>Sign In</b> button to continue.</span>");
    notification.setHtmlContentAllowed(true);
    notification.setStyleName("tray dark small closable login-help");
    notification.setPosition(Position.BOTTOM_CENTER);
    notification.setDelayMsec(20000);
    notification.show(Page.getCurrent());
}
项目:vaadin-vertx-samples    文件:DashboardUI.java   
@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());
                }
            });
}
项目:metasfresh-procurement-webui    文件:LoginRememberMeService.java   
public boolean isEnabled()
{
    if (!enabled)
    {
        return false;
    }

    final Page page = Page.getCurrent();
    if (page != null && page.getWebBrowser().isChrome())
    {
        logger.trace("Considering feature disabled for chome because Chrome's password manager is known to work");
        return false;
    }

    return true;
}
项目:metasfresh-procurement-webui    文件:LoginView.java   
protected void onForgotPassword(final String email)
{
    if (Strings.isNullOrEmpty(email))
    {
        throw new PasswordResetFailedException(email, i18n.get("LoginView.passwordReset.error.fillEmail"));
    }

    final String passwordResetKey = loginService.generatePasswordResetKey(email);
    final URI passwordResetURI = PasswordResetView.buildPasswordResetURI(passwordResetKey);
    loginService.sendPasswordResetKey(email, passwordResetURI);

    final Notification notification = new Notification(
            i18n.get("LoginView.passwordReset.notification.title") // "Password reset"
            , i18n.get("LoginView.passwordReset.notification.message") // "Your password has been reset. Please check your email and click on that link"
            , Type.HUMANIZED_MESSAGE);
    notification.setDelayMsec(15 * 1000);
    notification.show(Page.getCurrent());
}
项目:metasfresh-procurement-webui    文件:PasswordResetView.java   
public static final URI buildPasswordResetURI(final String passwordResetKey)
{
    try
    {
        final URI uri = Page.getCurrent().getLocation();
        final String query = null;
        final String fragment = MFNavigator.createURIFragment(NAME, passwordResetKey);
        final URI resetURI = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), query, fragment);
        System.out.println(resetURI);
        return resetURI;
    }
    catch (Exception e)
    {
        throw Throwables.propagate(e);
    }
}
项目:cuba    文件:ExceptionDialog.java   
protected void forceLogout() {
    App app = AppUI.getCurrent().getApp();
    final WebWindowManager wm = app.getWindowManager();
    try {
        Connection connection = wm.getApp().getConnection();
        if (connection.isConnected()) {
            connection.logout();
        }
    } catch (Exception e) {
        log.warn("Exception on forced logout", e);
    } finally {
        // always restart UI
        String url = ControllerUtils.getLocationWithoutParams() + "?restartApp";

        Page.getCurrent().open(url, "_self");
    }
}
项目:cuba    文件:CubaTable.java   
@Override
public void changeVariables(Object source, Map<String, Object> variables) {
    if (Page.getCurrent().getWebBrowser().isIE() && variables.containsKey("clickEvent")) {
        focus();
    }

    super.changeVariables(source, variables);

    if (shortcutActionManager != null) {
        shortcutActionManager.handleActions(variables, this);
    }

    String profilerMarker = (String) variables.get("profilerMarker");
    if (StringUtils.isNotEmpty(profilerMarker)) {
        AppUI ui = AppUI.getCurrent();
        ui.setProfilerMarker(profilerMarker);
    }
}
项目:cuba    文件:WebNewWindowButton.java   
public WebNewWindowButton() {
    component = new CubaButton();
    component.addStyleName(NEW_WINDOW_BUTTON_STYLENAME);
    component.setDescription(null);

    URL pageUrl;
    try {
        pageUrl = Page.getCurrent().getLocation().toURL();
    } catch (MalformedURLException ignored) {
        LoggerFactory.getLogger(WebNewWindowButton.class).warn("Couldn't get URL of current Page");
        return;
    }

    ExternalResource currentPage = new ExternalResource(pageUrl);
    final BrowserWindowOpener opener = new BrowserWindowOpener(currentPage);
    opener.setWindowName("_blank");

    opener.extend(component);
}
项目:VaadinSpringShiroMongoDB    文件:ProductForm.java   
public void editProduct(Product product) {
    if (product == null) {
        product = new Product();
    }
    fieldGroup.setItemDataSource(new BeanItem<Product>(product));

    // before the user makes any changes, disable validation error indicator
    // of the product name field (which may be empty)
    productName.setValidationVisible(false);

    // Scroll to the top
    // As this is not a Panel, using JavaScript
    String scrollScript = "window.document.getElementById('" + getId()
            + "').scrollTop = 0;";
    Page.getCurrent().getJavaScript().execute(scrollScript);
}
项目:hawkbit    文件:AbstractHawkbitLoginUI.java   
@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();
}
项目:hawkbit    文件:DashboardMenu.java   
private Component buildUserMenu(final UiProperties uiProperties) {
    final MenuBar settings = new MenuBar();
    settings.addStyleName("user-menu");
    settings.setHtmlContentAllowed(true);

    final MenuItem settingsItem = settings.addItem("", getImage(uiProperties.isGravatar()), null);

    final String formattedTenant = UserDetailsFormatter.formatCurrentTenant();
    if (!StringUtils.isEmpty(formattedTenant)) {
        settingsItem.setText(formattedTenant);
        UserDetailsFormatter.getCurrentTenant().ifPresent(tenant -> settingsItem.setDescription(i18n
                .getMessage("menu.user.description", tenant, UserDetailsFormatter.getCurrentUser().getUsername())));
    } else {
        settingsItem.setText("...");
    }

    settingsItem.setStyleName("user-menuitem");

    final String logoutUrl = generateLogoutUrl();

    settingsItem.addItem("Sign Out", selectedItem -> Page.getCurrent().setLocation(logoutUrl));
    return settings;
}
项目:hawkbit    文件:HawkbitUIErrorHandler.java   
@Override
public void error(final ErrorEvent event) {

    final HawkbitErrorNotificationMessage message = buildNotification(getRootExceptionFrom(event));
    if (event instanceof ConnectorErrorEvent) {
        final Connector connector = ((ConnectorErrorEvent) event).getConnector();
        if (connector instanceof UI) {
            final UI uiInstance = (UI) connector;
            uiInstance.access(() -> message.show(uiInstance.getPage()));
            return;
        }
    }

    final Optional<Page> originError = getPageOriginError(event);
    if (originError.isPresent()) {
        message.show(originError.get());
        return;
    }

    HawkbitErrorNotificationMessage.show(message.getCaption(), message.getDescription(), Type.HUMANIZED_MESSAGE);
}
项目:vaadin-jcrop    文件:Jcrop.java   
/**
 * generate's the requestUri for the RequestHandler with a ts-parameter to avoid caching of browser on resource-changes
 * 
 * @return
 */
private String getRequestUri() {
    URI uri = Page.getCurrent()
            .getLocation();
    String url = null;
    if ((uri.getPort() == 80) || (uri.getPort() == 443) || (uri.getPort() <= 0)) {
        url = uri.getScheme() + "://" + uri.getHost() + uri.getPath();
    } else {
        url = uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath();
    }
    if (url != null && !url.endsWith("/")) {
        url += "/";
    }
    url += this.requestHandlerUri + "?ts=" + new Date().getTime();
    return url;
}
项目:KrishnasSpace    文件:VaadinUI.java   
@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));
}
项目:metl    文件:ReleasesView.java   
protected void downloadExport(final String export, String filename) {

        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {
                try {
                    return new ByteArrayInputStream(export.getBytes(Charset.forName("utf-8")));
                } catch (Exception e) {
                    log.error("Failed to export configuration", e);
                    CommonUiUtils.notify("Failed to export configuration.", Type.ERROR_MESSAGE);
                    return null;
                }
            }
        };
        String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StreamResource resource = new StreamResource(ss,
                String.format("%s-config-%s.json", filename, datetime));
        final String KEY = "export";
        setResource(KEY, resource);
        Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
    }
项目:metl    文件:EditAgentPanel.java   
protected void exportConfiguration() {
    final String export = context.getImportExportService().exportAgent(agent.getId(), AppConstants.SYSTEM_USER);
    StreamSource ss = new StreamSource() {
        private static final long serialVersionUID = 1L;

        public InputStream getStream() {
            try {
                return new ByteArrayInputStream(export.getBytes());
            } catch (Exception e) {
                log.error("Failed to export configuration", e);
                CommonUiUtils.notify("Failed to export configuration.", Type.ERROR_MESSAGE);
                return null;
            }

        }
    };
    String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    StreamResource resource = new StreamResource(ss,
            String.format("%s-config-%s.json", agent.getName().toLowerCase().replaceAll(" ", "-"), datetime));
    final String KEY = "export";
    setResource(KEY, resource);
    Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
}
项目:metl    文件:ExecutionRunPanel.java   
protected void download() {
    String stepId = (String) stepTable.getSelectedRow();
    if (stepId != null) {
        final File file = executionService.getExecutionStepLog(stepId);
        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {
                try {
                    return new FileInputStream(file);
                } catch (Exception e) {
                    log.error("Failed to download log file", e);
                    CommonUiUtils.notify("Failed to download log file", Type.ERROR_MESSAGE);
                    return null;
                }
            }
        };
        StreamResource resource = new StreamResource(ss, file.getName());
        final String KEY = "export";
        setResource(KEY, resource);
        Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
    }
}
项目:metl    文件:ImportXmlTemplateWindow.java   
protected void importXml(String text) {
    if (isNotBlank(text)) {
        SAXBuilder builder = new SAXBuilder();
        builder.setXMLReaderFactory(XMLReaders.NONVALIDATING);
        builder.setFeature("http://xml.org/sax/features/validation", false);
        try {
            Document document = builder.build(new StringReader(text));
            String rootName = document.getRootElement().getName();
            if (rootName.equals("definitions")) {
                importFromWsdl(text);
            } else if (rootName.equals("schema")) {
                importFromXsd(text);
            } else {
                Notification note = new Notification("Unrecognized Content", "The XML file has a root element of " + rootName
                        + ", but expected \"definitions\" for WSDL or \"schema\" for XSD.");
                note.show(Page.getCurrent());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
项目:metl    文件:ChangePasswordDialog.java   
protected void changePassword() {
    ISecurityService securityService = context.getSecurityService();
    IOperationsService operationsService = context.getOperationsSerivce();
    User user = context.getUser();
    String password = securityService.hash(user.getSalt(), currentPasswordField.getValue());
    if (user != null && user.getPassword() != null && user.getPassword().equals(password)) {
        if (testNewPassword()) {
            operationsService.savePassword(user, newPasswordField.getValue());
            close();
        }
    } else {
        String address = Page.getCurrent().getWebBrowser().getAddress();
        log.warn("Invalid change password attempt for user " + user.getLoginId()
                + " from address " + address);
        notify("Invalid Password", "The current password is invalid");
        currentPasswordField.selectAll();
    }

}
项目:metl    文件:ExportDialog.java   
protected void downloadExport(final String export, String filename) {

        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {
                try {
                    return new ByteArrayInputStream(export.getBytes(Charset.forName("utf-8")));
                } catch (Exception e) {
                    log.error("Failed to export configuration", e);
                    CommonUiUtils.notify("Failed to export configuration.", Type.ERROR_MESSAGE);
                    return null;
                }
            }
        };
        String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StreamResource resource = new StreamResource(ss, String.format("%s-config-%s.json", filename, datetime));
        final String KEY = "export";
        setResource(KEY, resource);
        Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
    }
项目:metl    文件:Diagram.java   
public void export() {
    // Lookup how large the canvas needs to be based on node positions.
    int maxHeight = 0;
    int maxWidth = 0;
    for (Node node : getState().nodes) {
        if (node.getX() > maxWidth) {
            maxWidth = node.getX();
        }
        if (node.getY() > maxHeight) {
            maxHeight = node.getY();
        }
    }
    // Pad Boundary to include text and margins.
    maxWidth += 200;
    maxHeight += 200;
    // Call client side code to create the canvas and display it.
    Page.getCurrent().getJavaScript().execute("exportDiagram("+maxWidth+","+maxHeight+");");
}
项目:sqlexplorer-vaadin    文件:CommonUiUtils.java   
public static void notify(String caption, String message, Throwable ex, Type type) {
    Page page = Page.getCurrent();
    if (page != null) {
        Notification notification = new Notification(caption, contactWithLineFeed(FormatUtils.wordWrap(message, 150)),
                Type.HUMANIZED_MESSAGE);
        notification.setPosition(Position.MIDDLE_CENTER);
        notification.setDelayMsec(-1);

        String style = ValoTheme.NOTIFICATION_SUCCESS;
        if (type == Type.ERROR_MESSAGE) {
            style = ValoTheme.NOTIFICATION_FAILURE;
        } else if (type == Type.WARNING_MESSAGE) {
            style = ValoTheme.NOTIFICATION_WARNING;
        }
        notification.setStyleName(notification.getStyleName() + " " + ValoTheme.NOTIFICATION_CLOSABLE + " " + style);
        notification.show(Page.getCurrent());
    }
}
项目:root    文件:UserLoginView.java   
/**
 * Validate user input with data in the database
 * @return true if user fits password in the database, false otherwise
 */
private void validateData() {
    String username = usernameField.getValue();
    String password = passwordField.getValue();

    if (UI.getCurrent() == null) {
        System.out.println("CurrentUI is null");
    }
    else if (((WoundManagementUI)UI.getCurrent()).getMySession() == null)
        System.out.println("My session is null");
    else if (getEnvironment() == null)
        System.out.println("Environment is null, session id is " + ((WoundManagementUI)UI.getCurrent()).getMySession().getId());
    else {
        getEnvironment().loginEmployee(username, password);
        boolean correctdata = getEnvironment().getCurrentEmployee() != null;

        if (correctdata) {
            getEnvironment().setCurrentUriFragment("patientSelection");
            Page.getCurrent().setUriFragment(getEnvironment().getCurrentUriFragment());
        } else {
            Notification.show(MessageResources.getString("incorrectData"));

            this.passwordField.setValue("");
        }
    }
}
项目:viritin    文件:ClearableTextField.java   
@Override
public void attach() {
    super.attach();
    // TODO optimize this so that it is added only once
    Page.getCurrent().getStyles().add(
            ".clearable-textfield .v-widget {\n"
            + " border-radius: 4px 4px 4px 4px;\n"
            + "}\n"
            + ".clearable-textfield .v-slot:last-child>.v-widget {\n"
            + " border-top-left-radius: 0;\n"
            + " border-bottom-left-radius: 0; margin-left:-1px\n"
            + "}\n"
            + "\n"
            + ".clearable-textfield .v-slot:first-child>.v-widget {\n"
            + " border-top-right-radius: 0;\n"
            + " border-bottom-right-radius: 0;\n"
            + "}\n");
}