Example usage for org.apache.wicket RestartResponseAtInterceptPageException RestartResponseAtInterceptPageException

List of usage examples for org.apache.wicket RestartResponseAtInterceptPageException RestartResponseAtInterceptPageException

Introduction

In this page you can find the example usage for org.apache.wicket RestartResponseAtInterceptPageException RestartResponseAtInterceptPageException.

Prototype

public RestartResponseAtInterceptPageException(Class<? extends Page> interceptPageClass) 

Source Link

Document

Redirects to the specified intercept page, this will result in a bookmarkable redirect.

Usage

From source file:com.madalla.webapp.authorization.AppAuthorizationStrategy.java

License:Apache License

/**
 * Construct./*from  ww w .j  a v  a  2  s  .  c o m*/
 *
 * @param signInPageClass
 *          The sign in page class
 * @param pageAuthorizations
 *          Collection of PageAuthorization that need to be authorized
 */
public AppAuthorizationStrategy(final Class<? extends Page> signInPageClass,
        Collection<PageAuthorization> pageAuthorizations) {

    this.pageAuthorizations = pageAuthorizations;

    // Handle unauthorized access to pages
    Application.get().getSecuritySettings()
            .setUnauthorizedComponentInstantiationListener(new IUnauthorizedComponentInstantiationListener() {
                public void onUnauthorizedInstantiation(final Component component) {
                    // If there is a sign in page class declared, and the
                    // unauthorized component is a page, but it's not the
                    // sign in page
                    if (component instanceof Page) {
                        // Redirect to page to let the user sign in
                        throw new RestartResponseAtInterceptPageException(signInPageClass);
                    } else {
                        // The component was not a page, so throw exception
                        throw new UnauthorizedInstantiationException(component.getClass());
                    }
                }
            });
}

From source file:com.madalla.webapp.components.member.LoginPanel.java

License:Apache License

/**
 * @param id/*from  ww w. ja  v a2s.c  o  m*/
 *            See Component constructor
 * @param includeRememberMe
 *            True if form should include a remember-me checkbox
 * @see org.apache.wicket.Component#Component(String)
 */
public LoginPanel(final String id, final ICredentialHolder credentials, final boolean includeRememberMe,
        Class<? extends Page> destination) {
    super(id);

    if (destination == null) {
        this.destination = getApplication().getHomePage();
    } else {
        this.destination = destination;
    }

    //if we have a valid populated credential then validate
    if (StringUtils.isNotEmpty(credentials.getUsername()) && StringUtils.isNotEmpty(credentials.getPassword())
            && signIn(credentials.getUsername(), credentials.getPassword())) {

        throw new RestartResponseAtInterceptPageException(destination);

    }

    this.includeRememberMe = includeRememberMe;

    final Form<Object> form = new SignInForm("signInForm", credentials);

    add(form);

    final FeedbackPanel feedback = new FeedbackPanel("loginFeedback");
    feedback.setOutputMarkupId(true);
    form.add(feedback);

    lockedLabel = new Label("lockedLabel",
            new StringResourceModel("label.locked", this, new Model<ICredentialHolder>(credentials)));
    lockedLabel.setVisibilityAllowed(true);
    lockedLabel.setVisible(false);
    form.add(lockedLabel);

    unlockUser = new AjaxLink<String>("unlockUser") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.add(form);
            lockUserName(false);
            credentials.setUsername("");
        }

    };
    unlockUser.setVisibilityAllowed(true);
    form.add(unlockUser);

    //set up depending on if we have a username or not
    lockUserName(StringUtils.isNotEmpty(credentials.getUsername()));

    AjaxButton submit = new IndicatingAjaxButton("submitLink", form) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            log.debug("Ajax onError called");
            target.add(feedback);
            onSignInFailed(getUsername());
        }

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            log.debug("Ajax submit called");
            target.add(form);
            preSignIn(getUsername());

            if (!isUserLocked()) {
                lockUserName(true);
            } else {
                if (signIn(getUsername(), getPassword())) {
                    feedback.info(getLocalizer().getString("signInFailed", this, "Success"));
                    onSignInSucceeded(target);
                } else {
                    feedback.error(getLocalizer().getString("signInFailed", this, "Sign in failed"));
                    target.add(feedback);
                    onSignInFailed(getUsername());
                }

            }

        }

    };
    submit.setEnabled(true);

    //submit.setVisibilityAllowed(true);
    form.add(submit);
    form.add(new AttributeModifier("onSubmit", true, new Model<String>(
            "document.getElementById('" + submit.getMarkupId() + "').onclick();return false;")));

}

