Tapestry: How to display an alert dialog from my Java code - java

I'm actually writing a java code in the setupRender() method. Depending of a value provided by the server side, i would like to display an Alert dialog box to the user. By clicking on ok, the application should be closed.
I have not already found how to display an Alert dialog box with tapestry. Do somebody know how to procedd?
Thanks

It's not quite clear to me what you are trying to achieve, but perhaps the following two suggestions are useful.
Suggestion 1 - Display a message using AlertManager
In the page class, inject AlertManager and add the message to it.
public class YourPage {
#Inject
AlertManager alertManager;
Object setupRender() {
// ...
alertManager.alert(Duration.UNTIL_DISMISSED, Severity.INFO, "Love Tapestry");
}
}
Then use the <t:alerts/> component in the page template file to have the message displayed.
Note: The user may dismiss the message, that is, make it disappear. But it doesn't 'close the application' (whatever it is that you mean by that).
Suggestion 2 - Redirect to another page
The setupRender method can return different things. For example, it could return another page class, causing a redirect to that page. On that page, you could have the messages displayed and the session subsequently invalidated (if that's what you meant by 'application should be closed'.
public class YourPage {
Object setupRender() {
// ...
return AnotherPage.class;
}
}
public class AnotherPage {
#Inject
Request request;
void afterRender() {
Session session = request.getSession(false);
session.invalidate();
}
}
See the Tapestry docs for details about what setupRender() can return.
Suggestion 3 - Use JavaScript to display Alert and trigger Component Event
This approach uses JavaScript to display an Alert and subsequently trigger a component event via ajax. The event handler takes care of invalidating the session.
Note: Closing the current browser windows/tab with JavaScript isn't as easy as it used to be. See this Stackoverflow question for details.
YourPage.java
public class YourPage {
boolean someCondition;
void setupRender() {
someCondition = true;
}
#Inject
private JavaScriptSupport javaScriptSupport;
#Inject
ComponentResources resources;
public static final String EVENT = "logout";
void afterRender() {
if (someCondition) {
Link link = resources.createEventLink(EVENT);
JSONObject config = new JSONObject(
"msg", "See ya.",
"link", link.toAbsoluteURI()
);
javaScriptSupport.require("LogoutAndCloseWindow").with(config);
}
}
#Inject Request request;
#OnEvent(value = EVENT)
void logout() {
Session session = request.getSession(false);
if (session != null) session.invalidate();
}
}
YourPage.tml
<!DOCTYPE html>
<html
xmlns:t="http://tapestry.apache.org/schema/tapestry_5_4.xsd"
xmlns:p="tapestry:parameter">
<h1>Hit the Road Jack</h1>
</html>
LogoutAndCloseWindow.js
define(["jquery"], function($) {
return function(config) {
alert(config.msg);
$.ajax({
type: "GET",
url: config.link
});
window.close(); // Legacy. Doesn't work in current browsers.
// See https://stackoverflow.com/questions/2076299/how-to-close-current-tab-in-a-browser-window
}
})

Related

Don't know how to redirect to url from mail after login in Wicket

so I have this application. It has newly got sso via kerberos but is also running ldap as a fallback option. There is a routingpage that directs people to the homepage if authenticated by kerberos or leads them to the loginpage if not. Now I was made aware of the fact, that a lot of people actually go first to the application via a link they receive via mail where they need to approve something and they are annoyed that they get directed to the homepage after clicking the link because that is how it's implemented that after authentification they will go to the homepage.
So now I found a way to get redirect them straight to the approvalpage from the e-mail via kerberos but I can't seem to make it work via kerberos. I keep getting directed to the homepage.
So this is my attempt:
RoutingPage:
public class RouterPage extends BasePage {
public SSORouterPage () {
super();
AppSession session = (AppSession) SecureWebSession.get();
String approvalLink = getRequest().getRequestParameters().getParameterValue("approval_link").toString();
if (approvalLink != null) {
session.setApprovalLink(approvalLink);
}
if (!session.singleSignOn()) {
log.warn("User not logged in, redirecting to login page");
if (session.hasApprovalLink()) {
approvalLink = session.getApprovalLink();
session.setApprovalLink(null);
setResponsePage(LoginPage.class, getApprovalPageParameters(approvalLink));
} else {
setResponsePage(LoginPage.class);
}
} else {
String name = Optional
.ofNullable(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication).map(
Authentication::getName).orElse("undefined");
log.info("Sucessfull sign in for {}", name);
if (session.hasApprovalLink()) {
approvalLink = session.getApprovalLink();
session.setApprovalLink(null);
setResponsePage(new ApprovalPage(getApprovalPageParameters(approvalLink)));
} else {
setResponsePage(HomePage.class);
}
}
}
LoginPage
public class LoginPage extends BasePage {
private static final long serialVersionUID = 4297836260248255954L;
public static final String LOGIN_PANEL_ID = "panel";
public LoginPage() {
super();
if (AuthenticatedWebSession.class.isAssignableFrom(getSession().getClass()) && ((AuthenticatedWebSession) getSession()).isSignedIn()) {
continueToOriginalDestination();
}
}
public LoginPage(final PageParameters pageParameters){
super(pageParameters);
if (AuthenticatedWebSession.class.isAssignableFrom(getSession().getClass()) && ((AuthenticatedWebSession) getSession()).isSignedIn()) {
setResponsePage(new ApprovalPage(pageParameters));
}
}
The constructor with the PageParameters is clearly called because I can see them in the url, why do I get directed to the homepage? Any ideas?
I would recommend you to use Component#continueToOriginalDestination(). See its javadoc. Its purpose is to continue to the originally requested page after an interception like "you need to login first". You need to use #redirectToInterceptPage(LoginPage.class) with it.

How to open new page after a successful login GWT Java

I'm making a GWT application that requires users to log in. If username and password are correct, then they are allowed to use the application.
What needs to be implemented in the onSuccess() method to make this possible ?
Thanks in advance.
DBConnectionAsync rpcService = (DBConnectionAsync) GWT.create(DBConnection.class);
ServiceDefTarget target = (ServiceDefTarget) rpcService;
String moduleRelativeURL = GWT.getModuleBaseURL() + "DBConnectionImpl";
target.setServiceEntryPoint(moduleRelativeURL);
rpcService.authenticateUser("admin", "admin", new AsyncCallback<User>() {
#Override
public void onSuccess(User result) {
// What to do here to open or redirect the user to a new page ?
}
#Override
public void onFailure(Throwable caught) {
// Failure
}
});
A simple way of doing this would be to fire an event to the eventbus of you application and then catch this event in the main controller of your application, which would trigger the opening of the right page.
This two pages should explain everything you possibly need to know to do this:
Everything about the architecture GWT MVP
Everything about activity and places (navigation and history)
Just as if you need more information.
From onSuccess you can call a method which will be defined in a corresponding presenter and from that method you can fire an event which will allow user to enter into your application only on successful authentication .

How to change between pages with Selenium

I am trying to create a Test Case with Selenium, where I will create an application in one Page named "Policy". In this Application I want to create some Members. To go from Policy page to Members Page you have to press the button "Members" after you've successfully created the Policy Application. After creating all the members you need you have to navigate back to Policy page to continue.
(Main Menu Page -> Policy Page -> Members Page -> Policy Page)
I am using Page Object Pattern. I successfully log in the App, navigate to Policy Page, create the Application, but cannot go to Members Page in order to continue my Test. And of course, get back to Policy page. How can I do that? My test fails after message "Policy Created succesfully" is shown in Eclipse Console.
My code is:
#Test
public void TEST1_NavigateToPolicy() throws Exception {
MenuPage.policySelection();
}
#Test
public void TEST2_PolicyCreation() throws Exception {
PolicyPage.handleMultipleWindows("Policy");
PolicyPage.createPolicy( some requirements here);
PolicyPage.checkMessageByIdContains("Operation Apply executed Successfully", MESSAGE);
System.out.println("Policy Created succesfully");
}
#Test
public void TEST3_MemberCreation() {
//Navigate to Member Page and Create Member
PolicyPage.clickButton(MEMBERS_BUTTON);
}
Unless I'm testing the actual navigation via the UI I like to do as much navigating as possible by browsing directly to the page I need. It gives the test fewer opportunities to fail, and is often quicker as it can save extra steps.
So, I'd browse directly to the page simply using:
driver.get("yourURL");
Navigation between Policy and Members page can be done by:
#Test
public void TEST3_MemberCreation() {
// Create a policy
TEST2_PolicyCreation();
// Store the current window handle
String policyPageWindow = _webDriver.getWindowHandle();
// Clicking the "Members" button on Policy page
WebElement clickMemBerPageButton = _webDriver.findElement(By.name("MEMBERS_BUTTON"));
clickMemBerPageButton.click();
// switch focus of WebDriver to the next found window handle (that's your newly opened "Members" window)
for (String winHandle : _webDriver.getWindowHandles()) {
_webDriver.switchTo().window(winHandle);
}
//code to do something on new window (Members page)
// Switch back to policy page
_webDriver.switchTo().window(policyPageWindow);
}
Then this will be my sample code for you.
#Test
public void TEST3_MemberCreation() {
homePage = login(admin);
PolicyPage policyPage = homePage.NavigateToPolicyPage();
policyPage.handleMultipleWindows("Policy");
policyPage.createPolicy( some requirements here);
policyPage.checkMessageByIdContains("Operation Apply executed Successfully", MESSAGE);
System.out.println("Policy Created succesfully");
}
MembersPage membersPage = policyPage.clickMembersButton;(You have to handle the page navigation code inside this method and return MembersPage object)
membersPage.createMember(Data);
}
MembersPage clickMembersButton(){
element.click();
switchTo.window(newWindowHandle);
return new MembersPage();
}

Wicket : throw new RestartResponseException to logout and redirect

I have a problem to redirect a page after invalidating session using Wicket.
Careers1 is a page, that needs user to be logged in, with six buttons linked to other pages and an a href button, which get the user logged out.
My code apparently works, because if I click to log out, and I click to one of the six buttons, it redirects me to the log in page.
But I need it to redirect me immediately, after I clicked "log out".
I tried setResponsePage() and also adding signOut() the problem is the same of the RestartResponseException.
Here is my code
Careers1:
public class Careers1 extends WebPage
{
public Careers1()
{
Link logoutLink = new Link("logout")
{
#Override
public void onClick()
{
getSession().invalidate();
throw new RestartResponseException(Careers1.class);
}
};
add(logoutLink);
}
}
On careers.html I have
<div class="logout" > <a wicket:id="logout" href="#"> LOG OUT </a></div>
Which should invalidate the session, and redirect the user to the login.
You can try forcing wicket to redirect immediately using a fake page that just redirects back to Careers1. Let's name it RedirectorPage:
public class RedirectorPage extends WebPage
{
#Override
protected void onBeforeRender()
{
throw new RestartResponseException(Careers1.class);
}
}
Now in the logout link of Careers1 you redirect to RedirectorPage. That worked for me, but only after I moved the exception of RedirectorPage into onBeforeRender(). Throwing the exception in the page constructor still makes wicket ignore the fact the session has already been invalidated.

Wicket 6 !continueToOriginalDestination: operator ! is undefined

Situation
I'm migrating a project from Wicket 1.5.7 to Wicket 6.12, one of the errors I get is explained below.
Code
#Override
protected void onSubmit() {
final String usernameValue = mail.getModelObject();
//Password is left empty in this particular case
AuthenticatedWebSession.get().signIn(usernameValue,"");
if (!continueToOriginalDestination())
{
setResponsePage(getApplication().getHomePage());
}
}
Error
This is the error I got when changing wicket versions: The operator !
is undefined for the argument type(s) void
Note: I see this error when hovering over !continueToOriginalDestination
What did I try
In my search on stackoverflow I came accross this question:
continueToOriginalDestination does not bring me back to originating page
Also checked this topic on apache wicket:
http://apache-wicket.1842946.n4.nabble.com/Handling-ReplaceHandlerException-on-continueToOriginalDestination-in-wicket-1-5-td4101981.html#a4115437
So I changed my code to this:
#Override
public void onSubmit() {
final String usernameValue = mail.getModelObject();
AuthenticatedWebSession.get().signIn(usernameValue,"");
setResponsePage(getApplication().getHomePage());
throw new RestartResponseAtInterceptPageException(SignInPage.class);
}
Question
The old situation nor the code change seem to work in my particular case.
Maybe it's a small change, is my new code wrong, how should this work?
Has Wicket changed that much, so that the old code is not supported anymore, or can !continueToOriginalDestination be used as well?
This helps
http://www.skybert.net/java/wicket/changes-in-wicket-after-1.5/
In 1.5, you could do the following to break out of the rendering of one page, go to another page (like login page) and then send the user back to where he/she was:
public class BuyProductPage extends WebPage {
public BuyProductPage() {
User user = session.getLoggedInUser();
if (user null) {
throw new RestartResponseAtInterceptPageException(LoginPage.class);
}
}
}
and then in LoginPage.java have this to redirect the user back to BuyProductPage after he/she's logged in:
public class LoginPage extends WebPage {
public LoginPage() {
// first, login the user, then check were to send him/her:
if (!continueToOriginalDestination()) {
// redirect the user to the default page.
setResponsePage(HomePage.class);
}
}
}
The method continueToOriginalDestination has changed in Wicket 6, it's now void which makes your code look more magic and less than logic IMO:
public class LoginPage extends WebPage {
public LoginPage() {
// first, login the user, then check were to send him/her:
continueToOriginalDestination();
// Magic! If we get this far, it means that we should redirect the
// to the default page.
setResponsePage(HomePage.class);
}
}

Categories

Resources