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.bubblecloud.ilves.site.DefaultSiteUI.java

License:Apache License

@Override
protected Site constructSite(final VaadinRequest request) {
    // Construct entity manager for this site context.
    final EntityManager entityManager = entityManagerFactory.createEntityManager();
    // Construct audit entity manager for this site context.
    final EntityManager auditEntityManager = entityManagerFactory.createEntityManager();
    // Choose company for this site context.
    final VaadinServletRequest servletRequest = (VaadinServletRequest) VaadinService.getCurrentRequest();
    // The virtual host based on URL.
    final Company company = resolveCompany(entityManager, servletRequest);

    final SiteContext siteContext = new SiteContext(entityManager, auditEntityManager, servletRequest,
            securityProvider);//from w ww. j a va2 s  .c o m
    siteContext.putObject(EntityManager.class, entityManager);
    siteContext.putObject(EntityManagerFactory.class, entityManagerFactory);
    siteContext.putObject(Company.class, company);

    final X509Certificate[] clientCertificates = (X509Certificate[]) servletRequest.getHttpServletRequest()
            .getAttribute("javax.servlet.request.X509Certificate");

    if (clientCertificates != null && clientCertificates.length == 1
            && securityProvider.getUserFromSession() == null && company != null
            && company.isCertificateLogin()) {
        final User user = UserClientCertificateCache.getUserByCertificate(clientCertificates[0], true);
        if (user != null && user.getOwner().equals(company)) {
            securityProvider.setUser(user, UserDao.getUserGroups(entityManager, company, user));
            LOGGER.info("User certificate login: " + user.getEmailAddress() + " Remote address: "
                    + servletRequest.getHttpServletRequest().getRemoteAddr() + ":"
                    + servletRequest.getHttpServletRequest().getRemotePort() + ")");
        }
    }

    addCredentialPostRequestHandler();

    analyser = new SiteAnalyser(this, company.getGaTrackingId());
    this.getNavigator().addViewChangeListener(analyser);
    return new Site(SiteMode.PRODUCTION, contentProvider, localizationProvider, securityProvider, siteContext);
}

From source file:org.bubblecloud.ilves.ui.anonymous.login.ForgotPasswordFlowlet.java

License:Apache License

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

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

    fieldDescriptors.add(new FieldDescriptor("pin", getSite().localize("input-password-reset-pin"),
            TextField.class, null, 150, null, String.class, null, true, true, true));
    fieldDescriptors.add(new FieldDescriptor("emailAddress", getSite().localize("input-email-address"),
            TextField.class, null, 150, null, String.class, null, false, true, true)
                    .addValidator(new EmailValidator("Email address is not valid.")));

    editor = new ValidatingEditor(fieldDescriptors);

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

        @Override//from www  .  ja  v  a2  s  .c  o  m
        public void buttonClick(final ClickEvent event) {
            editor.commit();
            final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class);
            final Company company = getSite().getSiteContext().getObject(Company.class);

            final User user = UserDao.getUser(entityManager, company, (String) emailAddressProperty.getValue());
            if (user == null) {
                Notification.show(getSite().localize("message-user-email-address-not-registered"),
                        Notification.Type.WARNING_MESSAGE);
                return;
            }

            final List<EmailPasswordReset> emailPasswordResets = UserDao
                    .getEmailPasswordResetByEmailAddress(entityManager, user);
            final Date now = new Date();

            for (final EmailPasswordReset emailPasswordReset : emailPasswordResets) {
                if (now.getTime() - emailPasswordReset.getCreated().getTime() < 24 * 60 * 60 * 1000) {
                    Notification.show(getSite().localize("message-password-reset-email-already-sent"),
                            Notification.Type.ERROR_MESSAGE);
                    return;
                } else {
                    entityManager.getTransaction().begin();
                    try {
                        entityManager.remove(emailPasswordReset);
                        entityManager.getTransaction().commit();
                    } catch (final Exception e) {
                        if (entityManager.getTransaction().isActive()) {
                            entityManager.getTransaction().rollback();
                        }
                        throw new SiteException("Error removing old email password reset.", e);
                    }
                }
            }

            try {
                final String pin = (String) pinProperty.getValue();
                final byte[] pinAndSaltBytes = (user.getEmailAddress() + ":" + pin).getBytes("UTF-8");
                final MessageDigest md = MessageDigest.getInstance("SHA-256");
                final byte[] pinAndSaltDigest = md.digest(pinAndSaltBytes);

                final EmailPasswordReset emailPasswordReset = new EmailPasswordReset();
                emailPasswordReset.setUser(user);
                emailPasswordReset.setPinHash(StringUtil.toHexString(pinAndSaltDigest));
                emailPasswordReset.setCreated(now);

                entityManager.getTransaction().begin();
                try {
                    entityManager.persist(emailPasswordReset);
                    entityManager.getTransaction().commit();
                } catch (final Exception e) {
                    if (entityManager.getTransaction().isActive()) {
                        entityManager.getTransaction().rollback();
                    }
                    throw new SiteException("Error saving email password reset", e);
                }

                final String url = company.getUrl() + "#!reset/" + emailPasswordReset.getEmailPasswordResetId();

                final Thread emailThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EmailUtil.send(PropertiesUtil.getProperty("site", "smtp-host"), user.getEmailAddress(),
                                company.getSupportEmailAddress(), "Password Reset Link",
                                "Password reset has been requested for your user account."
                                        + "You can perform the reset using the following link: " + url);
                    }
                });
                emailThread.start();

                Notification.show(
                        getSite().localize("message-password-reset-email-sent")
                                + getSite().localize("message-your-password-reset-pin-is") + pin,
                        Notification.Type.WARNING_MESSAGE);

                final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest())
                        .getHttpServletRequest();
                LOGGER.info("Password reset email sent to " + user.getEmailAddress() + " (IP: "
                        + request.getRemoteHost() + ":" + request.getRemotePort() + ")");

                getFlow().back();
            } catch (final Exception e) {
                LOGGER.error("Error preparing password reset.", e);
                Notification.show(getSite().localize("message-password-reset-prepare-error"),
                        Notification.Type.WARNING_MESSAGE);
            }
            reset();
        }
    });

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

    reset();

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

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

    setViewContent(mainLayout);
}

