twilio API issues when submitting whastapp query - twilio-api

I'm using HttpURLConnection to post to https://api.twilio.com/2010-04-01/Accounts/****/Messages.json
this works for SMS - but when the txtTo and txtFrom are changed to To=whatsapp:+12345567&From=whatsapp:+123456778&Body=sacsacsac
it stops working ..... any ideas?
String message = "To=" + txtTo + "&From=" + txtFrom + "&Body=" + txtBody;
byte[] postData = message.getBytes( StandardCharsets.UTF_8 );

String message = "From=" + URLEncoder.encode("whatsapp:" + txtFrom, "UTF-8") +"&Body=" + URLEncoder.encode(txtBody, "UTF-8") + "&To=" + URLEncoder.encode("whatsapp:" + txtTo, "UTF-8");

Related

Selecting sql data with multiple rows and exporting as xml file

I have this JavaScript in my transformer
var dbConn;
try {
dbConn = DatabaseConnectionFactory.createDatabaseConnection($gc('DataWarehouseXMLDataConfig').sqlDriver,
$gc('DataWarehouseXMLDataConfig').sqlConnString,
$gc('DataWarehouseXMLDataConfig').sqlUsername,
$gc('DataWarehouseXMLDataConfig').sqlPassword);
var data = dbConn.executeCachedQuery('EXEC [dbo].[GetDataWarehouseData]');
var xml = "";
var xml2 = "";
var row = "";
while(data.next()) {
row = '<referral>' + '\n' +
'<careid>' + data.getString('careid') + '</careid>' + '\n' +
'<patientid>' + data.getString('patientid') + '</patientid>' + '\n' +
'<dateofreceipt>' + data.getString('dateofreceipt') + '</dateofreceipt>' + '\n' +
'<datefirstseen>' + data.getString('datefirstseen') + '</datefirstseen>' + '\n' +
'<nhsnumber>' + data.getString('nhsnumber') + '</nhsnumber>' + '\n' +
'<hospitalnumber>' + data.getString('hospitalnumber') + '</hospitalnumber>' + '\n' +
'<surname>' + data.getString('surname') + '</surname>' + '\n' +
'<forename>' + data.getString('forename') + '</forename>' + '\n' +
'<dateofbirth>' + data.getString('dateofbirth') + '</dateofbirth>' + '\n' +
'</referral>';
xml = xml + row;
xml2 = '<?xml version="1.0" encoding="utf-8"?>' + '\n' + '<results>' + xml + '</results>';
}
channelMap.put('xml2', xml2);
} finally {
if (dbConn) {
dbConn.close();
}
}
I'm using this outbound message template
<referral>
<careid></careid>
<patientid></patientid>
<dateofreceipt></dateofreceipt>
<datefirstseen></datefirstseen>
<nhsnumber></nhsnumber>
<hospitalnumber></hospitalnumber>
<surname></surname>
<forename></forename>
<dateofbirth></dateofbirth>
</referral>
I have a File Writer destination and the File Name has a .xml extension.
My template in the File Writer is ${XmlUtil.prettyPrint(${message.encodedData})}.
The SQL data is being retrieved ok.
I don't think I'm a million miles away but I'm doing something fundamentally wrong.
What do I need to do to send the required xml file please?
I fixed this by adding a mapping step to the source transformer and using JavaScript, like
tmp['referral']['dateofbirth'] = msg['dateofbirth'].toString();

FabricJS Android Webview Newlines showing as \n

So I load a basic page with the canvas and everything seems to work except newlines are shown as \n
here is the body as a java method:
input = StringEscapeUtils.unescapeShell(this.getData());
private String htmlBody(String input){
return "<html><head>" +
"<link href=\"fonts.css\" type=\"text/css\" rel=\"stylesheet\" />" +
"<script src=\"jquery.min.js\" type=\"text/javascript\"></script>" +
"<script src=\"fontfaceobserver.js\" type=\"text/javascript\"></script>" +
"<script src=\"fabric.min.js\" type=\"text/javascript\"></script>" +
"<style type=\"text/css\">" +
".canvas-container {" +
"margin: 0 auto;" +
"}"+
"</style>" +
"<script src=\"javascript_fabric.js\" type=\"text/javascript\"></script>" +
"</head><body>"+
"<div id=\"sb2div\" class=\"row\" style=\"margin: 0 auto!important; max-height: 100vh\">" +
"<canvas id=\"fabricjs-branding\" width=\"600\" height=\"600\" style=\"margin: auto!important;\"></canvas>" +
"</div>" +
"<script>" +
"$(document).ready(function(){" +
"setUpBranding();" +
"var o = " + input + ";" +
"console.log(o);" +
"fabricjscanvas.loadFromJSON(o);"+
"});" +
"</script>" +
"</body></html>";
}
setUpBranding() does my initialization of fabricjscanvas which does add some feature prototypes but the issue has nothing to do with them.
itext and textbox are standard using the current release 4
on the desktop using the same setup everything is fine...
based on a comment i found the newline characters were not getting unescaped with the rest of the json data... strange but I was able to fix it using the Java String Replace method... after using the StringEscapeUtils.unescapeShell
input = StringEscapeUtils.unescapeShell(this.getData());
input = input.replace("\\\\n", "\\n");

