Showing specific error in JSP with Ajax - java

I'm trying to show in my App different errors when a user is already logged in and when the user wrote their username/password wrong. I have tried many ways but none of them is working. I don't know what else to try or if it's even possible. I don't know if I'm close to the solution either.
What I'm trying to do is:
Set the errorMessage in the request;
Set the SC_INTERNAL_SERVER_ERROR in the response so the AJAX function enters in ** and the HTML in the paramether is the one in the JSP with the specific Message.
Action
public class LogUser extends Action {
#Override
public void execute() throws Exception {
...
String pageToGo = this.tryLogUser(username, password);
request.getRequestDispatcher(pageToGo).forward(request, response);
}
private String tryLogUser(String username, String password) throws Exception {
String pageToGo = "page/userHome";
...
if(canLog) {
...
try {
...
Server.getInstance().logIn(user); // Throws an Exception if the User is already logged in.
...
} catch (ServerException e) {
this.setErrorMessage("That user is already logged in.");
pageToGo = "page/error.jsp";
}
} else {
this.setErrorMessage("User and/or Password are incorrect.");
pageToGo = "page/error.jsp";
}
return pageToGo;
}
private void setErrorMessage(String message) {
request.setAttribute("errorMessage", message);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
JSP
<div class="alert alert-danger"> ${ requestScope.errorMessage } </div>
AJAX
function showUserHome() {
$.post( "${ sessionScope.ServletUrl }", $( "form#logForm" ).serialize() )
.done(function( html ) {
$( "div#toolbar" ).load("page/userToolbar.jsp");
$( "div#content" ).html( html );
})
.fail(function( html ) {
$( "#result" ).html( html );
});
}
Edit:
While trying to Debug it from the browser, it gets in the $.post and after that step, it jumps to the end of the function, skipping .done and .fail and the page remains the same. I'm not getting any error in the RAD Console or the Browser Console other than the SC_INTERNAL_SERVER_ERROR that I setted on the Action.

Calling setErrorPage method won't change your pageToGo local variable and thus always the same view is used. Change it to something like:
pageToGo = setErrorPage("That user is already logged in.");
(or even consider rename it to getErrorPage)

Related

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

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
}
})

Android paytm payment gateway response

I have implemented Paytm payment system and everything is working fine with a web intent on top of my intent, money is deducted from customer's acc and its getting added on my account but after the transaction gets complete it gets stuck on a white page saying 'Redirect to app' which i believe i should write the code to redirect back to my app but i don't know how to do that because i couldn't find a onTransactionSucess() event or anything similar to that i also tried onTransactionResponse but still no response. I checked all the paytm documentation and tried contacting paytm support but couldn't find a way.
Hope you have added 'CALLBACK_URL' which is requied to verify the checksum.
As mentioned in paytm documentation
CALLBACK_URL - Security parameter to avoid tampering. Generated using
server side checksum utility provided by Paytm. Merchant has to ensure
that this always gets generated on server. Utilities to generate
checksumhash is available here .
Hope this should do the magic.
I hope you have added this variable to your code -
PaytmPGService service;
If you are using it than you can get all the payment related methods like this :
service.startPaymentTransaction(this, true,
true, new PaytmPaymentTransactionCallback() {
#Override
public void onTransactionResponse(Bundle inResponse) {
System.out.println("===== onTransactionResponse " + inResponse.toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.equals(inResponse.getString("STATUS"), "TXN_SUCCESS")) {
// Payment Success
} else if (!inResponse.getBoolean("STATUS")) {
// Payment Failed
}
}
}
#Override
public void networkNotAvailable() {
// network error
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
// AuthenticationFailed
}
#Override
public void someUIErrorOccurred(String inErrorMessage) {
// UI Error
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {
// Web page loading error
}
#Override
public void onBackPressedCancelTransaction() {
// on cancelling transaction
}
#Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
// maybe same as onBackPressedCancelTransaction()
}
});
I hope this will help you.
Change default callbackurl to suppose, 'http://yourdomain (ip address if checking on localhost)/pgResponse.php';.
Add following code to pgResponse.php
<?php
session_start();
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";
$paramList = $_POST;
$return_array= $_POST;
$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);//generate new checksum
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your applicationís MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
$return_array["IS_CHECKSUM_VALID"] = $isValidChecksum ? "Y" : "N";
unset($return_array["CHECKSUMHASH"]);
$mid = $_POST['MID'];
$orderid = $_POST['ORDERID'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://securegw-stage.paytm.in/order/status?JsonData={"MID":"'.$mid.'","ORDERID":"'.$orderid.'","CHECKSUMHASH":"'.$checkSum.'"}',
CURLOPT_USERAGENT => 'Make Request'
));
$resp = curl_exec($curl);
$status= json_decode($resp)->STATUS;
//do something in your database
$encoded_json = htmlentities(json_encode($return_array));
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-I">
<title>Paytm</title>
<script type="text/javascript">
function response(){
return document.getElementById('response').value;
}
</script>
</head>
<body>
Redirecting back to the app.....</br>
<form name="frm" method="post">
<input type="hidden" id="response" name="responseField" value='<?php echo $encoded_json?>'>
</form>
</body>
</html>
In android studio:
public void onTransactionResponse(Bundle inResponse) {
Log.d("Create Response", inResponse.toString());
String response = inResponse.getString("RESPMSG");
if (response.equals("Txn Successful.")) {
Toast.makeText(Bag.this,"Payment done",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Bag.this,response,Toast.LENGTH_LONG).show();
}
}