From source file:com.madalla.webapp.login.LoginPanel.java

License:Apache License

/**
 * @param id/*from  ww  w.j  a va2 s  .  c o  m*/
 *            See Component constructor
 * @see org.apache.wicket.Component#Component(String)
 */
public LoginPanel(final String id, final ICredentialHolder credentials, Class<? extends Page> destination) {
    super(id);

    if (destination == null) {
        this.destination = getApplication().getHomePage();
    } else {
        this.destination = destination;
    }

    // if we have a valid populated credential then validate
    if (StringUtils.isNotEmpty(credentials.getUsername()) && StringUtils.isNotEmpty(credentials.getPassword())
            && signIn(credentials.getUsername(), credentials.getPassword())) {

        throw new RestartResponseAtInterceptPageException(destination);

    }

    final Form<Void> form = new SignInForm("signInForm", credentials);
    add(form);

    final FeedbackPanel feedback = new FeedbackPanel("loginFeedback");
    feedback.setOutputMarkupId(true);
    form.add(feedback);

    lockedLabel = new Label("lockedLabel",
            new StringResourceModel("label.locked", this, new Model<ICredentialHolder>(credentials)));
    lockedLabel.setVisibilityAllowed(true);
    lockedLabel.setVisible(false);
    form.add(lockedLabel);

    unlockUser = new AjaxLink<String>("unlockUser") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.add(form);
            lockUserName(false);
            credentials.setUsername("");
        }

    };
    unlockUser.setVisibilityAllowed(true);
    form.add(unlockUser);

    // set up depending on if we have a username or not
    lockUserName(StringUtils.isNotEmpty(credentials.getUsername()));

    AjaxButton submit = new IndicatingAjaxButton("submitLink", form) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            log.debug("Ajax onError called");
            target.add(feedback);
            target.add(form);
            onSignInFailed(getUsername());
        }

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            log.debug("Ajax onSubmit. userName=" + getUsername());
            target.add(form);
            preSignIn(getUsername());

            if (!isUserLocked()) {
                lockUserName(true);
            } else {
                if (signIn(getUsername(), getPassword())) {
                    feedback.info(getLocalizer().getString("signInFailed", this, "Success"));
                    onSignInSucceeded(target);
                } else {
                    feedback.error(getLocalizer().getString("signInFailed", this, "Sign in failed"));
                    target.add(feedback);
                    onSignInFailed(getUsername());
                }

            }

        }

    };
    submit.setEnabled(true);
    form.setDefaultButton(submit);

    // submit.setVisibilityAllowed(true);
    form.add(submit);
    form.add(new AttributeModifier("onSubmit", new Model<String>(
            "document.getElementById('" + submit.getMarkupId() + "').onclick();return false;")));

}

From source file:com.servoy.j2db.server.headlessclient.ServoyRequestCycle.java

License:Open Source License

/**
 * @see org.apache.wicket.protocol.http.WebRequestCycle#newClientInfo()
 *//*from ww  w .  ja v a2  s.com*/
