Example usage for com.vaadin.server VaadinSession getCurrent

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

Introduction

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

Prototype

public static VaadinSession getCurrent() 

Source Link

Document

Gets the currently used session.

Usage

From source file:net.sourceforge.javydreamercsw.validation.manager.web.ValidationManagerUI.java

License:Apache License

@Override
protected void init(VaadinRequest request) {
    LOG.log(Level.INFO, "Current working directory: {0}", System.getProperty("user.home"));
    Page.getCurrent().setTitle("Validation Manager");
    updateScreen();/*from www.j a va2 s. c  om*/
    //For the code below see: https://vaadin.com/forum#!/thread/1553240/8194235
    JavaScript.getCurrent().addFunction("aboutToClose", (JsonArray arguments) -> {
        try {
            if (user != null) {
                int id = SESSIONS.get(VaadinSession.getCurrent().getSession().getId());
                VMUserServer u = new VMUserServer(id);
                LOG.log(Level.FINE, "Clearing session for user: {0}", u.toString());
                SESSIONS.remove(VaadinSession.getCurrent().getSession().getId());
            }
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    });

    Page.getCurrent().getJavaScript().execute(
            "window.onbeforeunload = function (e) { var e = e || window.event; aboutToClose(); return; };");
}

From source file:org.adho.dhconvalidator.ui.ConverterPanel.java

/** Setup behaviour. */
private void initActions() {
    upload.addSucceededListener(new SucceededListener() {

        @Override//from  w  w  w. j a  v  a 2 s  . c om
        public void uploadSucceeded(SucceededEvent event) {

            // the upload has successfully been finished

            try {
                // uploadedContent has been filled by the Receiver of this upload component
                // see initComponents below
                final byte[] uploadData = uploadContent.toByteArray();
                // do we have data?
                if (uploadData.length == 0) {
                    Notification.show(Messages.getString("ConverterPanel.fileSelectionTitle"),
                            Messages.getString("ConverterPanel.fileSelectionMsg"), Type.TRAY_NOTIFICATION);
                } else {
                    appendLogMessage(Messages.getString("ConverterPanel.progress1"));

                    // ok, let's do the conversion in the background
                    ((DHConvalidatorServices) UI.getCurrent()).getBackgroundService()
                            .submit(new DefaultProgressCallable<Pair<ZipResult, String>>() {
                                @Override
                                public Pair<ZipResult, String> call() throws Exception {
                                    // background execution!

                                    // do the actual conversion
                                    Converter converter = new Converter(PropertyKey.oxgarage_url.getValue());

                                    ZipResult zipResult = converter.convert(uploadData,
                                            ConversionPath.getConversionPathByFilename(filename),
                                            (User) VaadinSession.getCurrent()
                                                    .getAttribute(SessionStorageKey.USER.name()),
                                            filename, new ConversionProgressListener() {

                                                @Override
                                                public void setProgress(String msg) {
                                                    getProgressListener().setProgress(msg);
                                                }
                                            });

                                    return new Pair<ZipResult, String>(zipResult,
                                            converter.getContentAsXhtml());
                                }
                            }, new ExecutionListener<Pair<ZipResult, String>>() {
                                @Override
                                public void done(Pair<ZipResult, String> result) {
                                }

                                @Override
                                public void error(Throwable t) {
                                }
                            }, new ProgressListener() {

                                @Override
                                public void setProgress(String value, Object... args) {
                                    appendLogMessage(value);
                                }
                            });
                }
            } catch (Exception e) {
                // we don't expect many problems at this point since the main work takes place in the
                // background
                // but just in case
                LOGGER.log(Level.SEVERE, Messages.getString("ConverterPanel.syncErrorMsg"), e);
                String message = e.getLocalizedMessage();
                if (message == null) {
                    message = Messages.getString("ConverterPanel.conversionErrorNullReplacement");
                }
                appendLogMessage(Messages.getString("ConverterPanel.errorLogMsg", message));
            }
        }
    });
    upload.addStartedListener(new StartedListener() {

        @Override
        public void uploadStarted(StartedEvent event) {
            if (!event.getFilename().isEmpty()) {
                // clean everything for the new conversion
                cleanUp();
                progressBar.setVisible(true);
                //               UI.getCurrent().push();
            }
        }
    });

    upload.addFailedListener(new FailedListener() {

        @Override
        public void uploadFailed(FailedEvent event) {
            resultCaption.setValue(Messages.getString("ConverterPanel.previewTitle", filename));
            progressBar.setVisible(false);
        }
    });
}

From source file:org.adho.dhconvalidator.ui.ConverterPanel.java

/** @return the download stream of the {@link ZipResult}-data. */
private InputStream createResultStream() {
    try {// w w w . j av a2  s  .c o  m
        ZipResult result = (ZipResult) VaadinSession.getCurrent()
                .getAttribute(SessionStorageKey.ZIPRESULT.name());
        logArea.setValue("");
        confToolLabel.setVisible(true);
        //         UI.getCurrent().push();

        return new ByteArrayInputStream(result.toZipData());
    } catch (IOException e) {
        e.printStackTrace();
        Notification.show(Messages.getString("ConverterPanel.resultCreationErrorTitle"),
                Messages.getString("ConverterPanel.resultCreationErrorMsg"), Type.ERROR_MESSAGE);
        return null;
    }
}

From source file:org.adho.dhconvalidator.ui.ConverterPanel.java

@Override
public void enter(ViewChangeEvent event) {
    VaadinSession.getCurrent().setAttribute(SessionStorageKey.ZIPRESULT.name(), null);
    cleanUp();//from  w w w .  j av  a  2 s .c  o m
    resultCaption.setValue(Messages.getString("ConverterPanel.previewTitle2"));
    Page.getCurrent().setTitle(Messages.getString("ConverterPanel.pageTitle"));
}

From source file:org.adho.dhconvalidator.ui.DHConvalidatorServices.java

@Override
protected void init(VaadinRequest request) {

    Messages.setLocaleProvider(VaadinSessionLocaleProvider.INSTANCE);

    backgroundService = new UIBackgroundService(false);

    // are we logged in?
    if ((VaadinSession.getCurrent().getAttribute(SessionStorageKey.USER.name())) == null) {
        // no, show login box then
        setContent(new LoginPanel());
        Page.getCurrent().setTitle(Messages.getString("DHConvalidatorServices.loginTitle"));
    } else {//from   ww w .  j  a  v a 2s. c o  m
        // add available services and navigation
        Navigator navigator = new Navigator(this, this);
        navigator.addView("", new ServiceSelectionPanel());
        navigator.addView(ServicesViewName.odt.name(), new PaperSelectionPanel(new OdtInputConverter()));
        navigator.addView(ServicesViewName.docx.name(), new PaperSelectionPanel(new DocxInputConverter()));
        navigator.addView(ServicesViewName.converter.name(), new ConverterPanel());
        navigator.addView(ServicesViewName.templates.name(), new TemplateGeneratorPanel());
        navigator.addView(ServicesViewName.conftoolupload.name(), new ConfToolUploadPanel());

        // the visual feedback may reference external resources like images
        // the ExternalResourceRequestHandler serves those external resources from
        // the ZipResult of the conversion process
        try {
            VaadinSession.getCurrent().addRequestHandler(
                    new ExternalResourceRequestHandler(PropertyKey.tei_image_location.getValue()));
        } catch (IOException e) {
            throw new IllegalStateException(Messages.getString("DHConvalidatorServices.errorExampleFiles"), e);
        }
        Page.getCurrent().setTitle(Messages.getString("DHConvalidatorServices.servicesTitle"));
    }
}

From source file:org.adho.dhconvalidator.ui.ExternalResourceRequestHandler.java

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {

    // does the request concern us?
    if (request.getPathInfo().startsWith("/popup" + imagePath)) {
        ZipResult zipResult = (ZipResult) VaadinSession.getCurrent()
                .getAttribute(SessionStorageKey.ZIPRESULT.name());
        // if this is about the example picture we use the example ZipResult
        if (request.getPathInfo().endsWith(examplePictureName)) {
            zipResult = exampleZipResult;
        }/*from  w  ww  .ja v a2s.  c  o  m*/

        if (zipResult != null) {
            byte[] resource = zipResult
                    .getExternalResource(request.getPathInfo().substring(PATH_PREFIX_LENGTH));
            if (resource != null) {
                response.getOutputStream().write(resource);
                return true;
            } else {
                throw new IOException(Messages.getString("ExternalResourceRequestHandler.resourceNotFound",
                        request.getPathInfo().substring(PATH_PREFIX_LENGTH)));
            }
        }
    }
    return false;
}

From source file:org.adho.dhconvalidator.ui.LoginPanel.java

/**
 * Authentication via ConfTool.//from   w  w  w . j  a v a 2s  . c om
 *
 * @param username
 * @param pass
 */
protected void authenticate(String username, char[] pass) {
    UserProvider userProvider = PropertyKey.getUserProviderInstance();
    try {
        User user = userProvider.authenticate(username, pass);

        user = userProvider.getDetailedUser(user);

        VaadinSession.getCurrent().setAttribute(SessionStorageKey.USER.name(), user);
        UI.getCurrent().setContent(new LoginResultPanel());
    } catch (IOException e) {
        e.printStackTrace();
        UI.getCurrent().setContent(new LoginResultPanel(e.getLocalizedMessage()));
    } catch (UserProvider.AuthenticationException a) {
        a.printStackTrace();
        UI.getCurrent().setContent(new LoginResultPanel(a.getLocalizedMessage()));
    }
}

From source file:org.adho.dhconvalidator.ui.LoginResultPanel.java

/**
 * Setup UI./*from   ww  w.  j a v  a  2  s .c  o m*/
 *
 * @param errorMessage
 */
private void initComponents(String errorMessage) {
    logoutLink = new LogoutLink();
    logoutLink.setVisible(false);

    User user = (User) VaadinSession.getCurrent().getAttribute(SessionStorageKey.USER.name());

    // if authencication has been successful we open up a new tab to show the DHConvalidator
    // services
    btContinue = new Button(Messages.getString("LoginResultPanel.continue"));
    new BrowserWindowOpener(DHConvalidatorServices.class).extend(btContinue);

    btRetry = new Button(Messages.getString("LoginResultPanel.retry"));
    btRetry.setVisible(false);

    Label infoLabel = new Label("", ContentMode.HTML);
    if (errorMessage != null) {
        infoLabel.setValue(Messages.getString("LoginResultPanel.authenticationFailure", errorMessage));
        btContinue.setVisible(false);
        btRetry.setVisible(true);
    } else {
        infoLabel.setValue(
                Messages.getString("LoginResultPanel.greeting", user.getFirstName(), user.getLastName()));
        logoutLink.setVisible(true);
    }

    addCenteredComponent(logoutLink, Alignment.TOP_RIGHT);
    addCenteredComponent(infoLabel);
    addCenteredComponent(btContinue);
    addCenteredComponent(btRetry);
}

From source file:org.adho.dhconvalidator.ui.LogoutLink.java

public LogoutLink() {
    super(Messages.getString("LogoutLink.title"));
    setStyleName(BaseTheme.BUTTON_LINK);
    addStyleName("plain-link");
    addClickListener(new ClickListener() {

        @Override//  w w w .  j a  v  a2 s . co m
        public void buttonClick(ClickEvent event) {
            List<Page> pages = new ArrayList<>();
            // keep the pages...
            for (UI ui : VaadinSession.getCurrent().getUIs()) {
                Page page = ui.getPage();
                if (page != null) {
                    pages.add(page);
                }
            }

            VaadinSession.getCurrent().close();

            // ... to notify them of the session close
            for (Page p : pages) {
                try {
                    p.reload();
                } catch (Exception e) {
                    Logger.getLogger("");
                }
            }
        }
    });
}

From source file:org.adho.dhconvalidator.ui.PaperSelectionPanel.java

/** Load and display the current papers. */
private void initData() {
    postDownloadLabel.setVisible(false);

    paperTable.removeAllItems();//from   ww  w  . j  ava2s  .com
    try {
        List<Paper> papers = PropertyKey.getPaperProviderInstance()
                .getPapers((User) VaadinSession.getCurrent().getAttribute(SessionStorageKey.USER.name()));
        for (Paper paper : papers) {
            paperTable.addItem(new Object[] { paper.getTitle() }, paper);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Notification.show(Messages.getString("PaperSelectionPanel.error1Title"),
                Messages.getString("PaperSelectionPanel.conftoolerrormsg", e.getLocalizedMessage()),
                Type.ERROR_MESSAGE);
    }
}