Google Web Toolkit - XSRF Protected Services : Invalid RPC Token - gwt

I've implemented XSRF Protected Services in GWT project. I'm using GWT 2.6.0 release. When I try to load my app in a browser I get a very strange exception as follows:
Uncaught com.google.gwt.user.client.rpc.RpcTokenException: Invalid RPC token (Invalid RpcToken type: expected 'com.google.gwt.user.client.rpc.XsrfToken' but got 'class com.google.gwt.user.client.rpc.XsrfToken')
I've searched my classpath and I only have one XsrfToken class provided by gwt-servlet.jar located inside my WAR file. I downloaded 2.6 code from GIT and I see the code that is throwing the exception is provided by ProxyCreator.java in the method generateCheckRpcTokenTypeOverride.
Does anyone have any idea as to why this exception would be thrown. The error indicates to me at least that it should pass given that what is expected is what it has.
I'm pasting the method in for completeness:
protected void generateCheckRpcTokenTypeOverride(SourceWriter srcWriter, TypeOracle typeOracle,
SerializableTypeOracle typesSentFromBrowser) {
JClassType rpcTokenType = typeOracle.findType(RpcToken.class.getName());
JClassType[] rpcTokenSubtypes = rpcTokenType.getSubtypes();
String rpcTokenImplementation = "";
for (JClassType rpcTokenSubtype : rpcTokenSubtypes) {
if (typesSentFromBrowser.isSerializable(rpcTokenSubtype)) {
if (rpcTokenImplementation.length() > 0) {
// >1 implematation of RpcToken, bail
rpcTokenImplementation = "";
break;
} else {
rpcTokenImplementation = rpcTokenSubtype.getQualifiedSourceName();
}
}
}
if (rpcTokenImplementation.length() > 0) {
srcWriter.println("#Override");
srcWriter.println("protected void checkRpcTokenType(RpcToken token) {");
srcWriter.indent();
srcWriter.println("if (!(token instanceof " + rpcTokenImplementation + ")) {");
srcWriter.indent();
srcWriter.println("throw new RpcTokenException(\"Invalid RpcToken type: " + "expected '"
+ rpcTokenImplementation + "' but got '\" + " + "token.getClass() + \"'\");");
srcWriter.outdent();
srcWriter.println("}");
srcWriter.outdent();
srcWriter.println("}");
}
}
Thanks very much in advance.

Related

Rest Assured cannot be resolved to a variable

I have created a java project and am getting the error in my console
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
RestAssured cannot be resolved to a variable
added jar- rest-assured-4.3.3-dist.zip- all extracted
from official website- https://github.com/rest-assured/rest-assured/wiki/Downloads
here is my code-
//java class basics
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
public class Basics {
public static void main(String[] args) {
//adding given, when , then conditions
RestAssured.baseURI = "https://rahulshettyacademy.com"; //added the base URI here
//adding given condition here with log report
given().log().all().queryParam("key", "qaclick123").header("Content-Type", "application/json")
.body("{\r\n" +
" \"location\": {\r\n" +
" \"lat\": -38.383494,\r\n" +
" \"lng\": 33.427362\r\n" +
" },\r\n" +
" \"accuracy\": 50,\r\n" +
" \"name\": \" Muzammil house\",\r\n" +
" \"phone_number\": \"(+91) 983 893 3937\",\r\n" +
" \"address\": \"29, side layout, cohen 09\",\r\n" +
" \"types\": [\r\n" +
" \"shoe park\",\r\n" +
" \"shop\"\r\n" +
" ],\r\n" +
" \"website\": \"http://google.com\",\r\n" +
" \"language\": \"French-IN\"\r\n" +`enter code here`
"}") // end of body
.when().post("maps/api/place/add/json") // added the resource here
.then().log().all().assertThat().statusCode(200); // validating response here
}
}
How do I resolve this?
I assume that you are using maven. If that is the case you need to remove
<scope> test </scope>
node form your rest assured dependency in pom.xml file. If you are not using maven, then try to set build path and make sure that you added all your .jar files into the project.

C# Download File from HTTP File Directory getting 401 error or 403 error