Yet another "Failed to validate oauth signature and token"

I've this problem that many others have been through. I'm doing everything correct but still i get this annoying "Failed to validate oauth signature and token" error :)
Well, something got to be wrong I guess..
I'm trying to obtain a request_token by making a post to "https://api.twitter.com/oauth/request_token" with headers:
Authorization:
OAuth oauth_consumer_key="MYVq....................ywj2g",
oauth_nonce="m8NG0s4oc87AOIpuILafAeI1YoMv5Mu9",
oauth_signature="Bxb%252FFIfOG9KLVj%252FUNdV%252FycVlGPs%253D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1378976842",
oauth_version="1.0"
But it complains about signature and token.
Is my signature invalid somehow?
And for this request I dont need a token right??
I can't figure out whats wrong.
Here's some of my getRequestToken code:
val oauth_consumer_key: String = CONSUMER_KEY
val oauth_nonce: String = generateNonce()
val oauth_timestamp: String = (System.currentTimeMillis / 1000).toString
var oauth_signature: String = ""
val oauth_signature_method: String = "HMAC-SHA1"
val oauth_version: String = "1.0"
val PARAMETER_STRING: String =
"oauth_consumer_key=" + oauth_consumer_key + "&" +
"oauth_nonce=" + oauth_nonce + "&" +
"oauth_signature_method=" + oauth_signature_method + "&" +
"oauth_timestamp=" + oauth_timestamp + "&" +
"oauth_version=" + oauth_version
val BASE_STRING: String =
"POST&" + URLEncoder.encode("https://api.twitter.com/oauth/request_token", "UTF-8") + "&" + URLEncoder.encode(PARAMETER_STRING, "UTF-8")
oauth_signature = getSignature(CONSUMER_SECRET, BASE_STRING, "HmacSHA1")
val AUTHORIZATION = "OAuth " +
"oauth_consumer_key=\"" + URLEncoder.encode(oauth_consumer_key, "UTF-8") +
"\", oauth_nonce=\"" + URLEncoder.encode(oauth_nonce, "UTF-8") +
"\", oauth_signature=\"" + URLEncoder.encode(oauth_signature, "UTF-8") +
"\", oauth_signature_method=\"" + URLEncoder.encode(oauth_signature_method, "UTF-8") +
"\", oauth_timestamp=\"" + URLEncoder.encode(oauth_timestamp, "UTF-8") +
"\", oauth_version=\"" + URLEncoder.encode(oauth_version, "UTF-8") + "\""
WS.url("https://api.twitter.com/oauth/request_token").withHeaders("Authorization" -> AUTHORIZATION).post(Results.EmptyContent()).map(response => {
if(response.status != 200) Logger.error(response.body) //THIS IS WHERE I GET THE ERROR
else {
if((response.json \ "oauth_callback_confirmed").as[String] == "true") {
REQUEST_TOKEN = (response.json \ "oauth_token").as[String]
REQUEST_SECRET = (response.json \ "oauth_token_secret").as[String]
requestDone.success(true)
}
}
})
Ok so I've got everyting to work (without the oauth_callback parameter, because if I add this I get the error again).
I get the Request_token, which is valid because when I manually paste the authenticate url in the browser together with the generated request token I get redirected to twitter authenticate page and then a correct callback is made and the result is correct also. (token, token_secret, user_id and screen_name)
But my code seem to ignore my redirect to this authorize page.
requestToken_future.map { result =>
Redirect("https://api.twitter.com/oauth/authenticate?oauth_token="+REQUEST_TOKEN)
}
If I put a Logger inside the brackets it shows the log in my terminal window. But that Redirect seems to just be ignored. Never goes off.
You haven't included the oauth_callback parameter which is required. See the documentation here.

https://api.twitter.com/oauth/request_token Fails in Blackberry Native SDK