@Override
protected ClientInfo newClientInfo() {
    // We will always do a redirect here. The servoy browser info has to make one.
    WebClientInfo webClientInfo = new WebClientInfo(this);
    ClientProperties cp = webClientInfo.getProperties();
    if (cp.isBrowserInternetExplorer() || cp.isBrowserMozilla() || cp.isBrowserKonqueror()
            || cp.isBrowserOpera() || cp.isBrowserSafari() || cp.isBrowserChrome()) {
        if (cp.isBrowserInternetExplorer() && cp.getBrowserVersionMajor() != -1
                && cp.getBrowserVersionMajor() < 7) {
            // IE6 is no longer supported when anchoring is enabled.
            boolean enableAnchoring = Utils.getAsBoolean(Settings.getInstance()
                    .getProperty("servoy.webclient.enableAnchors", Boolean.TRUE.toString())); //$NON-NLS-1$ 
            if (enableAnchoring) {
                throw new RestartResponseException(new UnsupportedBrowserPage("Internet Explorer 6")); //$NON-NLS-1$
            }
        }
        Page page = getResponsePage();
        if (page != null) {
            throw new RestartResponseAtInterceptPageException(
                    new ServoyBrowserInfoPage(urlFor(page).toString().replaceAll("../", ""))); //$NON-NLS-1$ //$NON-NLS-2$
        } else {
            throw new RestartResponseAtInterceptPageException(new ServoyBrowserInfoPage(getRequest().getURL()));
        }
    }
    return webClientInfo;
}

From source file:com.servoy.j2db.server.headlessclient.SolutionLoader.java

License:Open Source License

