XMPP asmack: Contact presence not working for transitions to "available" - xmpp

I am using asmack 8-0.8.3.
I don't receive messages for changes of Presence from my contacts when they move to "available".
If one contact passes from "available" to "dnd", I do receive a message. But not in the other way around.
Contact passes: "available" --> "dnd" --> "available" --> "dnd"
I receive: Presence{dnd} Presence{dnd}
Whereas I expect to receive a Presence update {available} between the 2 dnd.
Since I receive presence updates except for "available" I suppose my listener works fine. Also I suppose I correctly subscribed to my contacts' presence...
private class FriendListener implements RosterListener {
public void entriesAdded(Collection<String> addresses) { }
public void entriesUpdated(Collection<String> addresses) { }
public void entriesDeleted(Collection<String> addresses) { }
public void presenceChanged(Presence presence) {
String fromUserID = StringUtils.parseBareAddress(presence.getFrom());
System.out.println(
"Presence changed: " + fromUserID +
" Presence=" + presence.toString() +
" Type=" + presence.getType().toString() +
" Mode=" + presence.getMode().toString()
);
mainCallback_.updatePresenceFriend(fromUserID, presence);
}
}
public void subscribe(String friendID, String friendName) {
Presence presence = new Presence(Presence.Type.subscribe);
connection.sendPacket(presence);
RosterPacket rosterPacket = new RosterPacket();
rosterPacket.setType(IQ.Type.SET);
Item item = new Item(friendID, friendName);
item.setItemType(RosterPacket.ItemType.both);
rosterPacket.addRosterItem(item);
connection.sendPacket(rosterPacket);
System.out.println("Send subscribe to " + friendID);
subscribedUsers.add(friendID);
}

I found the problem!
Actually there was a bug in the log of my Listener, this line:
System.out.println(
"Presence changed: " + fromUserID +
" Presence=" + presence.toString() +
" Type=" + presence.getType().toString() +
" Mode=" + presence.getMode().toString()
);
It made crashed when Presence.getMode()==null, so that I did not process the Presence message. But no coredump was showing in the logs, I guess because the listener is in another thread...
Changing the log by the following line solved the problem
System.out.println(
"Presence changed: " + fromUserID +
" Presence=" + presence.toString()
);

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.

Getting Object tag value in AWS S3

I am using scala to get information about my objects that are in S3 I am intersted in getting each object I have inside S3 Bucket his tag value so far I have accomplished this code to get me information about my objects but did not succeeded in getting its tagging value: I used this code in scala:
def retrieveObjectTags(keyName: String): Unit ={
try {
println("Listing objects")
val req: ListObjectsV2Request =
new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2)
var result: ListObjectsV2Result = null
do {
result = client.listObjectsV2(req)
for (objectSummary <- result.getObjectSummaries) {
println(
" - " + objectSummary.getKey + " " + "(size = " + objectSummary.getSize +
")")
println(objectSummary.getETag)
}
println("Next Continuation Token : " + result.getNextContinuationToken)
req.setContinuationToken(result.getNextContinuationToken)
} while (result.isTruncated == true);
}catch {
case ase: AmazonServiceException => {
println(
"Caught an AmazonServiceException, " + "which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.")
println("Error Message: " + ase.getMessage)
println("HTTP Status Code: " + ase.getStatusCode)
println("AWS Error Code: " + ase.getErrorCode)
println("Error Type: " + ase.getErrorType)
println("Request ID: " + ase.getRequestId)
}
case ace: AmazonClientException => {
println(
"Caught an AmazonClientException, " + "which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.")
println("Error Message: " + ace.getMessage)
}
}
// val getTaggingRequest = new GetObjectTaggingRequest(bucketName,keyName)
// var getTagResult = client.getObjectTagging(getTaggingRequest)
//println(getTaggingRequest)
var tag: Tag = new Tag()
println("tag name:" + tag.getValue)
}
as for the remarked lines I have encounter a problem with it, what other way I can use to solve this problem?

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!

Google Web Toolkit - XSRF Protected Services : Invalid RPC Token

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.

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