I am trying to connect to Twitter though oAuth.I am making a POST request to the API https://api.twitter.com/oauth/request_token.
Here is is example of my Base signature string
POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Fapi.ec2.phunware.com%252Fapi%252Ftwitter%26oauth_consumer_key%3D6jq5dNZcccoPbApAJ0sOaA%26oauth_nonce%3DN2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY%3D%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1362843354%26oauth_version%3D1.0
I used the tool http://quonos.nl/oauthTester/ to verify my base signature.
Here is the corresponding header
OAuth oauth_callback="http%3A%2F%2Fapi.ec2.phunware.com%2Fapi%2Ftwitter",oauth_consumer_key="6jq5dNZcccoPbApAJ0sOaA",oauth_nonce="N2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY=",oauth_signature_method="HMAC-SHA1",oauth_signature="7ney2RxElbHUl2t1Jnz57pQpmFs%3D",oauth_timestamp="1362843354",oauth_version="1.0"
I tried the following command in my MAC terminal
curl --request 'POST' 'https://api.twitter.com/oauth/request_token' --header 'Authorization: OAuth oauth_callback="http%3A%2F%2Fapi.ec2.phunware.com%2Fapi%2Ftwitter",oauth_consumer_key="6jq5dNZcccoPbApAJ0sOaA",oauth_nonce="N2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY=",oauth_signature_method="HMAC-SHA1",oauth_signature="7ney2RxElbHUl2t1Jnz57pQpmFs%3D",oauth_timestamp="1362843354",oauth_version="1.0"' --verbose
And i get 401 unauthorized error. I tried to set the oauth_callback ="oob" but I still get the same error.
Please help. I am using Blackberry Native SDK to code. I am pasting the code here. I get 204 error when I try via Blackberry 10.1 Simulator.
QByteArray Twitter::generateTimeStamp()
{
QDateTime current = QDateTime::currentDateTime();
uint seconds = current.toTime_t();
return QString::number(seconds,10).toUtf8();
}
QByteArray Twitter::generateNonce()
{
QString nonce = QUuid::createUuid().toString();
nonce.remove(QRegExp("[^a-zA-Z\\d\\s]"));
qDebug()<< nonce.toUtf8();
return nonce.toUtf8().toBase64();
}
QByteArray Twitter::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce,bool addCallbackURL)
{
QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems();
QList<QByteArray> normParameters;
QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters);
while(i.hasNext()){
QPair<QByteArray, QByteArray> queryItem = i.next();
QByteArray normItem = queryItem.first + '=' + queryItem.second;
normParameters.append(normItem);
}
//consumer key
normParameters.append(QByteArray("oauth_consumer_key=") + consumer->consumerKey());
//token
if(accessToken != NULL){
normParameters.append(QByteArray("oauth_token=") + accessToken->oauthToken());
}
//signature method, only HMAC_SHA1
normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1"));
//time stamp
normParameters.append(QByteArray("oauth_timestamp=") + timestamp);
//nonce
normParameters.append(QByteArray("oauth_nonce=") + nonce);
//version
normParameters.append(QByteArray("oauth_version=1.0"));
//callback url
if(addCallbackURL)
normParameters.append(QByteArray("oauth_callback=") + QByteArray(CALLBACK_URL).toPercentEncoding());
//OAuth spec. 9.1.1.1
qSort(normParameters);
qDebug()<<normParameters;
QByteArray normString;
QListIterator<QByteArray> j(normParameters);
while (j.hasNext()) {
normString += j.next().toPercentEncoding();
normString += "%26";
}
normString.chop(3);
qDebug()<<normString;
//OAuth spec. 9.1.2
QString urlScheme = url.scheme();
QString urlPath = url.path();
QString urlHost = url.host();
QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8();
QByteArray httpm;
switch (method)
{
case GET:
httpm = "GET";
break;
case POST:
httpm = "POST";
break;
case DELETE:
httpm = "DELETE";
break;
case PUT:
httpm = "PUT";
break;
}
qDebug()<<"signature base="<<httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
//OAuth spec. 9.1.3
return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
}
QByteArray Twitter::generateAuthorizationHeader( const QUrl& url, HttpMethod method,bool addCallbackURL )
{
QByteArray timeStamp = generateTimeStamp();
QByteArray nonce = generateNonce();
QByteArray baseString = generateSignatureBase(url, method, timeStamp, nonce,addCallbackURL);
QByteArray key = consumer->consumerSecret() + '&';
if(accessToken != NULL)
key = key + accessToken->oauthTokenSecret();
QByteArray signature = HMACSH1::hmacSha1(key,baseString).toPercentEncoding();
QByteArray header;
header += "OAuth ";
if(addCallbackURL)
header += "oauth_callback=\"" + QByteArray(CALLBACK_URL).toPercentEncoding() + "\",";
header += "oauth_consumer_key=\"" + consumer->consumerKey() + "\",";
header += "oauth_nonce=\"" + nonce + "\",";
header += "oauth_signature_method=\"HMAC-SHA1\",";
header += "oauth_signature=\"" + signature + "\",";
header += "oauth_timestamp=\"" + timeStamp + "\",";
if(accessToken != NULL)
header += "oauth_token=\"" + accessToken->oauthToken() + "\",";
header += "oauth_version=\"1.0\"";
qDebug()<<"header =" <<header;
return header;
}
void Twitter::requestForToken()
{
QUrl url(TWITTER_REQUEST_TOKEN_URL);
QByteArray oauthHeader = generateAuthorizationHeader(url, POST,true);
QNetworkRequest req(url);
req.setRawHeader("Authorization", oauthHeader);
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
req.setHeader(QNetworkRequest::ContentLengthHeader,"0");
QNetworkReply *reply = networkAccessManager->post(req, QByteArray());
connect(networkAccessManager, SIGNAL(finished ( QNetworkReply*)), this, SLOT(tokenFetchSuccessfull(QNetworkReply*)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(tokenFetchFailed(QNetworkReply::NetworkError)));
qDebug()<<"Request For Token";
}
You mentioned you are using the Native SDK, are you also using Cascades? If so, you may have better luck using the bb-cascades-oauth library from GitHub. It has built in support for OAuth1 and OAuth2.
Also, it seems that having incorrect timestamps can be a common problem, based on the tips found here, so make sure that your simulator has the correct date and time.
Another developer here found that the http://quonos.nl/oauthTester/ was requiring a double escaped header which was incorrect, and causing 401 errors when making an actual authentication request. I noticed you used the same tester, and also have the double escaping in your base signature string above, so you might want to try without the double escaping.

Error C#.NET 3.0: The best overloaded method match for 'CreatePageSection(ref string, ref string, ref object)' has some invalid arguments

I have got the following problem. I encountered an error regarding the default parameters. I added a simple piece of code for an overload. Now I get in the new code (line 3: CreatePageSection(sItemID, "", null);) gives the error mentioned in the title.
I looked for the answer in the other topics, but I can't find the problem. Can someone help me?
The code is found here:
public void CreatePageSection(ref string sItemID)
{
CreatePageSection(sItemID, "", null);
}
public void CreatePageSection(ref string sItemID, ref string sFrameUrl, ref object vOnReadyState)
{
if (Strings.InStr(msPresentPageSections, "|" + sItemID + "|", 0) > 0) {
return;
}
msPresentPageSections = msPresentPageSections + sItemID + "|";
string writeHtml = "<div class=" + MConstants.QUOTE + "PageSection" + MConstants.QUOTE + " id=" + MConstants.QUOTE + "Section" + sItemID + "Div" + MConstants.QUOTE + " style=" + MConstants.QUOTE + "display: none;" + MConstants.QUOTE + ">";
this.WriteLine_Renamed(ref writeHtml);
//UPGRADE_WARNING: Couldn't resolve default property of object vOnReadyState. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//UPGRADE_NOTE: IsMissing() was changed to IsNothing_Renamed(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="8AE1CB93-37AB-439A-A4FF-BE3B6760BB23"'
writeHtml = " <iframe id=" + MConstants.QUOTE + sItemID + "Frame" + MConstants.QUOTE + " name=" + MConstants.QUOTE + sItemID + "Frame" + MConstants.QUOTE + " frameborder=" + MConstants.QUOTE + "0" + MConstants.QUOTE + (!string.IsNullOrEmpty(sFrameUrl) ? " src=" + MConstants.QUOTE + sFrameUrl + MConstants.QUOTE : "") + ((vOnReadyState == null) ? "" : " onreadystatechange=" + MConstants.QUOTE + Convert.ToString(vOnReadyState) + MConstants.QUOTE) + ">";
this.WriteLine_Renamed(ref writeHtml);
writeHtml = " </iframe>";
this.WriteLine_Renamed(ref writeHtml);
writeHtml = "</div>";
this.WriteLine_Renamed(ref writeHtml);
}
you must pass params by reference
public void CreatePageSection(ref string sItemID)
{
var missingString = String.Empty;
object missingObject = null;
CreatePageSection(ref sItemID, ref missingString, ref missingObject);
}
Since your are not manipulating sFrameUrl and vOnReadyState, remove the ref keyword from those parameters.
See: http://msdn.microsoft.com/en-us/library/14akc2c7(v=vs.71).aspx
hth
Mario