I’m trying to download several files from a local network device:
http file directory
I want to write a code that will automatically download all those .avi files to my pc drive.
I have 2 problems:
Problem 1: AUTHENTICATING using WebClient class only.
If I use WebClient class only to connect, I get a 401 Unauthorized error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = new NetworkCredential("user", "pword");
String userName = "user";
String passWord = "pword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
myWebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
Console.WriteLine("Header AUTHORIZATION: "+ myWebClient.Headers[HttpRequestHeader.Authorization].ToString());
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: Failure to authenticate
401 Unauthorized Error
Problem 2: Was able to authenticate using WebProxy class but can’t download . Getting 403 Not found error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
WebProxy wp = new WebProxy("http://192.168.2.72:81/sd/20170121/record000/",false);
wp.Credentials = new NetworkCredential("user","pword");
Console.WriteLine("Web Proxy: " + wp.Address);
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = wp.Credentials;
myWebClient.Proxy = wp;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\"\n\n", filename, wp.Address);
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: 403 Not Found
DOWNLOAD ERROR: System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at ConsoleApplication2.Program.Main(String[] args) in C:\Users\Gordon\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 139
Please help me identify if there are any mistakes in my code or is there a better way to submit credentials and download all the files.
Thanks in advance!
I'm not Dot Net developer, I'm just sharing my opinion.
In the second point you have mentioned that you are getting 403 which is the Http status code for Acces Denied. I feel your credentials are not valid or you don't have privilege to do the operation.

Paypal-IPN Simulator ends up in HTTP 404 error after successfully completion of the function