public SolutionLoader(PageParameters pp) {
    SolutionMetaData theReq = null;//  w w  w .j  ava 2s .  c  o  m

    try {
        if (ApplicationServerRegistry.get().getDataServer().isInGlobalMaintenanceMode()
                || ApplicationServerRegistry.get().getDataServer().isInServerMaintenanceMode()) {
            // do this before redirect & register client - where it is usually detected, because when clustered
            // this should result in a valid switch to another server in the cluster by the load balancer; if we wait until
            // after redirect, a page expired will happen on the other server

            //         throw new AbortWithHttpStatusException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, false); this works, but doesn't show maintenance error page for non-clustered case

            Session.get().invalidate();
            RequestCycle.get().setRedirect(false);
            throw new RestartResponseException(new ServoyServerInMaintenanceMode());
        }
    } catch (RemoteException e) {
        // will not happen
        throw new RuntimeException(e);
    }

    FeedbackPanel feedback = new FeedbackPanel("feedback");
    add(feedback);

    StartupArguments argumentsScope = new StartupArguments(pp);

    String solutionName = argumentsScope.getSolutionName();
    String method = argumentsScope.getMethodName();
    String firstArgument = argumentsScope.getFirstArgument();

    try {
        IRepository repository = ApplicationServerRegistry.get().getLocalRepository();
        SolutionMetaData smd = (SolutionMetaData) repository.getRootObjectMetaData(solutionName,
                IRepository.SOLUTIONS);
        if (smd == null || smd.getSolutionType() == SolutionMetaData.SOLUTION
                || smd.getSolutionType() == SolutionMetaData.WEB_CLIENT_ONLY
                || ((smd.getSolutionType() == SolutionMetaData.MOBILE
                        || smd.getSolutionType() == SolutionMetaData.MODULE)
                        && ApplicationServerRegistry.get().isDeveloperStartup())) {
            theReq = smd;
        } else {
            Debug.log("Not loading solution " + smd.getName() + ", it is not configured for webclient usage");
            theReq = null;
        }

        if (theReq != null) {
            Solution sol = (Solution) repository.getActiveRootObject(solutionName, IRepository.SOLUTIONS);
            if (sol.getLoginSolutionName() == null && sol.getLoginFormID() <= 0 && theReq.getMustAuthenticate()
                    && !((WebClientSession) getSession()).isSignedIn()) {
                String authType = pp.getString("sv_auth_type"); //$NON-NLS-1$
                boolean authorized = false;
                if ((authType != null && authType.equals("basic")) || //$NON-NLS-1$
                        (authType == null && Utils.getAsBoolean(Settings.getInstance()
                                .getProperty("servoy.webclient.basic.authentication", "false")))) //$NON-NLS-1$ //$NON-NLS-2$
                {
                    String authorizationHeader = ((WebRequest) RequestCycle.get().getRequest())
                            .getHttpServletRequest().getHeader("Authorization"); //$NON-NLS-1$
                    if (authorizationHeader != null) {
                        String authorization = authorizationHeader.substring(6);
                        // TODO: which encoding to use? see http://tools.ietf.org/id/draft-reschke-basicauth-enc-05.xml
                        authorization = new String(Utils.decodeBASE64(authorization));
                        int index = authorization.indexOf(':');
                        if (index > 0) {
                            String username = authorization.substring(0, index);
                            String password = authorization.substring(index + 1);
                            authorized = ((WebClientSession) getSession()).authenticate(username, password);
                        }
                    }
                    if (!authorized) {
                        ((WebResponse) RequestCycle.get().getResponse()).getHttpServletResponse()
                                .setHeader("WWW-Authenticate", "Basic realm=\"webclient\""); //$NON-NLS-1$ //$NON-NLS-2$
                        throw new AbortWithWebErrorCodeException(401);
                    }
                }

                if (!authorized) {
                    //signin first
                    throw new RestartResponseAtInterceptPageException(SignIn.class);
                }
            }
            WebClientSession session;
            HttpSession httpSession;
            synchronized (sol) {
                // create the http session
                httpSession = ((WebRequest) RequestCycle.get().getRequest()).getHttpServletRequest()
                        .getSession();
                Session.unset();
                session = (WebClientSession) getSession();
                session.bind();
                session.getClientInfo();
            }
            synchronized (httpSession) {
                IWebClientApplication sc = session.getWebClient();
                if (sc != null && sc.getSolution() != null
                        && sc.getFlattenedSolution().getMainSolutionMetaData().getName().equals(solutionName)) {
                    // make sure it is registered as a start of a request.
                    session.getWebClient().onBeginRequest(session);
                    FormManager formManager = ((FormManager) sc.getFormManager());
                    String currentPageMapName = getPageMap().getName();
                    if (currentPageMapName != null && !Utils
                            .equalObjects(sc.getMainPage().getPageMap().getName(), currentPageMapName)) {
                        IMainContainer newContainer = formManager.getOrCreateMainContainer(currentPageMapName);
                        formManager.setCurrentContainer(newContainer, currentPageMapName);
                    }
                    // remove the method/argument from the page parameters, they shouldn't be used to generate a redirect url.
                    pp.remove("method"); //$NON-NLS-1$
                    pp.remove("m"); //$NON-NLS-1$
                    pp.remove("argument"); //$NON-NLS-1$
                    pp.remove("a"); //$NON-NLS-1$

                    // also remove client method arguments to avoid stackoverflow for deeplinked authenticate solutions (js_login called inside deeplinked method)
                    sc.handleArguments(null);
                    if (method != null) {
                        try {
                            sc.getScriptEngine().getScopesScope().executeGlobalFunction(null, method,
                                    (firstArgument == null ? null
                                            : new Object[] { firstArgument, argumentsScope.toJSMap() }),
                                    false, false);
                        } catch (Exception e1) {
                            sc.reportError(
                                    Messages.getString("servoy.formManager.error.ExecutingOpenSolutionMethod", //$NON-NLS-1$
                                            new Object[] { method }),
                                    e1);
                        }
                    }
                    if (formManager.getCurrentContainer().getController() == null) {
                        Iterator<Form> e = sc.getFlattenedSolution().getForms(true);
                        // add all forms first, they may be referred to in the login form
                        Form first = sc.getFlattenedSolution().getForm(sc.getSolution().getFirstFormID());
                        boolean formCanBeInstantiated = sc.getFlattenedSolution().formCanBeInstantiated(first);
                        while (!formCanBeInstantiated && e.hasNext()) {
                            Form form = e.next();
                            formCanBeInstantiated = sc.getFlattenedSolution().formCanBeInstantiated(form);
                            if (formCanBeInstantiated)
                                first = form;
                        }
                        if (first != null) {
                            formManager.showFormInCurrentContainer(first.getName());
                        }
                    }

                } else {
                    sc = session.startSessionClient(theReq, method, argumentsScope);
                }
                if (sc.isValid()) {
                    Page page = sc.getMainPage();
                    // do get it from the real wicket session so that a lock is set on this page. (or waited for the lock)
                    Page p = session.getPage(page.getPageMapName(), page.getId(),
                            page.getCurrentVersionNumber());
                    if (p instanceof MainPage) {
                        page = p;
                        ShowUrlInfo urlScript = ((MainPage) p).getShowUrlInfo();
                        if (urlScript != null && "_self".equals(urlScript.getTarget())) {
                            // a redirect was found to it self, just redirect directly to that one.
                            // clear the current main pages show url script first.
                            ((MainPage) p).getShowUrlScript();
                            RequestCycle.get().setRequestTarget(new RedirectRequestTarget(urlScript.getUrl()));
                            return;
                        }
                    }

                    HybridUrlCodingStrategy.setInitialPageParameters(page, pp);
                    setResponsePage(page);
                    setRedirect(true);
                    //setRedirect(Utils.getAsBoolean(sc.getSettings().getProperty("servoy.webclient.nice.urls", "false")));
                }
            }
        }
    } catch (RestartResponseAtInterceptPageException restart) {
        setRedirect(false);
        throw restart;
    } catch (AbortException abort) {
        setRedirect(true);
        throw abort;
    } catch (Exception e) {
        Debug.error(e);
        error(e.toString());
    }
}

