Example usage for com.vaadin.server VaadinServlet getCurrent

List of usage examples for com.vaadin.server VaadinServlet getCurrent

Introduction

In this page you can find the example usage for com.vaadin.server VaadinServlet getCurrent.

Prototype

public static VaadinServlet getCurrent() 

Source Link

Document

Gets the currently used Vaadin servlet.

Usage

From source file:com.cerebro.provevaadin.Start.java

public Start() {

    InputStream iniFile = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/shiro.ini");
    if (iniFile == null) {
        logger.error("Il file Shiro.ini non esiste");
        return;/*  w  w w  .j a  va2  s .c o  m*/
    } else {
        logger.info("File presente");
    }
    Ini ini = new Ini();
    ini.load(iniFile);
    Factory<SecurityManager> factory = new IniSecurityManagerFactory(ini);
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    HorizontalLayout root = new HorizontalLayout();
    root.setWidth("800px");
    root.setHeight("600px");
    this.addComponent(root);
    this.setComponentAlignment(root, Alignment.MIDDLE_CENTER);

    FormLayout loginDiv = new FormLayout();
    root.addComponent(loginDiv);
    username.focus();
    errorMessage.setVisible(false);
    loginDiv.addComponents(username, password, rememberMe, login, errorMessage);

    login.addClickListener((Button.ClickEvent e) -> {
        logger.info("Pulsante: " + e.toString());
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username.getValue(), password.getValue());
        token.setRememberMe(rememberMe.getValue());
        try {
            currentUser.login(token);
            if (currentUser.hasRole("firsttime")) {
                logger.info("Configurazione parametri del primo avvio");
                getUI().setContent(new FirstTime());
            } else {
                logger.info("Classe di gioco principale");
                getUI().setContent(new Game());
                VaadinService.reinitializeSession(VaadinService.getCurrentRequest());
            }
        } catch (Exception ex) {
            logger.error("Errore nel login: " + ex.getMessage());
            username.setValue("");
            password.setValue("");
            errorMessage.setVisible(true);
        }
    });

    FormLayout signInForm = new FormLayout();
    root.addComponent(signInForm);
    usernameSignIn.focus();
    sesso.addItems("Maschio", "Femmina");
    signInForm.addComponents(usernameSignIn, passwordSignIn, passwordConf, nome, cognome, sesso, eta, signIn);
    signIn.addClickListener((Button.ClickEvent event) -> {
        logger.info("Iscrizione al sito");
        User utente = new User();
        utente.setEmail(usernameSignIn.getValue());
        utente.setPassword(passwordSignIn.getValue());
        utente.setNomeUtente(nome.getValue());
        utente.setCognomeUtente(cognome.getValue());
        utente.setSessoUtente(sesso.getValue().toString());
        utente.setDataNascitaUtente(eta.getValue());
        SignIn signInWindow = new SignIn(utente);
        signInWindow.center();
        UI.getCurrent().addWindow(signInWindow);
    });

}

From source file:com.foc.vaadin.FocWebApplication.java

License:Apache License

@Override
protected void init(VaadinRequest vaadinRequest) {
    HttpSession httpSession = null;/*from www .ja  v  a2s. c  o  m*/
    WrappedHttpSession wrapperHttpSession = VaadinSession.getCurrent() != null
            ? (WrappedHttpSession) VaadinSession.getCurrent().getSession()
            : null;
    if (wrapperHttpSession != null) {
        httpSession = wrapperHttpSession.getHttpSession();
    }

    initialize(vaadinRequest, VaadinServlet.getCurrent().getServletContext(), httpSession, false);
    initializeGUI(vaadinRequest, VaadinServlet.getCurrent().getServletContext(), httpSession);
}

From source file:com.foc.vaadin.gui.components.chart.JFreeChartWrapper_Modified.java

License:Apache License

