Understanding Server-sent Events - java

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?

Related

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

How can I create a new user in Parse, without changing the current user?

I am currently making a friend request module. The user clicks "Approve" the program adds the friend to the _User class on Parse Server. I believed the code below would do it, and it does, but the problem is that is changes the current user to the new friend that has been added. So if the current user is "Bob", and Bob adds "Mike" the new current user is Mike.
I've been experimenting with signUp(), signUpInBackground(), but neither seem to work.
ParseUser newFriend = new ParseUser();
newFriend.setUsername(friendRequestFrom); //friendRequestFrom is a String that carries a name
newFriend.setPassword("12345");
newFriend.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e == null){
Log.i("Parse Result","Succesful!");
Log.i("Current User",ParseUser.getCurrentUser().getUsername());
}
else{
Log.i("Parse Result","Failed " + e.toString());
}
}
});
In order to create a new Parse user in Parse using client side code, you have to use a cloud code function hosted in your app backend.
In fact, for security reasons, client librararies are not permitted to directly add users.
In your server side, create a file (main.js) containing the following code:
Parse.Cloud.define("createNewUser", function(request, response) {
var User = Parse.Object.extend("User");
var us = new User();
us.set("username", request.params.username);
us.set("name", request.params.name);
us.set("email", request.params.email);
us.set("password", request.params.password);
us.save(null, {
useMasterKey: true,
success: function(obj) {
response.success("user added");
},
error:function(err){
response.error(err);
}
});
});
Then, you can test this function in your javascript client code as following:
var params = { username: "userEmailAddress#yahoo.fr",
email: "userEmailAddress#yahoo.fr",
name:"Here write the user name",
password:"TheUserPasswordHere"};
Parse.Cloud.run("createNewUser", params).then(function(response){console.log("response: "+response);}).catch(function (err) {
console.log("error: "+err);
});

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.

Showing specific error in JSP with Ajax

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)

passing parameters from javascript to gwt?

I am new to Gwt,i m implementing a webclipper project so my task to send some parameters from javascript file to Gwt so that i will be able to make the connection with my couchdb database but i am getting a problem in passing parameters like title, url ,and summary from webpage to Gwt n then couchdb.The following code is my javascript code:-
function onPageInfo(o) {
document.getElementById('title').value = o.title;
document.getElementById('url').value = o.url;
document.getElementById('summary').innerText = o.summary;
}
// Global reference to the status display SPAN
var statusDisplay = null;
// POST the data to the server using XMLHttpRequest
function addBookmark() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = "http://127.0.0.1:8888/practice.html? gwt.codesvr=127.0.0.1:9997&gwt.codesvr=127.0.0.1:9997/?title=1&url=2&summary=3";
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
var summary = encodeURIComponent(document.getElementById('summary').value);
var tags = encodeURIComponent(document.getElementById('tags').value);
var params = 'title=' + title +
'&url=' + url +
'&summary=' + summary +
'&tags=' + tags;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/json');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
window.setTimeout(window.close, 1000);
} else {// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
}
// When the popup HTML has loaded
window.addEventListener('load', function(evt) {
// Handle the bookmark form submit event with our addBookmark function
document.getElementById('addbookmark').addEventListener('submit', addBookmark);
// Cache a reference to the status display SPAN
statusDisplay = document.getElementById('status-display');
// Call the getPageInfo function in the background page, injecting content_script.js
// into the current HTML page and passing in our onPageInfo function as the callback
chrome.extension.getBackgroundPage().getPageInfo(onPageInfo);
});
Thanks.....
You can call a function defined in a java file (of GWT client module) by exporting that function. Let's assume there is a class A.java which is also your entry point class. This class contains someMethod() which you need to call from javascript passing some parameters. The content of your class A would be something like
public class A implements EntryPoint {
public static functionExported = false;
public void onModuleLoad() {
ExportToBeCalledFromJs();
// other code goes here
}
public static native void ExportToBeCalledFromJs() /*-{
$wnd.toBeCalledFromJs = $entry(function(s1, s2) {
return #com.practice.gwt.client.A::someFunction();
});
#com.practice.gwt.client.A:functionExported = true;
}-*/;
}
Above code exports the function and makes it available to javascript. You can simply call toBeCalledFromJs(param1, param2) fromyour js where param1 would substitute s1 and param2 would substitute s2. If you wish to add more parameters you can modify $entry(function(s1, s2) in the code above.

Categories

Resources