From source file:com.servoy.j2db.server.headlessclient.WebClientSession.java

License:Open Source License

@SuppressWarnings("nls")
public IWebClientApplication startSessionClient(RootObjectMetaData sd, String method,
        StartupArguments argumentsScope) throws Exception {
    String firstArgument = argumentsScope.getFirstArgument();
    IWebClientApplication webClient = getWebClient();
    if (webClient != null) {
        boolean solutionLoaded = webClient.getSolution() != null;
        if (solutionLoaded && !webClient.closeSolution(false, null)) {
            return webClient; // not allowed to close solution?
        }/*from  w w  w  .j  ava 2 s. co  m*/

        if (solutionLoaded && isSignedIn()
                && !Utils.getAsBoolean(
                        Settings.getInstance().getProperty("servoy.allowSolutionBrowsing", "true"))
                && !sd.getName().equals(keepCredentialsSolutionName)) {
            webClient.logout(null);
        }
        if (!isSignedIn()) {
            SolutionMetaData smd = (SolutionMetaData) sd;
            IRepository repository = ApplicationServerRegistry.get().getLocalRepository();
            Solution sol = (Solution) repository.getActiveRootObject(smd.getName(), IRepository.SOLUTIONS);
            if (sol.getLoginSolutionName() == null && sol.getLoginFormID() <= 0 && smd.getMustAuthenticate()) {
                //signin first
                throw new RestartResponseAtInterceptPageException(SignIn.class);
            }
        }
        keepCredentialsSolutionName = null;
    }
    if (webClient == null || webClient.isShutDown()) {
        HttpServletRequest req = ((WebRequest) RequestCycle.get().getRequest()).getHttpServletRequest();
        httpSession = req.getSession();
        webClient = createWebClient(req, credentials, method,
                firstArgument == null ? null : new Object[] { firstArgument, argumentsScope.toJSMap() },
                sd.getName());
        webClient.handleArguments(new String[] { sd.getName() }, argumentsScope);
        if (RequestCycle.get() != null) {
            // if this is inside a request cycle set the service provider.
            // will be reset by the detach of the RequestCycle.
            J2DBGlobals.setServiceProvider(webClient);
        }
        setAttribute("servoy_webclient", webClient);
    } else {
        webClient.handleArguments(firstArgument != null ? new String[] { sd.getName(), method, firstArgument }
                : new String[] { sd.getName(), method }, argumentsScope);
    }

    webClient.handleClientUserUidChanged(null, ""); // fake first load
    if (webClient.getSolution() != null)
        getSolutionLastModifiedTime(webClient.getSolution());
    else {
        if (webClient.getPreferedSolutionNameToLoadOnInit() != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("s", webClient.getPreferedSolutionNameToLoadOnInit());
            map.put("m", webClient.getPreferedSolutionMethodNameToCall());
            if (webClient.getPreferedSolutionMethodArguments() != null
                    && webClient.getPreferedSolutionMethodArguments().length > 0) {
                map.put("a", webClient.getPreferedSolutionMethodArguments()[0]);
            }
            throw new RestartResponseException(SolutionLoader.class, new PageParameters(map));
        }
    }
    return webClient;
}