@Override
public void attach() {
    //      super.attach();
    //      AbstractWebApplicationContext context = (AbstractWebApplicationContext) getUI().getContext();
    ServletContext context = VaadinServlet.getCurrent().getServletContext();
    if (mode == RenderingMode.AUTO) {
        WebBrowser webBrowser = getWebBrowser();
        if (webBrowser.isIE() && webBrowser.getBrowserMajorVersion() < 9) {
            setRenderingMode(RenderingMode.PNG);
        } else {//w  w  w . j  a v  a 2s .co m
            // all decent browsers support SVG
            setRenderingMode(RenderingMode.SVG);
        }
    }
    ;
    Image image = new Image("", getSource());

    chartLayout.addComponent(image);
    //VAADIN 7
    //      getApplication().addResource((ConnectorResource) getSource());

    setResource("src", getSource());//Antoine See Workarround from https://vaadin.com/forum#!/thread/8366526
    markAsDirtyRecursive();
}

From source file:com.haulmont.cuba.web.App.java

License:Apache License

/**
 * Called when <em>the first</em> UI of the session is initialized.
 *///  www.j  a  v  a  2s  .  c om
protected void init(Locale requestLocale) {
    VaadinSession vSession = VaadinSession.getCurrent();
    vSession.setAttribute(App.class, this);

    vSession.setLocale(messageTools.getDefaultLocale());

    // set root error handler for all session
    vSession.setErrorHandler(event -> {
        try {
            getExceptionHandlers().handle(event);
            getAppLog().log(event);
        } catch (Throwable e) {
            //noinspection ThrowableResultOfMethodCallIgnored
            log.error("Error handling exception\nOriginal exception:\n{}\nException in handlers:\n{}",
                    ExceptionUtils.getStackTrace(event.getThrowable()), ExceptionUtils.getStackTrace(e));
        }
    });

    appLog = new AppLog();

    connection = createConnection();
    exceptionHandlers = new ExceptionHandlers(this);
    cookies = new AppCookies();

    themeConstants = loadTheme();

    VaadinServlet vaadinServlet = VaadinServlet.getCurrent();
    ServletContext sc = vaadinServlet.getServletContext();
    String resourcesTimestamp = sc.getInitParameter("webResourcesTs");
    if (StringUtils.isNotEmpty(resourcesTimestamp)) {
        this.webResourceTimestamp = resourcesTimestamp;
    }

    log.debug("Initializing application");

    // get default locale from config
    Locale targetLocale = resolveLocale(requestLocale);
    setLocale(targetLocale);
}

From source file:com.hybridbpm.ui.component.development.FormEditor.java

License:Apache License

private void compileTheme() {
    try {/* w w  w.  j a va 2  s  .  c o  m*/
        binder.commit();
        ServletContext context = VaadinServlet.getCurrent().getServletContext();
        String fullPath = context.getRealPath("/VAADIN/themes/dashboard");
        String customScssFileName = fullPath + "/custom.scss";
        SassCompiler.writeFile(customScssFileName, module.getModel());

        ProcessBuilder processBuilder = new ProcessBuilder("java", "-cp", "../../../WEB-INF/lib/*",
                "com.vaadin.sass.SassCompiler", "styles.scss", "styles.css");
        processBuilder.directory(new File(fullPath));
        File error = new File(fullPath, "custom.scss.log");
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectError(Redirect.PIPE);
        Process process = processBuilder.start();
        process.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuilder builder = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            builder.append(line);
            line = reader.readLine();
        }
        reader.close();
        if (!builder.toString().trim().isEmpty()) {
            throw new Exception(builder.toString());
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        Notification.show("Error", ex.getMessage(), Notification.Type.ERROR_MESSAGE);
    }
}

From source file:de.catma.ui.CatmaApplication.java

License:Open Source License

private void initTempDirectory() throws IOException {
    String tempDirProp = RepositoryPropertyKey.TempDir.getValue();
    File tempDir = new File(tempDirProp);

    if (!tempDir.isAbsolute()) {
        this.tempDirectory = VaadinServlet.getCurrent().getServletContext().getRealPath(//TODO: check
                WEB_INF_DIR + System.getProperty("file.separator") + tempDirProp);
    } else {//w w  w. ja v a 2  s.c om
        this.tempDirectory = tempDirProp;
    }

    tempDir = new File(this.tempDirectory);
    if ((!tempDir.exists() && !tempDir.mkdirs())) {
        throw new IOException("could not create temporary directory: " + this.tempDirectory);
    }
}

