There are a lot of libraries or tools to query the Twitter API using Python, PHP, Javascript and other programming languages, but there is nothing to query it using Pentaho PDI (aka Kettle). So with a little research and time, i successfully implemented the OAUTH authentication required to use the Twitter REST API using native Kettle steps. I can now query Twitter with Pentaho Data Integration !
1 – Register an application with Twitter to get the your API and Consumer Key
Before stepping into Kettle, you will need to register an Application to obtain your OAUTH Access Token. Create an application using the “tokens from dev.twitter.com” (follow the steps from the previous link.. this is pretty straight forward). Once the application registered, you have the minimum information to build the OAUTH request:
- API Key
- API Secret
- Access Token
- Access Token Secret
The information can be found in the API Keys tab of your Application.
2- Understanding how it works
The Twitter API is based on HTTP Protocol and authentication relies on OAUTH Protocol. So basically, all the HTTP requests have to provide OAUTH information in the HTTP Authorization Header as per the image below:
I suggest to read the Authorization Request page of the API Documentation to understand the specifications. Read it twice. The challenge with Kettle is to generate the HTTP Header.
3- Create a transformation
This is where the fun starts! Now that you have read Authorization Request page twice, you know that some information like OAUTH_NONCE and OAUTH_TIMESTAMPS have to be generated for each request. Before stepping into details, let’s see the big picture with an example.
I will do a request using the Search/Tweet call and search for the word “#pentaho”.
- I need the URL where to send the request
- I need specific parameters to the Search/Tweet call
- I need to generate the HTTP Header
- I need to send the HTTP request
- I need to extract the data from the JSON result
The transformation should look like:
Let’s see each step in details
3.1 – Data Grid
I use 2 different Data Grids, the first is all the static data needed to create OAUTH authentication. The second is the API URI and HTTP Method used to do the call. The OAUTH data grid is always the same whatever the call is, so it can be copied/pasted in other transformation if needed. It also allows creating a more advanced transformation using subtransformation.
3.2 – Modified Java Script Value – Generate Header
It is possible to achieve almost anything with the Java Script step. I used it to generate the HTTP Header with 2 libraries I found on Internet. All the credit goes to Netflix Inc and Paul Johnston for publishing the libraries that do the magic. I just added a few lines at the end of the script.
Make sure to edit the variable URL_PARM at line 763 to reflect the specific parameters corresponding to the API Call.
For the Search/Tweets call, the parameters are
https://api.twitter.com/1.1/search/tweets.json?q=%23pentaho&count=4&result_type=mixed
So the line 763 will be
1 |
var URL_PARAM = 'q=' + encodeURIComponent('#pentaho') + '&count=2&result_type=mixed'; |
encodeURIComponent is used to “URL ENCODE” the string.
Here is the full script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 |
/* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));} function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));} function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));} function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));} function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));} function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));} /* * Perform a simple self-test to see if the VM is working */ function sha1_vm_test() { return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"; } /* * Calculate the SHA-1 of an array of big-endian words, and a bit length */ function core_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for(var j = 0; j < 80; j++) { if(j < 16) w[j] = x[i + j]; else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); } /* * Perform the appropriate triplet combination function for the current * iteration */ function sha1_ft(t, b, c, d) { if(t < 20) return (b & c) | ((~b) & d); if(t < 40) return b ^ c ^ d; if(t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; } /* * Determine the appropriate additive constant for the current iteration */ function sha1_kt(t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* * Calculate the HMAC-SHA1 of a key and some data */ function core_hmac_sha1(key, data) { var bkey = str2binb(key); if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz); var ipad = Array(16), opad = Array(16); for(var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz); return core_sha1(opad.concat(hash), 512 + 160); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert an 8-bit or 16-bit string to an array of big-endian words * In 8-bit function, characters >255 have their hi-byte silently ignored. */ function str2binb(str) { var bin = Array(); var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32); return bin; } /* * Convert an array of big-endian words to a string */ function binb2str(bin) { var str = ""; var mask = (1 << chrsz) - 1; for(var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask); return str; } /* * Convert an array of big-endian words to a hex string. */ function binb2hex(binarray) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF); } return str; } /* * Convert an array of big-endian words to a base-64 string */ function binb2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; for(var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF); for(var j = 0; j < 4; j++) { if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } return str; } /* * Copyright 2008 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Here's some JavaScript software for implementing OAuth. This isn't as useful as you might hope. OAuth is based around allowing tools and websites to talk to each other. However, JavaScript running in web browsers is hampered by security restrictions that prevent code running on one website from accessing data stored or served on another. Before you start hacking, make sure you understand the limitations posed by cross-domain XMLHttpRequest. On the bright side, some platforms use JavaScript as their language, but enable the programmer to access other web sites. Examples include Google Gadgets, and Microsoft Vista Sidebar. For those platforms, this library should come in handy. */ // The HMAC-SHA1 signature method calls b64_hmac_sha1, defined by // http://pajhome.org.uk/crypt/md5/sha1.js /* An OAuth message is represented as an object like this: {method: "GET", action: "http://server.com/path", parameters: ...} The parameters may be either a map {name: value, name2: value2} or an Array of name-value pairs [[name, value], [name2, value2]]. The latter representation is more powerful: it supports parameters in a specific sequence, or several parameters with the same name; for example [["a", 1], ["b", 2], ["a", 3]]. Parameter names and values are NOT percent-encoded in an object. They must be encoded before transmission and decoded after reception. For example, this message object: {method: "GET", action: "http://server/path", parameters: {p: "x y"}} ... can be transmitted as an HTTP request that begins: GET /path?p=x%20y HTTP/1.0 (This isn't a valid OAuth request, since it lacks a signature etc.) Note that the object "x y" is transmitted as x%20y. To encode parameters, you can call OAuth.addToURL, OAuth.formEncode or OAuth.getAuthorization. This message object model harmonizes with the browser object model for input elements of an form, whose value property isn't percent encoded. The browser encodes each value before transmitting it. For example, see consumer.setInputs in example/consumer.js. */ /* This script needs to know what time it is. By default, it uses the local clock (new Date), which is apt to be inaccurate in browsers. To do better, you can load this script from a URL whose query string contains an oauth_timestamp parameter, whose value is a current Unix timestamp. For example, when generating the enclosing document using PHP: <script src="oauth.js?oauth_timestamp=<?=time()?>" ... Another option is to call OAuth.correctTimestamp with a Unix timestamp. */ var OAuth; if (OAuth == null) OAuth = {}; OAuth.setProperties = function setProperties(into, from) { if (into != null && from != null) { for (var key in from) { into[key] = from[key]; } } return into; } OAuth.setProperties(OAuth, // utility functions { percentEncode: function percentEncode(s) { if (s == null) { return ""; } if (s instanceof Array) { var e = ""; for (var i = 0; i < s.length; ++s) { if (e != "") e += '&'; e += OAuth.percentEncode(s[i]); } return e; } s = encodeURIComponent(s); // Now replace the values which encodeURIComponent doesn't do // encodeURIComponent ignores: - _ . ! ~ * ' ( ) // OAuth dictates the only ones you can ignore are: - _ . ~ // Source: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent s = s.replace(/\!/g, "%21"); s = s.replace(/\*/g, "%2A"); s = s.replace(/\'/g, "%27"); s = s.replace(/\(/g, "%28"); s = s.replace(/\)/g, "%29"); return s; } , decodePercent: function decodePercent(s) { if (s != null) { // Handle application/x-www-form-urlencoded, which is defined by // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1 s = s.replace(/\+/g, " "); } return decodeURIComponent(s); } , /** Convert the given parameters to an Array of name-value pairs. */ getParameterList: function getParameterList(parameters) { if (parameters == null) { return []; } if (typeof parameters != "object") { return OAuth.decodeForm(parameters + ""); } if (parameters instanceof Array) { return parameters; } var list = []; for (var p in parameters) { list.push([p, parameters[p]]); } return list; } , /** Convert the given parameters to a map from name to value. */ getParameterMap: function getParameterMap(parameters) { if (parameters == null) { return {}; } if (typeof parameters != "object") { return OAuth.getParameterMap(OAuth.decodeForm(parameters + "")); } if (parameters instanceof Array) { var map = {}; for (var p = 0; p < parameters.length; ++p) { var key = parameters[p][0]; if (map[key] === undefined) { // first value wins map[key] = parameters[p][1]; } } return map; } return parameters; } , getParameter: function getParameter(parameters, name) { if (parameters instanceof Array) { for (var p = 0; p < parameters.length; ++p) { if (parameters[p][0] == name) { return parameters[p][1]; // first value wins } } } else { return OAuth.getParameterMap(parameters)[name]; } return null; } , formEncode: function formEncode(parameters) { var form = ""; var list = OAuth.getParameterList(parameters); for (var p = 0; p < list.length; ++p) { var value = list[p][1]; if (value == null) value = ""; if (form != "") form += '&'; form += OAuth.percentEncode(list[p][0]) +'='+ OAuth.percentEncode(value); } return form; } , decodeForm: function decodeForm(form) { var list = []; var nvps = form.split('&'); for (var n = 0; n < nvps.length; ++n) { var nvp = nvps[n]; if (nvp == "") { continue; } var equals = nvp.indexOf('='); var name; var value; if (equals < 0) { name = OAuth.decodePercent(nvp); value = null; } else { name = OAuth.decodePercent(nvp.substring(0, equals)); value = OAuth.decodePercent(nvp.substring(equals + 1)); } list.push([name, value]); } return list; } , setParameter: function setParameter(message, name, value) { var parameters = message.parameters; if (parameters instanceof Array) { for (var p = 0; p < parameters.length; ++p) { if (parameters[p][0] == name) { if (value === undefined) { parameters.splice(p, 1); } else { parameters[p][1] = value; value = undefined; } } } if (value !== undefined) { parameters.push([name, value]); } } else { parameters = OAuth.getParameterMap(parameters); parameters[name] = value; message.parameters = parameters; } } , setParameters: function setParameters(message, parameters) { var list = OAuth.getParameterList(parameters); for (var i = 0; i < list.length; ++i) { OAuth.setParameter(message, list[i][0], list[i][1]); } } , /** Fill in parameters to help construct a request message. This function doesn't fill in every parameter. The accessor object should be like: {consumerKey:'foo', consumerSecret:'bar', accessorSecret:'nurn', token:'krelm', tokenSecret:'blah'} The accessorSecret property is optional. */ completeRequest: function completeRequest(message, accessor) { if (message.method == null) { message.method = "GET"; } var map = OAuth.getParameterMap(message.parameters); if (map.oauth_consumer_key == null) { OAuth.setParameter(message, "oauth_consumer_key", accessor.consumerKey || ""); } if (map.oauth_token == null && accessor.token != null) { OAuth.setParameter(message, "oauth_token", accessor.token); } if (map.oauth_version == null) { OAuth.setParameter(message, "oauth_version", "1.0"); } if (map.oauth_timestamp == null) { OAuth.setParameter(message, "oauth_timestamp", OAuth.timestamp()); } if (map.oauth_nonce == null) { OAuth.setParameter(message, "oauth_nonce", OAuth.nonce(6)); } OAuth.SignatureMethod.sign(message, accessor); } , setTimestampAndNonce: function setTimestampAndNonce(message) { OAuth.setParameter(message, "oauth_timestamp", OAuth.timestamp()); OAuth.setParameter(message, "oauth_nonce", OAuth.nonce(6)); } , addToURL: function addToURL(url, parameters) { newURL = url; if (parameters != null) { var toAdd = OAuth.formEncode(parameters); if (toAdd.length > 0) { var q = url.indexOf('?'); if (q < 0) newURL += '?'; else newURL += '&'; newURL += toAdd; } } return newURL; } , /** Construct the value of the Authorization header for an HTTP request. */ getAuthorizationHeader: function getAuthorizationHeader(realm, parameters) { var header = 'OAuth realm="' + OAuth.percentEncode(realm) + '"'; var list = OAuth.getParameterList(parameters); for (var p = 0; p < list.length; ++p) { var parameter = list[p]; var name = parameter[0]; if (name.indexOf("oauth_") == 0) { header += ',' + OAuth.percentEncode(name) + '="' + OAuth.percentEncode(parameter[1]) + '"'; } } return header; } , /** Correct the time using a parameter from the URL from which the last script was loaded. */ correctTimestampFromSrc: function correctTimestampFromSrc(parameterName) { parameterName = parameterName || "oauth_timestamp"; var scripts = document.getElementsByTagName('script'); if (scripts == null || !scripts.length) return; var src = scripts[scripts.length-1].src; if (!src) return; var q = src.indexOf("?"); if (q < 0) return; parameters = OAuth.getParameterMap(OAuth.decodeForm(src.substring(q+1))); var t = parameters[parameterName]; if (t == null) return; OAuth.correctTimestamp(t); } , /** Generate timestamps starting with the given value. */ correctTimestamp: function correctTimestamp(timestamp) { OAuth.timeCorrectionMsec = (timestamp * 1000) - (new Date()).getTime(); } , /** The difference between the correct time and my clock. */ timeCorrectionMsec: 0 , timestamp: function timestamp() { var t = (new Date()).getTime() + OAuth.timeCorrectionMsec; return Math.floor(t / 1000); } , nonce: function nonce(length) { var chars = OAuth.nonce.CHARS; var result = ""; for (var i = 0; i < length; ++i) { var rnum = Math.floor(Math.random() * chars.length); result += chars.substring(rnum, rnum+1); } return result; } }); OAuth.nonce.CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; /** Define a constructor function, without causing trouble to anyone who was using it as a namespace. That is, if parent[name] already existed and had properties, copy those properties into the new constructor. */ OAuth.declareClass = function declareClass(parent, name, newConstructor) { var previous = parent[name]; parent[name] = newConstructor; if (newConstructor != null && previous != null) { for (var key in previous) { if (key != "prototype") { newConstructor[key] = previous[key]; } } } return newConstructor; } /** An abstract algorithm for signing messages. */ OAuth.declareClass(OAuth, "SignatureMethod", function OAuthSignatureMethod(){}); OAuth.setProperties(OAuth.SignatureMethod.prototype, // instance members { /** Add a signature to the message. */ sign: function sign(message) { var baseString = OAuth.SignatureMethod.getBaseString(message); var signature = this.getSignature(baseString); OAuth.setParameter(message, "oauth_signature", signature); return signature; // just in case someone's interested } , /** Set the key string for signing. */ initialize: function initialize(name, accessor) { var consumerSecret; if (accessor.accessorSecret != null && name.length > 9 && name.substring(name.length-9) == "-Accessor") { consumerSecret = accessor.accessorSecret; } else { consumerSecret = accessor.consumerSecret; } this.key = OAuth.percentEncode(consumerSecret) +"&"+ OAuth.percentEncode(accessor.tokenSecret); } }); /* SignatureMethod expects an accessor object to be like this: {tokenSecret: "lakjsdflkj...", consumerSecret: "QOUEWRI..", accessorSecret: "xcmvzc..."} The accessorSecret property is optional. */ // Class members: OAuth.setProperties(OAuth.SignatureMethod, // class members { sign: function sign(message, accessor) { var name = OAuth.getParameterMap(message.parameters).oauth_signature_method; if (name == null || name == "") { name = "HMAC-SHA1"; OAuth.setParameter(message, "oauth_signature_method", name); } OAuth.SignatureMethod.newMethod(name, accessor).sign(message); } , /** Instantiate a SignatureMethod for the given method name. */ newMethod: function newMethod(name, accessor) { var impl = OAuth.SignatureMethod.REGISTERED[name]; if (impl != null) { var method = new impl(); method.initialize(name, accessor); return method; } var err = new Error("signature_method_rejected"); var acceptable = ""; for (var r in OAuth.SignatureMethod.REGISTERED) { if (acceptable != "") acceptable += '&'; acceptable += OAuth.percentEncode(r); } err.oauth_acceptable_signature_methods = acceptable; throw err; } , /** A map from signature method name to constructor. */ REGISTERED : {} , /** Subsequently, the given constructor will be used for the named methods. The constructor will be called with no parameters. The resulting object should usually implement getSignature(baseString). You can easily define such a constructor by calling makeSubclass, below. */ registerMethodClass: function registerMethodClass(names, classConstructor) { for (var n = 0; n < names.length; ++n) { OAuth.SignatureMethod.REGISTERED[names[n]] = classConstructor; } } , /** Create a subclass of OAuth.SignatureMethod, with the given getSignature function. */ makeSubclass: function makeSubclass(getSignatureFunction) { var superClass = OAuth.SignatureMethod; var subClass = function() { superClass.call(this); }; subClass.prototype = new superClass(); // Delete instance variables from prototype: // delete subclass.prototype... There aren't any. subClass.prototype.getSignature = getSignatureFunction; subClass.prototype.constructor = subClass; return subClass; } , getBaseString: function getBaseString(message) { var URL = message.action; var q = URL.indexOf('?'); var parameters; if (q < 0) { parameters = message.parameters; } else { // Combine the URL query string with the other parameters: parameters = OAuth.decodeForm(URL.substring(q + 1)); var toAdd = OAuth.getParameterList(message.parameters); for (var a = 0; a < toAdd.length; ++a) { parameters.push(toAdd[a]); } } return OAuth.percentEncode(message.method.toUpperCase()) +'&'+ OAuth.percentEncode(OAuth.SignatureMethod.normalizeUrl(URL)) +'&'+ OAuth.percentEncode(OAuth.SignatureMethod.normalizeParameters(parameters)); } , normalizeUrl: function normalizeUrl(url) { var uri = OAuth.SignatureMethod.parseUri(url); var scheme = uri.protocol.toLowerCase(); var authority = uri.authority.toLowerCase(); var dropPort = (scheme == "http" && uri.port == 80) || (scheme == "https" && uri.port == 443); if (dropPort) { // find the last : in the authority var index = authority.lastIndexOf(":"); if (index >= 0) { authority = authority.substring(0, index); } } var path = uri.path; if (!path) { path = "/"; // conforms to RFC 2616 section 3.2.2 } // we know that there is no query and no fragment here. return scheme + "://" + authority + path; } , parseUri: function parseUri (str) { /* This function was adapted from parseUri 1.2.1 http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js */ var o = {key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], parser: {strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ }}; var m = o.parser.strict.exec(str); var uri = {}; var i = 14; while (i--) uri[o.key[i]] = m[i] || ""; return uri; } , normalizeParameters: function normalizeParameters(parameters) { if (parameters == null) { return ""; } var list = OAuth.getParameterList(parameters); var sortable = []; for (var p = 0; p < list.length; ++p) { var nvp = list[p]; if (nvp[0] != "oauth_signature") { sortable.push([ OAuth.percentEncode(nvp[0]) + " " // because it comes before any character that can appear in a percentEncoded string. + OAuth.percentEncode(nvp[1]) , nvp]); } } sortable.sort(function(a,b) { if (a[0] < b[0]) return -1; if (a[0] > b[0]) return 1; return 0; }); var sorted = []; for (var s = 0; s < sortable.length; ++s) { sorted.push(sortable[s][1]); } return OAuth.formEncode(sorted); } }); OAuth.SignatureMethod.registerMethodClass(["PLAINTEXT", "PLAINTEXT-Accessor"], OAuth.SignatureMethod.makeSubclass( function getSignature(baseString) { return this.key; } )); OAuth.SignatureMethod.registerMethodClass(["HMAC-SHA1", "HMAC-SHA1-Accessor"], OAuth.SignatureMethod.makeSubclass( function getSignature(baseString) { b64pad = '='; var signature = b64_hmac_sha1(this.key, baseString); return signature; } )); try { OAuth.correctTimestampFromSrc(); } catch(e) { } /*************************************************************************************** * * Build the header * ***************************************************************************************/ var URL_PARAM = 'q=' + encodeURIComponent('pentaho') + '&count=2&result_type=mixed'; var accessor = { consumerSecret: oauth_consumer_secret , tokenSecret : oauth_token_secret}; var message = { method: HTTP_METHOD , action: URL , parameters: OAuth.decodeForm(URL_PARAM) }; var oauth_timestamp = Math.round(new Date().getTime()/1000.0); var oauth_nonce = OAuth.nonce(11); message.parameters.push(['oauth_consumer_key', oauth_consumer_key]); message.parameters.push(['oauth_nonce', oauth_nonce]); message.parameters.push(['oauth_signature_method', oauth_signature_method]); message.parameters.push(['oauth_timestamp', oauth_timestamp]); message.parameters.push(['oauth_token', oauth_token]); message.parameters.push(['oauth_version', oauth_version]); OAuth.SignatureMethod.sign(message, accessor); var REST_HEADER = OAuth.getAuthorizationHeader("", message.parameters); var REST_URL = URL+'?'+URL_PARAM |
The oauth_xxxxxx variables come from previous Data Grids. The final result is the REST_HEADER and REST_URL. Both variables are sent to next transformation’s step (REST Client).
3.3 – Rest Client
The Rest Client step is pretty simple because all parameters have been defined in the previous steps. The Headers tab enables you to define the content of any HTTP headers using an existing field. This is where the REST_HEADER variable is defined as Authentification header.
The answer from Twitter is sent to the “result” variable. It could be the expected answer but it could be an error message too. A good error handling mechanism has to be developed. For the sake of the demo, I assume getting the expected answer.
3.4 – JSON and Text Output
Twitter sends the result with a JSON format. The first “Text Output Raw Json” step is a debugging step I use to develop the transformation. It’s very useful to have the original JSON answer to build a good JsonPath expression in the JSON step.
For the demo, I created 2 CSV, the first for the twit message and the second for each hashtags of each twit message.
Conclusion
As you can see, it’s pretty easy to retrieve data from Twitter. You can call another API’s function by changing the URI (in the datagrid), the parameter string (in Javascript) and the Jsonpath (JSON Step). And there you go ! You now have data to create analysis!
You can download the demo transformation from my github repo: https://github.com/patlaf/pdi_scripts
New Blog Post: Query Twitter API with #Pentaho #PDI http://t.co/YHQUgr9igG
Thank you for your posting. Would love to see more of API call from PDI.
Have you tried making Omniture API call? I wonder I can also utilize this OAUTH for omniture.
Thx for the comment ! I’ve never try Omniture. However, I’m planning to use the StackOverflow API soon.. I’ll probably write about it once done !
Thanks, was looking for something like this. Gonna test this out.
Hi Patlaf,
Tested your code and got it running and I have couple of doubts. I am not familiar with Java and please excuse if these are dumb.
1. In the Java code “ ” was throwing syntax errors and I had to remove all of them to get the code running. Was this due to my environment issue ?
2. Even after removing the nbsp the Java code was throwing “Error: signature_method_rejected (script#624)” errors while testing Modified java script and running ” Get Variables” . I ignored the errror and the transformation ran without issues. Below is the error. Please let me know if I can do something to resolve this.
——————— Error ————————-
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – ERROR (version 5.0.1-stable, build 1 from 2013-11-15_16-08-58 by buildguy) : Unexpected error
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – ERROR (version 5.0.1-stable, build 1 from 2013-11-15_16-08-58 by buildguy) : org.pentaho.di.core.exception.KettleValueException:
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – Javascript error:
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – Error: signature_method_rejected (script#624)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 –
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesMod.addValues(ScriptValuesMod.java:457)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesMod.processRow(ScriptValuesMod.java:692)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.pentaho.di.trans.step.RunThread.run(RunThread.java:60)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at java.lang.Thread.run(Unknown Source)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – Caused by: org.mozilla.javascript.JavaScriptException: Error: signature_method_rejected (script#624)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.mozilla.javascript.gen.script_1._c_newMethod_41(script:624)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.mozilla.javascript.gen.script_1.call(script)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:76)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 – at org.mozilla.javascript.gen.script_1._c_sign_40(script:606)
2014/06/14 20:38:14 – Modified Java Script Value – Generate Header.0 –
————————–
Hi Rahul,
Did you got any solution in this error.
I have some clue here,
1) for your first issue regarding “ ”, this is just a ‘standard space’ specification in HTML, and so it is working here the same, and that is no need of it here. So it is OK to delete all of it out of this script.
2) After above now we got another error here as “Error: signature_method_rejected” at line # 624. I think this is because of we need to define it as “HMAC-SHA1″, which is done in second parameter definiton at line # 603 of this script. But it is still providing error for me too.
I don’t know much of java script, but have these clues regarding this error.
If you have any solution of it or got any reply, Please Share.
with regards,
Rahul Trivedi
Excellent post. I tried the transformation and it works perfectly. Thank you very much!
Nice Blog. If i want to generate the signature for Oauth2 version. How can i do that using PDI ?
Great Job! Thanks for sharing your knowledge.
Great work!!!
It is just what I was looking for….
One simple question:I run the ‘pentaho’ search with this Kettle steps and in my twitter account(“search”). I found very different results, not only in the number of tweets but also in the languaje of the selected tweets. The kettle steps gave me mostly english, while my account gave me results mostly in spanish. How can I make the search in kettle steps to be similar to that in my account?
thanks in advance.
Claudiio
@Claudio Look at the different parameters of the call https://dev.twitter.com/docs/api/1.1/get/search/tweets
There is many parameters that can be set that will get you different result. I would start with the “result_type” and the lang first.
Hi patlaf
Recently visited this blog, It solved a part of one of my problem.
Thanks :)
Also found that the Demo Transformation is not on the link you provided above, (may be, its deleted).
Can you please provide it back.
with regards,
Rahul Trivedi
Hello, the file should be downloadable now.. Sorry for the buggy link !
Hi Patlaf,
Now I am testing (or trying :-) ) to use this for an Twitter streaming api like this:
==========================
https://stream.twitter.com/1.1/statuses/filter.json?delimited=length&track=twitterapi
or
https://stream.twitter.com/1.1/statuses/firehose.json
==========================
But every time it gives me “Bad Authentication” message json data in result column.
so here, I am curious that, Is our Previous Tokens and Keys are not enough here for Streaming API?
Or
I have to follow a different process (or use different java script) for this kind of streaming API?
There is one more question that, Is our “Rest Client” step is able to sustain a slightly long duration HTTP connection (which is required in this Streaming API).
http://forums.pentaho.com/showthread.php?173275-How-to-Implement-Twitter-quot-Streaming-quot-API-with-Oauth-1-1
Hey Rahul,
I’m currently working on a new script that uses the streaming api. I’ll post it once done !
How to do the it in java instead of doing in js
Hi Patlaf,
Seems that the file link in the post is broken, please share the file again.
Thanks.
I uploaded the script to my github repo: https://github.com/patlaf/pdi_scripts
Thanks a lot Patlaf. I experimented with the script it is working gr8. Just that there is some error in hashtags component, which I will spend some more time to figure out.
However, this script does not utilize the streaming api.. Have you experimented with streaming api, because this way we cannot keep getting the real time stats and push to file or db for instance for seeing the what people are tweeting in real time.
Thanks once again, hope to hear from you.
Hi Patlaf,
did you got any thing now regarding Twitter streaming API as you stated above.
Can’t we just use twitter4J libraries in Kettle.
I had successfully implemented streaming API in java code through Twitter4J.
Hey Rahul,
I didn’t have time yet. I’ve been really busy the last weeks. I suppose it’s possible to use twitter4J in Kettle since everything is Java. However, I’m not a Java developer so I believe we are actually facing the same problem.
I’m currently using the streaming API with R and I’m thinking implementing it with kettle with the “R script executor” plugin available in the marketplace. Let me know if it’s something that might interest you !
[…] one of my previous posts (Query Twitter Api With Pentaho PDI), many people asked for a way to use the Twitter Streaming API with Pentaho PDI. Implementing […]
I like this method but i don’t know how to get more than 100 tweets, if you know please help me
[…] Pentaho: http://www.patlaf.com/query-twitter-api-with-pentaho-pdi-kettle/ […]
Thank you very much for sharing this transformation. Have you done something similar for Google calendar API?
Thanks a lot Patlaf, great job.. Very useful..