From source file:com.socialsite.authentication.SocialSiteUnauthorizedComponentInstantiationListener.java

License:Open Source License

/**
 * Redirects to the LogingPage if the user is not authorized
 * //  w w w  .  j  a  v a2 s .co m
 * @param component
 *            component which failed the authorization check
 */
public void onUnauthorizedInstantiation(final Component component) {
    throw new RestartResponseAtInterceptPageException(LoginPage.class);

}

From source file:com.ttdev.wicketpagetest.sample.guice.PageRequiringLogin.java

License:Open Source License

public PageRequiringLogin() {
    MySession session = (MySession) WebSession.get();
    String currentUser = session.getCurrentUser();
    if (currentUser == null) {
        throw new RestartResponseAtInterceptPageException(LoginPage.class);
    }//from  w w  w  .j a  v  a  2s  .  c  om
    add(new Label("name", currentUser));
}

From source file:com.tysanclan.site.projectewok.auth.TysanSecurity.java

License:Open Source License

/**
 * @see org.apache.wicket.application.IComponentInstantiationListener#onInstantiation(org.apache.wicket.Component)
 *///w  w  w . j  a va  2 s. c  o  m
@Override
public void onInstantiation(Component component) {
    // Check authorization
    if (!authorize(component.getClass())) {
        // If not authorized, redirect to access denied page
        throw new RestartResponseAtInterceptPageException(AccessDeniedPage.class);
    }

}

From source file:com.tysanclan.site.projectewok.components.InactiveKeyRoleTransferPanel.java

License:Open Source License

public InactiveKeyRoleTransferPanel(String id, RoleType roleType) {
    super(id);/*from w w  w. j av a  2 s  .  c o m*/

    Role role = roleService.getRoleByType(roleType);

    if (role == null)
        throw new RestartResponseAtInterceptPageException(AccessDeniedPage.class);

    UserFilter filter = new UserFilter();
    filter.setRetired(false);
    filter.addRank(Rank.REVERED_MEMBER);
    filter.addRank(Rank.FULL_MEMBER);
    filter.addRank(Rank.SENIOR_MEMBER);
    filter.setTruthsayerNominated(false);
    filter.addOrderBy("username", true);

    List<User> users = userDAO.findByFilter(filter);

    final DropDownChoice<User> userChoice = new TysanDropDownChoice<User>("user", null, users);
    userChoice.setNullValid(false);
    userChoice.setRequired(true);

    nominationForm = new Form<RoleType>("transferForm", new Model<RoleType>(roleType)) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            roleService.initiateTransfer(getModelObject(), userChoice.getModelObject());

            setResponsePage(new InactiveKeyRoleTransferPage());
        }

    };

    nominationForm.add(userChoice);
    nominationForm.add(new Label("name", role.getName()).setRenderBodyOnly(true));
    nominationForm.add(new Label("name2", role.getName()).setRenderBodyOnly(true));
    nominationForm.add(new Label("name3", role.getName()).setRenderBodyOnly(true));

    add(nominationForm);
}