have spent lot of hours trying to figure this out with Paypal Simulator, Sandbox but the result is same. My handler function(handleIpn) gets called and processed, with "Verified" "Complete" status but the IPN history as well as the simulator ends up in the HTTP 404 error. On IPN Simulator page the error is - "We're sorry, but there's an HTTP error. Please try again." My set up is Java-Spring MVC.
#RequestMapping(value = "/ipnHandler.html")
public void handleIpn (HttpServletRequest request) throws IpnException {
logger.info("inside ipn");
IpnInfo ipnInfo = new IpnInfo();
Enumeration reqParamNames = request.getParameterNames();
StringBuilder cmd1 = new StringBuilder();
String pName;
String pValue;
cmd1.append("cmd=_notify-validate");
while (reqParamNames.hasMoreElements()) {
pName = (String) reqParamNames.nextElement();
pValue = request.getParameter(pName);
try{
cmd1.append("&").append(pName).append("=").append(pValue);
}
catch(Exception e){
e.printStackTrace();
}
}
try
{
URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
HttpsURLConnection con = (HttpsURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Host", "www.sandbox.paypal.com/cgi-bin/webscr");
con.setRequestProperty("Content-length", String.valueOf(cmd1.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(cmd1.toString());
output.flush();
output.close();
//4. Read response from Paypal
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String res = in.readLine();
in.close();
//5. Capture Paypal IPN information
ipnInfo.setLogTime(System.currentTimeMillis());
ipnInfo.setItemName(request.getParameter("item_name"));
ipnInfo.setItemNumber(request.getParameter("item_number"));
ipnInfo.setPaymentStatus(request.getParameter("payment_status"));
ipnInfo.setPaymentAmount(request.getParameter("mc_gross"));
ipnInfo.setPaymentCurrency(request.getParameter("mc_currency"));
ipnInfo.setTxnId(request.getParameter("txn_id"));
ipnInfo.setReceiverEmail(request.getParameter("receiver_email"));
ipnInfo.setPayerEmail(request.getParameter("payer_email"));
ipnInfo.setResponse(res);
// ipnInfo.setRequestParams(reqParamNames);
//6. Validate captured Paypal IPN Information
if (res.equals("VERIFIED")) {
//6.1. Check that paymentStatus=Completed
if(ipnInfo.getPaymentStatus() == null || !ipnInfo.getPaymentStatus().equalsIgnoreCase("COMPLETED"))
ipnInfo.setError("payment_status IS NOT COMPLETED {" + ipnInfo.getPaymentStatus() + "}");
//6.2. Check that txnId has not been previously processed
IpnInfo oldIpnInfo = this.getIpnInfoService().getIpnInfo(ipnInfo.getTxnId());
if(oldIpnInfo != null)
ipnInfo.setError("txn_id is already processed {old ipn_info " + oldIpnInfo);
//6.3. Check that receiverEmail matches with configured {#link IpnConfig#receiverEmail}
if(!ipnInfo.getReceiverEmail().equalsIgnoreCase(this.getIpnConfig().getReceiverEmail()))
ipnInfo.setError("receiver_email " + ipnInfo.getReceiverEmail()
+ " does not match with configured ipn email " + this.getIpnConfig().getReceiverEmail());
//6.4. Check that paymentAmount matches with configured {#link IpnConfig#paymentAmount}
if(Double.parseDouble(ipnInfo.getPaymentAmount()) != Double.parseDouble(this.getIpnConfig().getPaymentAmount()))
ipnInfo.setError("payment amount mc_gross " + ipnInfo.getPaymentAmount()
+ " does not match with configured ipn amount " + this.getIpnConfig().getPaymentAmount());
//6.5. Check that paymentCurrency matches with configured {#link IpnConfig#paymentCurrency}
if(!ipnInfo.getPaymentCurrency().equalsIgnoreCase(this.getIpnConfig().getPaymentCurrency()))
ipnInfo.setError("payment currency mc_currency " + ipnInfo.getPaymentCurrency()
+ " does not match with configured ipn currency " + this.getIpnConfig().getPaymentCurrency());
}
else
ipnInfo.setError("Inavlid response {" + res + "} expecting {VERIFIED}");
logger.info("ipnInfo = " + ipnInfo);
this.getIpnInfoService().log(ipnInfo);
//7. In case of any failed validation checks, throw {#link IpnException}
if(ipnInfo.getError() != null)
throw new IpnException(ipnInfo.getError());
}
catch(Exception e)
{
if(e instanceof IpnException)
throw (IpnException) e;
logger.log(Level.FATAL, e.toString(), e);
throw new IpnException(e.toString());
}
//8. If all is well, return {#link IpnInfo} to the caller for further business logic execution
paymentController.processSuccessfulPayment(ipnInfo);
}
Any help /pointers would greatly appreciate.
thanks.
Finally, got it working! Didn't realize that my issue of redirection in Spring MVC could have impact on Paypal - IPN status. May be my lack of good understanding of HTTP redirections! In above method instead of void return am now returning a jsp page, so "void" is changed to "String" with returning value the jsp file name.
Hope it does help someone!

How to create a SalesForce 'User' with SOAP Partner API?

I want to create a User in SalesForce programmatically by using SOAP API Partner WSDL. This is my code:
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.SaveResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.soap.partner.sobject.*;
import com.sforce.soap.partner.*;
import com.sforce.soap.*;
import com.sforce.*;
public class PartnerAPICreateUser {
/**
* #param args
*/
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername("waprau#waprau.com");
config.setPassword("dhskjhkjgfkjsdhkfjg");
PartnerConnection connection = null;
try {
SObject user = new SObject();
user.setType("user");
user.setField("Alias", "abcd");
user.setField("DefaultGroupNotificationFrequency", "P");
user.setField("DigestFrequency", "D");
user.setField("Email", "abcd#pqrs.com");
user.setField("EmailEncodingKey", "ISO-8859-1");
user.setField("LanguageLocaleKey", "English");
user.setField("LastName", "Rau");
user.setField("LocaleSidKey", "En");
user.setField("TimeZoneSidKey", "America/Los_Angeles");
user.setField("Username", "abcd#pqrs.com");
user.setField("UserPermissionsCallCenterAutoLogin", "true");
user.setField("UserPermissionsMarketingUser", "true");
user.setField("UserPermissionsOfflineUser", "true");
connection = Connector.newConnection(config);
SaveResult[] results = connection.create(new SObject[] { user });
System.out.println("Created user: " + results[0].getId());
QueryResult queryResults = connection
.query("SELECT Id, Name from User "
+ "ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
System.out.println("Id: " + s.getField("Id") + " - Name: "
+ s.getField("Name"));
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}
However, when I execute this Java program it gives following output which shows 'Created user: null' :-(
Created user: null
Id: 005E0000001fb3vIAA - Name: Rau
Id: 005E0000001fVTTIA2 - Name: Chatter Expert
Id: 005E0000001fVU1IAM - Name: Wap Rau
Administrative Permissions when I go to MyName > Setup > Manage Users (in Administration Setup) > Profiles
Can you tell me whats wrong?
Thanks,
Wap Rau
The create call is returning an error, but you don't check for it, the returned SaveResult will tell you why it didn't create the user, you want something like
SaveResult[] results = connection.create(new SObject[] { user });
if (results[0].isSuccess())
System.out.println("Created user: " + results[0].getId());
else
System.out.println("Error: " + results[0].getErrors()[0].getStatusCode() +
":" + results[0].getErrors()[0].getMessage());

How To Use I18N Messages In A Grails Plugin

I've added a new exception to my plugin:
class UnzipException extends RuntimeException {
String message
String defaultMessage
String fileName
}
. . .
else {
throw new UnzipException(
message:"grailsant.unzipexception.badfile",
defaultMessage: "Invalid zip file: ${zipFile}",
fileName: zipFile)
}
...
And in the plugin's messages.properties I have:
grailsant.unzipexception.badfile=Invalid zip file: {0}
Two questions:
How do I get {0} filled in with fileName?
Can an application override the grailsant.unzipexception.badfile message?
(1) It seems like this has to be done by app:
try {
. . .
} catch (org.grails.plugins.grailsant.UnzipException e) {
flash.message = e.message
flash.args = [e.fileName]
flash.defaultMessage = e.defaultMessage
}
(2) Yep, if the message.properties in the app has the same key as the plugin, the app's values will be used.