Example usage for com.vaadin.server VaadinService getCurrentRequest

List of usage examples for com.vaadin.server VaadinService getCurrentRequest

Introduction

In this page you can find the example usage for com.vaadin.server VaadinService getCurrentRequest.

Prototype

public static VaadinRequest getCurrentRequest() 

Source Link

Document

Gets the currently processed Vaadin request.

Usage

From source file:org.vaadin.addons.sitekit.viewlet.anonymous.login.OpenIdLoginViewlet.java

License:Apache License

/**
 * SiteView constructSite occurred./*w w w  .j  a v  a  2  s .  c  o  m*/
 */
@Override
public void enter(final String parameterString) {

    final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
    final Company company = getSite().getSiteContext().getObject(Company.class);
    final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest())
            .getHttpServletRequest();

    try {
        final VerificationResult verification = OpenIdUtil.getVerificationResult(company.getUrl(),
                "openidlogin");
        final Identifier identifier = verification.getVerifiedId();

        if (identifier == null) {
            ((AbstractSiteUI) UI.getCurrent()).redirectTo(company.getUrl(), "login",
                    getSite().localize("message-login-failed") + ":" + verification.getStatusMsg(),
                    Notification.Type.ERROR_MESSAGE);
        }

        final User user = UserDao.getUserByOpenIdIdentifier(entityManager, company, identifier.getIdentifier());

        if (user == null) {
            LOGGER.warn("User OpenID login failed due to not registered Open ID identifier: "
                    + identifier.getIdentifier() + " (IP: " + request.getRemoteHost() + ":"
                    + request.getRemotePort() + ")");
            ((AbstractSiteUI) UI.getCurrent()).redirectTo(company.getUrl(), "login",
                    getSite().localize("message-login-failed"), Notification.Type.WARNING_MESSAGE);
            return;
        }

        if (user.isLockedOut()) {
            LOGGER.warn("User login failed due to user being locked out: " + user.getEmailAddress() + " (IP: "
                    + request.getRemoteHost() + ":" + request.getRemotePort() + ")");
            ((AbstractSiteUI) UI.getCurrent()).redirectTo(company.getUrl(), "login",
                    getSite().localize("message-login-failed"), Notification.Type.WARNING_MESSAGE);
            return;
        }

        final ProcessingContext processingContext = new ProcessingContext(entityManager, request, user,
                getSite().getSecurityProvider().getRoles());

        LOGGER.info("User login: " + user.getEmailAddress() + " (IP: " + request.getRemoteHost() + ":"
                + request.getRemotePort() + ")");
        AuditService.log(processingContext, "openid password login");

        final List<Group> groups = UserDao.getUserGroups(entityManager, company, user);

        UserDao.updateUser(entityManager, user);

        ((SecurityProviderSessionImpl) getSite().getSecurityProvider()).setUser(user, groups);

        ((AbstractSiteUI) UI.getCurrent()).redirectTo(company.getUrl(),
                getSite().getCurrentNavigationVersion().getDefaultPageName(),
                getSite().localize("message-login-success") + " (" + user.getEmailAddress() + ")",
                Notification.Type.HUMANIZED_MESSAGE);

    } catch (final Exception exception) {
        LOGGER.error("Error logging in OpenID user.", exception);
        ((AbstractSiteUI) UI.getCurrent()).redirectTo(company.getUrl(), "login",
                getSite().localize("message-login-error"), Notification.Type.ERROR_MESSAGE);
    }
}

From source file:org.vaadin.addons.sitekit.viewlet.anonymous.login.RegisterFlowlet.java

License:Apache License