Ajax call working on Google Chrome but not on IE 11

I am developing a RESTFul web service project which has a POJO as below:
#XmlRootElement
public class Input {
//variable declarations
public Input(){
//default constructor
}
//constructor no 1
public Input(String LR, double ECH,double CSH,String APP) {
this.LR = LR;
this.ECH = ECH;
this.CSH = CSH;
this.APP = APP;
}
//constructor no 2
public Input(String LR, double ECH,double CSH,String APP,...) {
this.LR = LR;
this.ECH = ECH;
this.CSH = CSH;
this.APP = APP;
//constructor of all other parameters including these
}
//getters and setters method below.
}
My ajax is getting called on this button:
<button type="submit" onClick='functionname();' class="btn btn-primary" ><span class="glyphicon glyphicon-lock"></span>Function</button>
The Controller class I have is as follows:
#Path("/input")
public class InputResponse {
InputService inputservice = new InputService();
#PUT
#Path("/approve")
#Produces(MediaType.APPLICATION_JSON)
public void approveInputRecord(Input obj) throws Exception{
String LR = obj.getLR();
double CSH = obj.getCSH();
double ECH = obj.getECH();
String APP = obj.getAPP();
Input input = new Input(LR,CSH,ECH,APP);
input = inputservice.approveTransaction(input);
}
}
The Service Class for the same is as below:
public class InputService {
CallableStatement stmt;
Statement commitStmt;
public InputService(){
//database connection
}
public Input approveTransaction(Input input) throws SQLException {
commitStmt = dcc.con.createStatement();
stmt=dcc.con.prepareCall("BEGIN APPROVRTRANSACTION(?,?,?,?); END;");
stmt.setString(1, input.getLR());
stmt.setDouble(2, input.getECH());
stmt.setDouble(3, input.getCSH());
stmt.setString(4, input.getAPP());
stmt.execute();
commitStmt.executeQuery("COMMIT");
return input;
}
}
Inside my JAVA Script my ajax call to above is:
var obj = {
LogReference : logreference,
EuroclearHoldings:euroclearholdings,
ClearstreamHoldings:clearstreamholdings,
Approver : loginXPID
}
var jsonobj = JSON.stringify(obj);
$.ajax({
url:'./webapi/input/approve',
type: 'PUT',
data:jsonobj,
cache:false,
contentType: 'application/json',
dataType:'json',
success:function(data)
{
alert('success');
},
error:function(xhr,textstatus,errorthrown){
alert(xhr.responseText);
alert(textstatus);
alert(errorthrown);
}
},'json');
Having this as my code my application is working fine on Google Chrome but sometimes works and sometimes not on Internet Explorer 11. This is the strange behavior. And the other thing which I am unable to get is even if it works on Chrome the ajax call always getting the alerts in error. Can anybody please explain why is it so? And how do I solve it? Any help much appreciated.
Update
Here is the output on network --> Response tab on chrome when error is thrown. But despite that I still get the output.
Many Thanks
As I can see your Button type="submit". If it is inside the form tag then call the ajax request in action of the file. As I can see from above comments this might be the issue. As you are submitting something this changes to a POST request and not GET request so its giving the error method not allowed. And looking at the solution just change the Button type='button' or call the ajax on the action of form tag. It should work.

Understanding Server-sent Events

I'm trying to update an HTML5 table in real-time with some data from the database. Here is my code:
HTML page:
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("[some address]/api/sse");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("placeholder").innerHTML=table;
};
}
else {
[erro message]
}
</script>
And my Java Restful service:
#Path("/sse")
public class SSEResource {
#Context
private UriInfo context;
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() throws Exception {
SomeObject o = new SomeObject();
final String myString = o.someQuery().getEntity().toString();
return "data: " + myString + "\n\n";
}
}
This someQuery() method queries from database and returns what I want to put on my table. Everythings looks great. But I want to know if it's right or wrong, because if I put some log on someQuery() method, I see that every 3 seconds the query is executed. This may cause heavy duty, right? Is this normal or is my code wrong?

Parse (Java for Android) login returns Object Not Found

I'm trying to login using Parse for android.
If I enter the correct username and password, I log in successfully.
But when I use a wrong password or username, I always get error 101: object not found.
Here's the code (Notice "username" and "password" are EditText):
private void doLogin() {
if (!validate()) { // IF VALIDATION FAILS, DO NOTHING
return;
} // ELSE...
String name = email.getText().toString();
String pass = password.getText().toString();
ParseUser.logInInBackground(name, pass, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
goToMainActivity(user.getUsername());
} else {
handleParseError(e);
}
}
});
}
Thanks for your help.
Update: Parse does not have means to check if there was an incorrect login field. Hence they use the general 101: Object Not Found error to catch it. Reference: https://parse.com/docs/android/api/com/parse/ParseException.html
Previous stackoverflow link: Parse : invalid username, password
If you want your app to respond to an incorrect login, just replace the line handleParseError(e); with code to handle it.
For example, if you want a message box to show up, place that code there. If you do not want to do anything, comment out that line. Not sure what else you are looking for...
I would suggest replacing it with a Toast message

Categories

Resources