From source file:edu.kit.dama.ui.admin.utils.UIHelper.java

License:Apache License

public static URI getWebAppUrl() {
    String baseUrl = DataManagerSettings.getSingleton()
            .getStringProperty(DataManagerSettings.GENERAL_BASE_URL_ID, "http://localhost:8080");
    return URI.create(baseUrl + VaadinServlet.getCurrent().getServletContext().getContextPath());
}

From source file:io.pivotal.pde.demo.tracker.gemfire.TrackerUI.java

@Override
protected void init(VaadinRequest request) {
    this.grid = new Grid();
    this.filter = new TextField();
    this.addNewBtn = new Button("Check In", FontAwesome.PLUS);

    ApplicationContext ctx = (ApplicationContext) VaadinServlet.getCurrent().getServletContext()
            .getAttribute("spring-context");
    this.repo = ctx.getBean(CheckInRepository.class);
    this.editor = ctx.getBean(CheckInEditor.class);

    // build layout
    HorizontalLayout actions = new HorizontalLayout(filter, addNewBtn);
    VerticalLayout mainLayout = new VerticalLayout(actions, grid, editor);
    setContent(mainLayout);/*from w  ww  .j av a  2s.  c  o m*/

    // Configure layouts and components
    actions.setSpacing(true);
    mainLayout.setMargin(true);
    mainLayout.setSpacing(true);

    grid.setHeight(300, Unit.PIXELS);
    grid.setWidth(550, Unit.PIXELS);
    grid.setColumns("plate", "city", "timestamp");
    grid.setContainerDataSource(new BeanItemContainer<CheckIn>(CheckIn.class));

    filter.setInputPrompt("Filter by License Plate");

    // Hook logic to components

    // Replace listing with filtered content when user changes filter
    filter.addTextChangeListener(e -> refillGrid(e.getText()));

    // Show the form when new button is clicked
    addNewBtn.addClickListener(e -> editor.newCheckIn());

    // Listen changes made by the editor, refresh data from backend
    editor.setChangeHandler(new CheckInEditor.ChangeHandler() {

        @Override
        public void onChange() {
            editor.setVisible(false);
            refillGrid(filter.getValue());
        }

    });

    CheckInCacheListener changeListener = ctx.getBean(CheckInCacheListener.class);
    changeListener.setHandler(this);

    // this.setPollInterval(5000);

    // Initialize listing
    refillGrid(null);
}

From source file:org.hip.vif.web.util.VIFAppHelper.java

License:Open Source License

/** Helper method to initialize the servlet context.<br />
 * This method sets the servlet's context path to <code>VSys</code> and initializes the
 * <code>DataSourceRegistry</code> singleton. */
public static void initializeContext() {
    final PreferencesHandler lPreferences = PreferencesHandler.INSTANCE;
    if (!lPreferences.isVifInitialized()) {
        final String lContextDir = VaadinServlet.getCurrent().getServletContext().getContextPath();
        if (lContextDir.length() <= 1) { // NOPMD by lbenno
            // embedded app, i.e. Jetty
            VSys.useConfPath(false);//from   www.j  ava 2  s.  c om
            final String lConfigPath = new File("").getAbsolutePath(); //$NON-NLS-1$
            VSys.setContextPath(lConfigPath);
        } else {
            // OSGi in servlet container, e.g. Tomcat
            VSys.useConfPath(true);
            VSys.setContextPath(VaadinServlet.getCurrent().getServletContext().getRealPath(""));
        }
        DataSourceRegistry.INSTANCE.setActiveConfiguration(lPreferences.getDBConfiguration());
        setLogDir();
        lPreferences.setVifInitialization(true);
    }
}

From source file:org.jumpmind.metl.ui.init.AppUI.java

License:Open Source License

public WebApplicationContext getWebApplicationContext() {
    return WebApplicationContextUtils
            .getRequiredWebApplicationContext(VaadinServlet.getCurrent().getServletContext());
}