Example usage for com.vaadin.server VaadinService getCurrentResponse

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

Introduction

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

Prototype

public static VaadinResponse getCurrentResponse() 

Source Link

Document

Gets the currently processed Vaadin response.

Usage

From source file:de.metas.ui.web.base.util.impl.HttpSessionProvider.java

License:Open Source License

@Override
public HttpServletResponse getCurrentResponse() {
    final VaadinResponse response = VaadinService.getCurrentResponse();
    if (response instanceof VaadinServletResponse) {
        return (VaadinServletResponse) response;
    } else {// w w  w .  ja v a 2s  .  c o  m
        throw new AdempiereException("Invalid response: " + response);
    }
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.QbicmainportletUI.java

License:Open Source License

/**
* 
*//*from w w  w  .j a v a  2  s.c  om*/
void errorMessageIfIsProduction() {
    if (isInProductionMode())
        try {
            VaadinService.getCurrentResponse().sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT,
                    "openbis could not be accessed.");
        } catch (IOException | IllegalArgumentException e1) {
            VaadinService.getCurrentResponse().setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        }
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.WorkflowComponent.java

License:Open Source License

/**
 * logs error and shows user that submission failed. Different exceptions yield different error
 * messages/*from   w w  w.  ja va 2 s  .co m*/
 * 
 * @param e
 */
public void handleException(Exception e) {
    if (e instanceof ConnectException || e instanceof IllegalArgumentException
            || e instanceof SubmitFailedException) {
        LOGGER.error("Submission failed, probably gUSE. " + e.getMessage(), e.getStackTrace());
        helpers.Utils.Notification("Workflow submission failed",
                "Requested workflow could not be submitted due to internal errors. Please try again later and contact your project manager if the problem persists.",
                "error");
        try {
            VaadinService.getCurrentResponse().sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT,
                    "An error occured, while trying to connect to the database. Please try again later, or contact your project manager.");
        } catch (IOException | IllegalArgumentException e1) {
            // TODO Auto-generated catch block
            LOGGER.error("Something went wrong: " + e.getMessage(), e.getStackTrace());
            VaadinService.getCurrentResponse().setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        }
    } else if (e instanceof RemoteAccessException) {
        LOGGER.error("Submission failed, probably openbis. error message: " + e.getMessage(),
                e.getStackTrace());
        helpers.Utils.Notification("Workflow submission failed",
                "Requested workflow could not be submitted due to internal errors. Please try again later and contact your project manager if the problem persists.",
                "error");
    } else {
        LOGGER.error("Internal error: " + e.getMessage(), e.getStackTrace());
        helpers.Utils.Notification("Workflow submission failed",
                "Requested workflow could not be submitted due to internal errors. Please try again later and contact your project manager if the problem persists.",
                "error");
    }
}

From source file:org.azrul.langkuik.Langkuik.java

public void initLangkuik(final EntityManagerFactory emf, final UI ui,
        final RelationManagerFactory relationManagerFactory, List<Class<?>> customTypeInterfaces) {

    List<Class<?>> rootClasses = new ArrayList<>();
    for (ManagedType<?> entity : emf.getMetamodel().getManagedTypes()) {
        Class<?> clazz = entity.getJavaType();
        if (clazz.getAnnotation(WebEntity.class).isRoot() == true) {
            rootClasses.add(clazz);//ww w .  j a va 2  s. c o m
        }
    }

    //Manage custom type
    if (customTypeInterfaces == null) {
        customTypeInterfaces = new ArrayList<>();
    }
    //add system level custom type
    customTypeInterfaces.add(AttachmentCustomType.class);
    //create DAOs for custom types
    final List<DataAccessObject<?>> customTypeDaos = new ArrayList<>();
    for (Class<?> clazz : customTypeInterfaces) {
        customTypeDaos.add(new HibernateGenericDAO(emf, clazz));
    }

    //Setup page
    VerticalLayout main = new VerticalLayout();
    VerticalLayout content = new VerticalLayout();
    final Navigator navigator = new Navigator(ui, content);
    final HorizontalLayout breadcrumb = new HorizontalLayout();

    MenuBar menubar = new MenuBar();
    menubar.setId("MENUBAR");
    main.addComponent(menubar);
    main.addComponent(breadcrumb);
    main.addComponent(content);

    final Deque<History> history = new ArrayDeque<>();
    final Configuration config = Configuration.getInstance();

    history.push(new History("START", "Start"));
    StartView startView = new StartView(history, breadcrumb);
    navigator.addView("START", startView);
    MenuBar.MenuItem create = menubar.addItem("Create", null);
    MenuBar.MenuItem view = menubar.addItem("View", null);

    final PageParameter pageParameter = new PageParameter(customTypeDaos, emf, relationManagerFactory, history,
            config, breadcrumb);

    for (final Class rootClass : rootClasses) {
        final WebEntity myObject = (WebEntity) rootClass.getAnnotation(WebEntity.class);
        final DataAccessObject<?> dao = new HibernateGenericDAO<>(emf, rootClass);
        create.addItem("New " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                Object object = dao.createNew(true);
                BeanView<Object, ?> createNewView = new BeanView<>(object, null, null, pageParameter);
                String targetView = "CREATE_NEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) createNewView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "Create new " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
        view.addItem("View " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                PlainTableView<?> seeApplicationView = new PlainTableView<>(rootClass, pageParameter);
                String targetView = "VIEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) seeApplicationView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "View " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
    }

    menubar.addItem("Logout", null).addItem("Logout", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            ConfirmDialog.show(ui, "Please Confirm:", "Are you really sure you want to log out?", "I am",
                    "Not quite", new ConfirmDialog.Listener() {
                        @Override
                        public void onClose(ConfirmDialog dialog) {
                            if (dialog.isConfirmed()) {
                                HttpServletRequest req = (HttpServletRequest) VaadinService.getCurrentRequest();
                                HttpServletResponse resp = (HttpServletResponse) VaadinService
                                        .getCurrentResponse();
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                SecurityContextLogoutHandler ctxLogOut = new SecurityContextLogoutHandler();
                                ctxLogOut.logout(req, resp, auth);
                            }
                        }
                    });

        }
    });
    navigator.navigateTo("START");
    ui.setContent(main);
}

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