@Override
public void initialize() {
    originalPasswordProperty = new ObjectProperty<String>(null, String.class);
    verifiedPasswordProperty = new ObjectProperty<String>(null, String.class);

    final List<FieldDescriptor> fieldDescriptors = new ArrayList<FieldDescriptor>();

    final PasswordValidator passwordValidator = new PasswordValidator(getSite(), originalPasswordProperty,
            "password2");

    //fieldDescriptors.addAll(SiteFields.getFieldDescriptors(Customer.class));

    for (final FieldDescriptor fieldDescriptor : SiteFields.getFieldDescriptors(Customer.class)) {
        if (fieldDescriptor.getId().equals("adminGroup")) {
            continue;
        }//from  w w  w .j a  v a 2  s .c  om
        if (fieldDescriptor.getId().equals("memberGroup")) {
            continue;
        }
        if (fieldDescriptor.getId().equals("created")) {
            continue;
        }
        if (fieldDescriptor.getId().equals("modified")) {
            continue;
        }
        fieldDescriptors.add(fieldDescriptor);
    }

    //fieldDescriptors.remove(fieldDescriptors.size() - 1);
    //fieldDescriptors.remove(fieldDescriptors.size() - 1);
    fieldDescriptors
            .add(new FieldDescriptor("password1", getSite().localize("input-password"), PasswordField.class,
                    null, 150, null, String.class, null, false, true, true).addValidator(passwordValidator));
    fieldDescriptors.add(new FieldDescriptor("password2", getSite().localize("input-password-verification"),
            PasswordField.class, null, 150, null, String.class, null, false, true, true)
                    .addValidator(new PasswordVerificationValidator(getSite(), originalPasswordProperty)));

    editor = new ValidatingEditor(fieldDescriptors);
    passwordValidator.setEditor(editor);

    final Button registerButton = new Button(getSite().localize("button-register"));
    registerButton.addListener(new ClickListener() {
        /** The default serial version ID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            editor.commit();
            customer.setCreated(new Date());
            customer.setModified(customer.getCreated());
            final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
            final Company company = getSite().getSiteContext().getObject(Company.class);

            final PostalAddress invoicingAddress = new PostalAddress();
            final PostalAddress deliveryAddress = new PostalAddress();
            customer.setInvoicingAddress(invoicingAddress);
            customer.setDeliveryAddress(deliveryAddress);

            if (UserDao.getUser(entityManager, company, customer.getEmailAddress()) != null) {
                Notification.show(getSite().localize("message-user-email-address-registered"),
                        Notification.Type.WARNING_MESSAGE);
                return;
            }

            final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest())
                    .getHttpServletRequest();

            try {
                final byte[] passwordAndSaltBytes = (customer.getEmailAddress() + ":"
                        + ((String) originalPasswordProperty.getValue())).getBytes("UTF-8");
                final MessageDigest md = MessageDigest.getInstance("SHA-256");
                final byte[] passwordAndSaltDigest = md.digest(passwordAndSaltBytes);

                customer.setOwner(company);
                final User user = new User(company, customer.getFirstName(), customer.getLastName(),
                        customer.getEmailAddress(), customer.getPhoneNumber(),
                        StringUtil.toHexString(passwordAndSaltDigest));

                if (UserDao.getGroup(entityManager, company, "user") == null) {
                    UserDao.addGroup(entityManager, new Group(company, "user", "Default user group."));
                }

                UserDao.addUser(entityManager, user, UserDao.getGroup(entityManager, company, "user"));
                CustomerDao.saveCustomer(entityManager, customer);
                UserDao.addGroupMember(entityManager, customer.getAdminGroup(), user);
                UserDao.addGroupMember(entityManager, customer.getMemberGroup(), user);

                final String url = company.getUrl() + "#!validate/" + user.getUserId();

                final Thread emailThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EmailUtil.send(PropertiesUtil.getProperty("site", "smtp-host"), user.getEmailAddress(),
                                company.getSupportEmailAddress(), "Email Validation",
                                "Please validate your email by browsing to this URL: " + url);
                    }
                });
                emailThread.start();

                LOGGER.info("User registered " + user.getEmailAddress() + " (IP: " + request.getRemoteHost()
                        + ":" + request.getRemotePort() + ")");
                Notification.show(getSite().localize("message-registration-success"),
                        Notification.Type.HUMANIZED_MESSAGE);

                getFlow().back();
            } catch (final Exception e) {
                LOGGER.error("Error adding user. (IP: " + request.getRemoteHost() + ":"
                        + request.getRemotePort() + ")", e);
                Notification.show(getSite().localize("message-registration-error"),
                        Notification.TYPE_WARNING_MESSAGE);
            }
            reset();
        }
    });

    editor.addListener(new ValidatingEditorStateListener() {
        @Override
        public void editorStateChanged(final ValidatingEditor source) {
            if (source.isValid()) {
                registerButton.setEnabled(true);
            } else {
                registerButton.setEnabled(false);
            }
        }
    });

    reset();

    final VerticalLayout panel = new VerticalLayout();
    panel.addComponent(editor);
    panel.addComponent(registerButton);
    panel.setSpacing(true);

    final HorizontalLayout mainLayout = new HorizontalLayout();
    mainLayout.addComponent(panel);

    setViewContent(mainLayout);
}

From source file:org.vaadin.spring.security.managed.DefaultVaadinManagedSecurity.java

License:Apache License

/**
 * Clears the session of all attributes except some internal Vaadin attributes and reinitializes it. If Websocket
 * Push is used, the session will never be reinitialized since this throws errors on at least
 * Tomcat 8.//from ww  w. j a v a  2  s  .  com
 */
protected void clearAndReinitializeSession() {
    final VaadinRequest currentRequest = VaadinService.getCurrentRequest();
    final UI currentUI = UI.getCurrent();
    if (currentUI != null) {
        final Transport transport = currentUI.getPushConfiguration().getTransport();
        if (Transport.WEBSOCKET.equals(transport) || Transport.WEBSOCKET_XHR.equals(transport)) {
            LOGGER.warn(
                    "Clearing and reinitializing the session is currently not supported when using Websocket Push.");
            return;
        }
    }
    if (currentRequest != null) {
        LOGGER.debug("Clearing the session");
        final WrappedSession session = currentRequest.getWrappedSession();
        final String serviceName = VaadinService.getCurrent().getServiceName();
        final Set<String> attributesToSpare = new HashSet<String>();
        attributesToSpare.add(serviceName + ".lock");
        attributesToSpare.add(VaadinSession.class.getName() + "." + serviceName);
        for (String s : currentRequest.getWrappedSession().getAttributeNames()) {
            if (!attributesToSpare.contains(s)) {
                LOGGER.trace("Removing attribute {} from session", s);
                session.removeAttribute(s);
            }
        }
        LOGGER.debug("Reinitializing the session {}", session.getId());
        VaadinService.reinitializeSession(currentRequest);
        LOGGER.debug("Session reinitialized, new ID is {}",
                VaadinService.getCurrentRequest().getWrappedSession().getId());
    } else {
        LOGGER.warn(
                "No VaadinRequest bound to current thread, could NOT clear/reinitialize the session after login");
    }
}

From source file:org.vaadin.tori.component.BBCodeWysiwygEditor.java

License:Apache License

private void configureTheme(final CKEditorConfig config) {
    String themesPath = VaadinService.getCurrentRequest().getContextPath() + "/VAADIN/themes/";
    String toriTheme = UI.getCurrent().getTheme() + "/";
    String toriCss = themesPath + toriTheme + "styles.css";
    config.setContentsCss(toriCss);//from w ww.  j  av a  2s  .  c om
    config.setBodyClass("v-app v-widget authoring post tori " + UI.getCurrent().getTheme());
}

From source file:pl.exsio.frameset.vaadin.i18n.locale.provider.ClientLocaleProviderImpl.java

License:Open Source License

private VaadinRequest getCurrentVaadinRequest() {
    return VaadinService.getCurrentRequest();
}

From source file:ui.button.LifetimeHomeButton.java

License:Apache License

@Override
public void buttonClick(ClickEvent event) {
    String path = VaadinService.getCurrentRequest().getContextPath();
    Page.getCurrent().setLocation(path);
}

From source file:ui.button.LogoutButton.java

License:Apache License

@Override
public void buttonClick(ClickEvent event) {
    VaadinSession.getCurrent().close();//  w  ww . j av  a2  s  .  c o m
    VaadinSession.getCurrent().getSession().invalidate();
    String path = VaadinService.getCurrentRequest().getContextPath();
    Page.getCurrent().setLocation(path);
    String msg = Translator.getTranslation("Loging out...", language);
    Notification.show(msg, Notification.Type.TRAY_NOTIFICATION);
    UI.getCurrent().close();
}

From source file:ui.button.UserHomeButton.java

License:Apache License

@Override
public void buttonClick(ClickEvent event) {
    String path = VaadinService.getCurrentRequest().getContextPath();
    Page.getCurrent().setLocation(path + "/user");
}

From source file:ui.button.VisitButton.java

License:Apache License

public VisitButton(final Integer userId, final Integer hostId, String hostname, String language) {
    super(hostname, FontAwesome.LINK);
    this.guest = userId;
    this.host = hostId;
    this.language = language;
    addClickListener(new ClickListener() {
        @Override/*  ww w. j  av  a  2s  .c  om*/
        public void buttonClick(ClickEvent event) {
            ServiceLocator.findLifetimeService().setHostId(guest, host);
            String path = VaadinService.getCurrentRequest().getContextPath();
            Page.getCurrent().setLocation(path + "/visitor");
        }
    });
}

From source file:xyz.iipster.security.SecurityUtilsImpl.java

License:Apache License

@Override
public Authentication login(String userName, String password) {
    Authentication authentication = authenticationManager
            .authenticate(new UsernamePasswordAuthenticationToken(userName, password));

    VaadinService.reinitializeSession(VaadinService.getCurrentRequest());
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return authentication;
}