From source file:org.bubblecloud.ilves.ui.anonymous.login.OpenIdLoginViewlet.java

License:Apache License

/**
 * SiteView constructSite occurred./*from 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;
        }

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

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

        SecurityService.updateUser(getSite().getSiteContext(), 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.bubblecloud.ilves.ui.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 ava 2  s .co m*/
        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.setStyleName(ValoTheme.BUTTON_PRIMARY);
    registerButton.addClickListener(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();
            invoicingAddress.setAddressLineOne("?");
            invoicingAddress.setAddressLineTwo("?");
            invoicingAddress.setAddressLineThree("?");
            invoicingAddress.setCity("?");
            invoicingAddress.setPostalCode("?");
            invoicingAddress.setCountry("?");
            final PostalAddress deliveryAddress = new PostalAddress();
            deliveryAddress.setAddressLineOne("?");
            deliveryAddress.setAddressLineTwo("?");
            deliveryAddress.setAddressLineThree("?");
            deliveryAddress.setCity("?");
            deliveryAddress.setPostalCode("?");
            deliveryAddress.setCountry("?");
            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));

                SecurityService.addUser(getSite().getSiteContext(), user,
                        UserDao.getGroup(entityManager, company, "user"));

                if (SiteModuleManager.isModuleInitialized(CustomerModule.class)) {
                    SecurityService.addCustomer(getSite().getSiteContext(), customer, 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.setMargin(true);
    mainLayout.addComponent(panel);

    final Panel mainPanel = new Panel();
    mainPanel.setSizeUndefined();
    mainPanel.setContent(mainLayout);

    setViewContent(mainPanel);
}

From source file:org.eclipse.hawkbit.ui.common.UserDetailsFormatter.java

License:Open Source License

public static UserDetails getCurrentUser() {
    final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    return (UserDetails) context.getAuthentication().getPrincipal();
}

From source file:org.eclipse.hawkbit.ui.HawkbitUI.java

License:Open Source License

/**
 * Get Locale for i18n./*from  w  ww.  j a va2s.  c o  m*/
 *
 * @return String as locales
 */
private static String[] getLocaleChain() {
    String[] localeChain = null;
    // Fetch all cookies from the request
    final Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();
    if (cookies == null) {
        return localeChain;
    }

    for (final Cookie c : cookies) {
        if (c.getName().equals(SPUIDefinitions.COOKIE_NAME) && !c.getValue().isEmpty()) {
            localeChain = c.getValue().split("#");
            break;
        }
    }
    return localeChain;
}

From source file:org.eclipse.hawkbit.ui.login.AbstractHawkbitLoginUI.java

License:Open Source License

private static Cookie getCookieByName(final String name) {
    // Fetch all cookies from the request
    final Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();

    if (cookies != null) {
        // Iterate to find cookie by its name
        for (final Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie;
            }//  ww  w. j  av  a2s.  c  o  m
        }
    }

    return null;
}

From source file:org.eclipse.hawkbit.ui.login.LoginView.java

License:Open Source License

private Cookie getCookieByName(final String name) {
    // Fetch all cookies from the request
    final Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();

    if (cookies != null) {
        // Iterate to find cookie by its name
        for (final Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie;
            }/*from   w  w w .j  av  a 2  s  .  co  m*/
        }
    }

    return null;
}

From source file:org.geant.sat.ui.UserShibImpl.java

License:BSD License

/**
 * Returns true if user is authenticated.
 *//*from w w  w.j ava  2  s. c  o  m*/
@Override
public boolean isAuthenticated() {
    if (VaadinService.getCurrentRequest().getWrappedSession().getAttribute(PRINCIPAL_KEY) == null) {
        updateUserInformation();
    }
    return VaadinService.getCurrentRequest().getWrappedSession().getAttribute(PRINCIPAL_KEY) != null;
}

From source file:org.geant.sat.ui.UserShibImpl.java

License:BSD License

/**
 * Get names of attribute/header fields.
 * //  ww w . j a va2  s . c  o  m
 * @return names enumeration.
 */
private Enumeration<String> getNames() {
    if (useHeaders) {
        return VaadinService.getCurrentRequest().getHeaderNames();
    }
    return VaadinService.getCurrentRequest().getAttributeNames();
}