License:Open Source License

private void setCookies() {
    if (multiTenancyIndicator.isMultiTenancySupported()) {
        final Cookie tenantCookie = new Cookie(SP_LOGIN_TENANT, tenant.getValue().toUpperCase());
        tenantCookie.setPath("/");
        // 100 days
        tenantCookie.setMaxAge(HUNDRED_DAYS_IN_SECONDS);
        tenantCookie.setHttpOnly(true);/*ww  w . ja va 2s.  c  o m*/
        tenantCookie.setSecure(uiProperties.getLogin().getCookie().isSecure());
        VaadinService.getCurrentResponse().addCookie(tenantCookie);
    }

    final Cookie usernameCookie = new Cookie(SP_LOGIN_USER, username.getValue());
    usernameCookie.setPath("/");
    // 100 days
    usernameCookie.setMaxAge(HUNDRED_DAYS_IN_SECONDS);
    usernameCookie.setHttpOnly(true);
    usernameCookie.setSecure(uiProperties.getLogin().getCookie().isSecure());
    VaadinService.getCurrentResponse().addCookie(usernameCookie);
}

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

License:Open Source License

private void setCookies() {
    if (multiTenancyIndicator.isMultiTenancySupported()) {
        final Cookie tenantCookie = new Cookie(SP_LOGIN_TENANT, tenant.getValue().toUpperCase());
        tenantCookie.setPath("/");
        // 100 days
        tenantCookie.setMaxAge(3600 * 24 * 100);
        tenantCookie.setHttpOnly(true);/*from  w  ww .j ava  2s . co m*/
        tenantCookie.setSecure(uiProperties.getLogin().getCookie().isSecure());
        VaadinService.getCurrentResponse().addCookie(tenantCookie);
    }

    final Cookie usernameCookie = new Cookie(SP_LOGIN_USER, username.getValue());
    usernameCookie.setPath("/");
    // 100 days
    usernameCookie.setMaxAge(3600 * 24 * 100);
    usernameCookie.setHttpOnly(true);
    usernameCookie.setSecure(uiProperties.getLogin().getCookie().isSecure());
    VaadinService.getCurrentResponse().addCookie(usernameCookie);
}

From source file:org.inakirj.imagerulette.utils.CookieManager.java

License:Open Source License

/**
 * Creates the cookie./*from  w  w w.j  a  v a 2  s  .  co m*/
 *
 * @return the cookie
 */
private Cookie createCookie() {
    Cookie newCookie = new Cookie(COOKIE_ID, "");
    newCookie.setComment("Saving urls for dice rulette");
    newCookie.setPath("/");
    newCookie.setMaxAge(60 * 60 * 24 * 365 * 10);
    VaadinService.getCurrentResponse().addCookie(newCookie);
    return newCookie;
}

From source file:org.inakirj.imagerulette.utils.CookieManager.java

License:Open Source License

/**
 * Save all URLs.// w  ww  .ja  va 2  s  .c  o  m
 *
 * @param urlList
 *            the url list
 */
public void saveAllURLs(List<String> urlList) {
    matchCookie();
    String cookieValue = urlList.stream().reduce("", (t, u) -> {
        if (t.isEmpty()) {
            return u;
        }
        return t + COOKIE_VALUE_SEPARATOR + u;
    });
    // This is needed, because when getting the cookie from browser those
    // attributes are not set
    appCookie.setValue(cookieValue);
    appCookie.setComment("Saving urls for dice rulette");
    appCookie.setPath("/");
    appCookie.setMaxAge(60 * 60 * 24 * 365 * 10);
    VaadinService.getCurrentResponse().addCookie(appCookie);
}

From source file:org.opencms.ui.login.CmsLoginController.java

License:Open Source License

/**
 * Called when the user clicks on the login button.<p>
 *//*from ww w. jav  a 2 s. c  o  m*/
public void onClickLogin() {

    String user = m_ui.getUser();
    String password = m_ui.getPassword();
    CmsMessageContainer message = CmsLoginHelper.validateUserAndPasswordNotEmpty(user, password);
    CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
    String storedMessage = null;
    if ((loginMessage != null) && !loginMessage.isLoginCurrentlyForbidden() && loginMessage.isActive()) {
        storedMessage = loginMessage.getMessage();
        // If login is forbidden, we will get an error message anyway, so we don't need to store the message here
    }
    if (message != null) {
        String errorMessage = message.key(m_params.getLocale());
        //  m_ui.displayError(errorMessage);
        displayError(errorMessage, true);
        return;
    }

    String ou = m_ui.getOrgUnit();
    String realUser = CmsStringUtil.joinPaths(ou, user);
    String pcType = m_ui.getPcType();
    CmsObject currentCms = A_CmsUI.getCmsObject();
    CmsUser userObj = null;

    try {
        try {
            userObj = currentCms.readUser(realUser, password);
        } catch (CmsException e) {
            LOG.warn(e.getLocalizedMessage(), e);
            message = org.opencms.workplace.Messages.get()
                    .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_0);
            displayError(message.key(m_params.getLocale()), true);
            return;
        }
        if (OpenCms.getLoginManager().canLockBecauseOfInactivity(currentCms, userObj)) {
            boolean locked = null != userObj.getAdditionalInfo().get(KEY_ACCOUNT_LOCKED);
            if (locked) {
                displayError(CmsInactiveUserMessages.getLockoutText(A_CmsUI.get().getLocale()), false);
                return;
            }
        }
        if (OpenCms.getLoginManager().requiresPasswordChange(currentCms, userObj)) {
            CmsChangePasswordDialog passwordDialog = new CmsChangePasswordDialog(currentCms, userObj,
                    A_CmsUI.get().getLocale());
            passwordDialog.setAdditionalMessage(getPasswordChangeMessage());
            A_CmsUI.get().setContentToDialog(
                    Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_PWCHANGE_HEADER_0)
                            + userObj.getSimpleName(),
                    passwordDialog);
            return;
        }
        currentCms.loginUser(realUser, password);
        if (LOG.isInfoEnabled()) {
            CmsRequestContext context = currentCms.getRequestContext();
            LOG.info(org.opencms.jsp.Messages.get().getBundle().key(
                    org.opencms.jsp.Messages.LOG_LOGIN_SUCCESSFUL_3, context.getCurrentUser().getName(),
                    "{workplace login dialog}", context.getRemoteAddress()));
        }
        OpenCms.getSessionManager().updateSessionInfo(currentCms,
                (HttpServletRequest) VaadinService.getCurrentRequest());
        if ((loginMessage != null) && loginMessage.isLoginCurrentlyForbidden()) {
            // we are an administrator
            storedMessage = org.opencms.workplace.Messages.get()
                    .container(org.opencms.workplace.Messages.GUI_LOGIN_SUCCESS_WITH_MESSAGE_2,
                            loginMessage.getMessage(), new Date(loginMessage.getTimeEnd()))
                    .key(A_CmsUI.get().getLocale());
        }

        if (storedMessage != null) {
            OpenCms.getSessionManager().sendBroadcast(null, storedMessage,
                    currentCms.getRequestContext().getCurrentUser());
        }
        CmsWorkplaceSettings settings = CmsLoginHelper.initSiteAndProject(currentCms);

        CmsLoginHelper.setCookieData(pcType, user, ou,
                (VaadinServletRequest) (VaadinService.getCurrentRequest()),
                (VaadinServletResponse) (VaadinService.getCurrentResponse()));
        VaadinService.getCurrentRequest().getWrappedSession()
                .setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings);

        final String loginTarget = getLoginTarget(currentCms, settings, m_params.getRequestedResource());
        final boolean isPublicPC = CmsLoginForm.PC_TYPE_PUBLIC.equals(pcType);
        if (OpenCms.getLoginManager().requiresUserDataCheck(currentCms, userObj)) {
            I_CmsDialogContext context = new A_CmsDialogContext("", ContextType.appToolbar, null) {

                @Override
                public void finish(CmsProject project, String siteRoot) {

                    finish(null);
                }

                @Override
                public void finish(Collection<CmsUUID> result) {

                    m_ui.openLoginTarget(loginTarget, isPublicPC);
                }

                public void focus(CmsUUID structureId) {

                    // nothing to do
                }

                public List<CmsUUID> getAllStructureIdsInView() {

                    return null;
                }

                @Override
                public void start(String title, Component dialog, DialogWidth style) {

                    if (dialog != null) {
                        m_window = CmsBasicDialog.prepareWindow(style);
                        m_window.setCaption(title);
                        m_window.setContent(dialog);
                        UI.getCurrent().addWindow(m_window);
                        if (dialog instanceof CmsBasicDialog) {
                            ((CmsBasicDialog) dialog).initActionHandler(m_window);
                        }
                    }
                }

                public void updateUserInfo() {

                    // not supported
                }
            };
            CmsUser u = currentCms.readUser(userObj.getId());
            u.setAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_LAST_USER_DATA_CHECK,
                    Long.toString(System.currentTimeMillis()));
            currentCms.writeUser(u);
            CmsUserDataDialog dialog = new CmsUserDataDialog(context, true);
            context.start(dialog.getTitle(UI.getCurrent().getLocale()), dialog);
        } else {

            m_ui.openLoginTarget(loginTarget, isPublicPC);
        }
    } catch (Exception e) {

        // there was an error during login
        if (e instanceof CmsException) {
            CmsMessageContainer exceptionMessage = ((CmsException) e).getMessageContainer();
            if (org.opencms.security.Messages.ERR_LOGIN_FAILED_DISABLED_2 == exceptionMessage.getKey()) {
                // the user account is disabled
                message = org.opencms.workplace.Messages.get()
                        .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_DISABLED_0);
            } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_TEMP_DISABLED_4 == exceptionMessage
                    .getKey()) {
                // the user account is temporarily disabled because of too many login failures
                message = org.opencms.workplace.Messages.get()
                        .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_TEMP_DISABLED_0);
            } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1 == exceptionMessage
                    .getKey()) {
                // all logins have been disabled be the Administration
                CmsLoginMessage loginMessage2 = OpenCms.getLoginManager().getLoginMessage();
                if (loginMessage2 != null) {
                    message = org.opencms.workplace.Messages.get().container(
                            org.opencms.workplace.Messages.GUI_LOGIN_FAILED_WITH_MESSAGE_1,
                            loginMessage2.getMessage());
                }
            }
        }
        if (message == null) {
            if (e instanceof CmsCustomLoginException) {
                message = ((CmsCustomLoginException) e).getMessageContainer();
            } else {
                // any other error - display default message
                message = org.opencms.workplace.Messages.get()
                        .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_0);
            }
        }

        //   m_ui.displayError(message.key(m_params.getLocale()));

        if (e instanceof CmsException) {
            CmsJspLoginBean.logLoginException(currentCms.getRequestContext(), user, (CmsException) e);
        } else {
            LOG.error(e.getLocalizedMessage(), e);
        }
        displayError(message.key(m_params.getLocale()), false);
        return;
    }
}

From source file:views.WorkflowView.java

License:Open Source License

/**
 * logs error and shows user that submission failed. Different exceptions yield different error
 * messages/*from ww w  .  j ava  2s  .co m*/
 * 
 * @param e
 */
public void handleException(Exception e) {
    if (e instanceof ConnectException || e instanceof IllegalArgumentException
            || e instanceof SubmitFailedException) {
        LOGGER.error("Submission failed, probably gUSE. " + e.getMessage(), e.getStackTrace());
        showNotification(SUBMISSION_FAILED_MESSAGE);
        try {
            VaadinService.getCurrentResponse().sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT,
                    "An error occured, while trying to connect to the database. Please try again later, or contact your project manager.");
        } catch (IOException | IllegalArgumentException e1) {
            // TODO Auto-generated catch block
            VaadinService.getCurrentResponse().setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        }
    } else if (e instanceof RemoteAccessException) {
        LOGGER.error("Submission failed, probably openbis. error message: " + e.getMessage(),
                e.getStackTrace());
        showNotification(SUBMISSION_FAILED_MESSAGE);
    } else {
        LOGGER.error("Internal error: " + e.getMessage(), e.getStackTrace());
        showNotification(SUBMISSION_FAILED_MESSAGE);
    }
}