How to get back the original string after decompressing - Zlib - javascript

I am trying to compress and decompress the string using Zlib. Here is the JS file I'm using to compress and decompress.
Compression code:
compress_string = function () {
var string = document.getElementById("input_value").value;
var deflate = new Zlib.Deflate(string);
var compressed = deflate.compress();
var b64encoded = btoa(String.fromCharCode.apply(null, compressed));
var elem = document.getElementById("input_value");
elem.value = b64encoded;
var elemLabel = document.getElementById("zlsize");
elemLabel.value = ("Size of sample is: " + string.length) + " " + ("Compressed Value: " + b64encoded + " Size: " + b64encoded.length);
}
After compressing I'm setting the compressed value back to the input_value text field.
Decompression Code:
decompress_string = function () {
var string = document.getElementById("input_value").value;
var compressData = new Uint8Array(atob(string).split("").map(function(c) { return c.charCodeAt(0); }))
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
var elem = document.getElementById("input_value");
elem.value = btoa(plain);
var elemLabel = document.getElementById("zlsize");
elemLabel.value = ("Size of compressed string is: " + string.length) + " " + ("Decompressed Value: " + plain + " Size: " + plain.length);
}
I'm trying to compress below sample string:
<xml><username>myusername</username><password>mypassword</password></xml>
Size of sample is: 73
Compressed Value: eJxNibEJAAAMg/7/OjoEdCjGAoAnmqg6fF8T7QMfCxxR
Size: 44
When trying to decompress the above compressed string, I'm getting an object of Uint8Array as below:
Size of compressed string is: 44
Decompressed Value: [object Uint8Array]
Size: 70
While trying to convert the object Uint8Array to string using btoa(), the output is like below:
W29iamVjdCBVaW50OEFycmF5XQ==
Question: How to get the original string?

Your problem is text encoding.
Uint8Array is a binary representation of something, and strings can be written in many formats. You need to stick to one, and convert using that.
I've chosen UTF-8 in this example, using this library
function compress(input){
var binaryconverter = new TextEncoder('utf-8');
var binary = binaryconverter.encode(input);
var deflate = new Zlib.Deflate(binary);
var compressed = deflate.compress();
return btoa(String.fromCharCode.apply(null, compressed));
}
function decompress(b64encoded){
var compressed = new Uint8Array(atob(b64encoded).split("").map(function(c){return c.charCodeAt(0);}));
var inflate = new Zlib.Inflate(compressed);
var binary = inflate.decompress();
var binaryconverter = new TextDecoder('utf-8');
return binaryconverter.decode(binary);
}
var input = '<xml><username>myusername</username><password>mypassword</password></xml>';
var b64encoded = compress(input);
var output = decompress(b64encoded);
alert(output);
So, when encoding, I first convert the string to the binary representation of the text in UTF-8 format, then I'm using ZLib to compress, and then again this is converted to a base64 string for ease of transfer.
To decompress, you do the inverse thing: first decode the base64 string, then ZLib to inflate and finally again we convert binary to string using UTF-8

Documentation zlib.js appear to suggest plain (input) of type Array.<number> or Uint8Array
// plain = Array.<number> or Uint8Array
var deflate = new Zlib.Deflate(plain);
var compressed = deflate.compress();
at OP , var string appear to be type string , see
var string = document.getElementById("input_value").value;
var deflate = new Zlib.Deflate(string);
To retrieve the text value from compressed , base64 formatted string , below ; first , map var string to .charCodeAt() number , returning array of numbers representing text characters ; second , push .charCodeAt() numbers to map array ; third, call window.btoa(encodeURIComponent(escape(compressed[i]))) on each item within array of charCodeAt() values , pushed to same map array; fourth , decode base64encoded string in for loop , calling String.fromCharCode(plain[i]) on decompressed Uint8Array , returning original input string.
Try
var elem = document.getElementById("input_value")
, elemLabel = document.getElementById("zlsize")
, compress = document.getElementById("compress")
, decompress = document.getElementById("decompress")
, b64map = []
, _b64encoded
, b64encoded
, _string
, string
, _plain
, compressData;
function compress_string () {
string = elem.value;
_string = [].slice.call(string).map(function (value, key) {
return value.charCodeAt(0)
});
var deflate = new Zlib.Deflate(_string);
var compressed = deflate.compress();
for (var i = 0; i < compressed.length; i++) {
b64map.push([compressed[i]
, window.btoa(encodeURIComponent(escape(compressed[i])))])
};
_b64encoded = b64map.map(function (value, key) {
return value[1]
});
b64encoded = _b64encoded.join("");
elem.value = b64encoded;
elemLabel.innerText = ("Size of sample is: "
+ string.length) + " " + ("Compressed Value: "
+ b64encoded + " Size: " + b64encoded.length)
};
function decompress_string () {
string = elem.value;
elem.value = "";
compressData = _b64encoded.map(function (value, key) {
return new RegExp(value).test(string) ? b64map[key][0] : null
});
compressData = new Uint8Array(compressData);
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
b64map = b64encoded = [];
_plain = "";
for (var i = 0; i < plain.length; i++) {
_plain += String.fromCharCode(plain[i])
};
elem.value = _plain;
elemLabel.innerText = ("Size of compressed string is: "
+ elem.value.length) + " "
+ ("Decompressed Value: " + _plain + " Size: "
+ _plain.length);
};
compress.addEventListener("click", compress_string);
decompress.addEventListener("click", decompress_string);
jsfiddle http://jsfiddle.net/guest271314/ov6nwLak/
$.getScript("https://raw.githubusercontent.com/imaya/zlib.js/master/bin/zlib.min.js")
var elem = document.getElementById("input_value")
, elemLabel = document.getElementById("zlsize")
, compress = document.getElementById("compress")
, decompress = document.getElementById("decompress")
, b64map = []
, _b64encoded
, b64encoded
, _string
, string
, _plain
, compressData;
elem.value = "<xml><username>myusername</username><password>mypassword</password></xml>";
function compress_string () {
string = elem.value;
_string = [].slice.call(string).map(function (value, key) {
return value.charCodeAt(0)
});
var deflate = new Zlib.Deflate(_string);
var compressed = deflate.compress();
for (var i = 0; i < compressed.length; i++) {
b64map.push([compressed[i]
, window.btoa(encodeURIComponent(escape(compressed[i])))])
};
_b64encoded = b64map.map(function (value, key) {
return value[1]
});
b64encoded = _b64encoded.join("");
elem.value = b64encoded;
elemLabel.innerText = ("Size of sample is: "
+ string.length) + " " + ("Compressed Value: "
+ b64encoded + " Size: " + b64encoded.length)
};
function decompress_string () {
string = elem.value;
elem.value = "";
compressData = _b64encoded.map(function (value, key) {
return new RegExp(value).test(string) ? b64map[key][0] : null
});
compressData = new Uint8Array(compressData);
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
b64map = b64encoded = [];
_plain = "";
for (var i = 0; i < plain.length; i++) {
_plain += String.fromCharCode(plain[i])
};
elem.value = _plain;
elemLabel.innerText = ("Size of compressed string is: "
+ elem.value.length) + " "
+ ("Decompressed Value: " + _plain + " Size: " +
_plain.length);
};
compress.addEventListener("click", compress_string);
decompress.addEventListener("click", decompress_string);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="input_value" />
<button id="compress">compress</button>
<button id="decompress">decompress</button>
<br />
<label id="zlsize"></label>

Related

'object HTMLCollection' instead of Image URL from RSS

I'm trying to pull thumbnail URLs from a wordpress feed and keep getting [object HTMLCollection] instead of an image URL string for the thumbnail. The feed i'm pulling from is: https://harpercollegece.com/feed/. I know that the tag is named media:thumbnail and the value is stored in 'URL'. I can't find the correct way to reference this image inside of the forEach loop when running through each post. I've tried searching other posts as well as on google for several hours.
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
getElementsByTagName returns an HTMLCollection. To get the URL, you'll have to grab the first element in that collection with [0]. The URL is stored in an attribute called url, a la
<media:thumbnail url="https://harpercollegece.files.wordpress.com/2021/01/writing-red-typewriter-typing.jpg" />
From your HTMLElement, get the url attribute like so:
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>

Trying to loop through large string to find matching substrings

I have one large string with '----begin----' and '----end----' through out the string. I am trying to seperate out each message and display them all inside a div as seperate messages. The following code gets me the first one but I am struggling with the logic to loop through a large string with many messages. How do I loop through the entire large string? Thank you.
var app = document.querySelector('#app');
function parseStr(str) {
var start_idx = str.indexOf('------Begin Message------');
var end_idx = str.indexOf('------End Message------');
app.innerHTML += '<p>' + str.substring(start_idx, start_idx + 27) + '</p>' + '<p>' +
str.substring(start_idx + 27, end_idx) + '</p><p>' +
str.substring(end_idx, end_idx + 23);
}
parseStr(str);
Below code will replace all your header and footer message text to <p> </p> tags giving you back a complete html string.
function parseStr(str) {
let beginMsg = "------Begin Message------";
let endMsg = "------End Message------";
var re1 = new RegExp(beginMsg, "gi");
var re2 = new RegExp(endMsg, "gi");
str = str.replace(re1, "<p>").replace(re2, "</p>");
return str;
}
OR if you want it this way
function parseStr(str) {
let beginMsg = "------Begin Message------";
let endMsg = "------End Message------";
var re1 = new RegExp(beginMsg, "gi");
var re2 = new RegExp(endMsg, "gi");
str = str.replace(re1, "<div><p>"+beginMsg+"</p><p>").replace(re2, "</p><p>"+endMsg+"</p></div>");
return str;
}
This while-loop should go through all messages:
function parseStr(str) {
let beginMsg = "------Begin Message------"
let endMsg = "------End Message------"
while ((let end_idx = str.indexOf(endMsg)) !== -1) {
let start_idx = str.indexOf(beginMsg);
/* start of your code */
app.innerHTML += '<p>' +
str.substring(start_idx, start_idx + beginMsg.length) +
'</p><p>' + str.substring(start_idx + beginMsg.length, end_idx) +
'</p><p>' + str.substring(end_idx, end_idx + endMsg.length);
/* end of your code */
str = str.slice(end_idx + endMsg.length);
}
}
"Large string" is a kind of trigger word for programmers. It matters if we're thinking megabytes, or just a few pages of text. In the "large, but not crazy large" case, just split on the delimiters.
const bigString = "------Begin Message------This is a message------End Message------------Begin Message------This is another message------End Message------"
const startDelim = "------Begin Message------"
const endDelim = "------End Message------"
// use a regex with a conjunction start or ("|") end delimiter
let regex = new RegExp(`${startDelim}|${endDelim}`);
// split, then filter for the messages, processing each as a <p>
let messages = bigString.split(regex).reduce((acc, el, i) => {
if (i%2) acc.push(`<p>${el}</p>`)
return acc
}, [])
console.log(messages)
If it's truly large, you might not want it in memory, and you might not want all of the parsed pieces all in the dom at once.

How to Generate and validate JWE in node js?

I tried the bellow code to create RSA-OAEP and A128GCM JWE generator and validator. it works with node js , ie, encrypt claims and generate the jwe and decrypt the same gives me the claims. but it is not working with the other clients , like nimbusds jose, jose4j. So for a sure I am missing something.
I am doing this by reading https://www.rfc-editor.org/rfc/rfc7516
index.js
var crypto = require('crypto');
var randomstring = require("randomstring");
var ursa = require("ursa");
var fs = require("fs");
var base64url = require('base64url');
var ascii = require("./ASCII");
var claims = {
firstName: "vimal"
};
var header = {
"enc": "A128GCM",
"alg": "RSA-OAEP"
};
var headerBase64Url = base64url.encode(JSON.stringify(header));
console.log("headerBase64Url : " + headerBase64Url);
console.log("headerBase64Url to UTF8 : " + base64url.decode(headerBase64Url));
var cek = randomstring.generate(16);
console.log("cek : " + cek);
var publicKey = ursa.createPublicKey(fs.readFileSync('./pubkey.pem'));
var encryptedKey = publicKey.encrypt(cek, 'utf8', 'base64');
console.log("encryptedKey : " + encryptedKey);
// var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
// var decryptedKey = privateKey.decrypt(encryptedKey, "hex", "utf8");
// console.log("decryptedKey : " + decryptedKey);
var iv = randomstring.generate(12);
console.log("IV : " + iv);
var cipher = crypto.createCipheriv('aes-128-gcm', cek, iv);
cipher.setAAD(Buffer.from(ascii.toASCII(headerBase64Url)));
var chipherText = cipher.update(JSON.stringify(claims), "utf8", "base64");
chipherText += cipher.final('base64');
console.log("chipherText : " + chipherText);
var chipherTextAuthTag = cipher.getAuthTag().toString("base64");
console.log("chipherText Auth Tag : " + chipherTextAuthTag);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
console.log("jweToken : " + jweToken);
// decrypt
var jweTokenParts = jweToken.split(".");
var headerHex = base64url.decode(jweTokenParts[0]);
console.log(headerHex);
var encryptedKeyHex = base64url.decode(jweTokenParts[1], "base64");
console.log(encryptedKeyHex);
var ivHex = base64url.decode(jweTokenParts[2], "base64");
console.log(ivHex);
var chipperTextHex = base64url.decode(jweTokenParts[3], "base64");
console.log(chipperTextHex);
var chipherTextAuthTagHex = base64url.decode(jweTokenParts[4], "base64");
console.log(chipherTextAuthTagHex);
var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
var decryptedKeyHex = privateKey.decrypt(encryptedKeyHex, "base64", "utf8");
console.log("decryptedKeyHex : " + decryptedKeyHex);
var dcipher = crypto.createDecipheriv('aes-128-gcm', decryptedKeyHex, iv);
dcipher.setAAD(Buffer.from(ascii.toASCII(jweTokenParts[0])));
dcipher.setAuthTag(Buffer.from(chipherTextAuthTagHex, "base64"));
var planText = dcipher.update(chipperTextHex, "base64", "utf8");
planText += dcipher.final('utf8');
console.log(planText);
ASCII.js
function toASCII(text) {
var ascii = "";
for (var f in text) {
ascii = ascii + text.charCodeAt(f);
}
return ascii;
}
module.exports = {
toASCII: toASCII
};
Generated public and private key using the below command
openssl genrsa -out ./privkey.pem 2048
openssl pkcs8 -topk8 -inform pem -in ./privkey.pem -outform pem -nocrypt -out ./privkey.pkc8.pem
openssl rsa -in ./privkey.pkc8.pem -pubout -out ./pubkey.pem
Please help me to fix this code.
This is my public key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyT0HZHrlk8nN8HfTDq5t
dv6UCKHf7+RF1bICxaR4h2vzGCqcYUlzyW7Sp33BZAHDeO3d5tX26m7z2EOPaOPn
SSe6psgvBmE4Ivyc3+uyIYJm+Eo9bXiqqfvuDRidXsHj23w41l6GMERKbpOBVvp+
dmWt/cWU8FESvKUqNw/Au2R9mE1sQ5irMQj42hhUrVA1azs2AYpysKNZABm11YMb
/vd/xSPLsNqcDefuCs7j3CcT9xNLrMV6K63QjCAP+h0IMuA+ayi3WRUbl04D6cAC
AC97/cKMC0YLRumbf5x5/KjUBwNlzgRA3/n9KE+YjJ9Rs9dtiGnlg+c70Kgx4hm9
9QIDAQAB
-----END PUBLIC KEY-----
Generated JWE
eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.A_KMJqfr6FZSoejRGWPsZKMCNZmPyaWoNvpG6KMRpqyv7Alb8Ui5ELWLjpcaemjNM8EFU8d4-Yzz8jRRZ5TpK2pEEc4NXfDLcnj2b0-38_-P-0HbW1YyMkkGMVXIpJDYMo8vKgVHIBj0pNlzgF7xmxLFWZlJlXmYzXi4QZcig5HezHg7AAQB7U2HYry25cQDYam60747gRCH372NaSm_dfRCNvH8copVXqiJGNs6xhslxMt_LopnZt9iIcAC9o7m0FPdnu_0Ui_w0jp5OUam8i0v8k6SSajBvXSedtUENxcehPGRSFYzi8KqZ53u4CpRygir84wNFRTi7zmLV6TlVw.84xgyx6TTI8I.4zTt1fI1XCbvxW2L-pH8_Mfp_ySF.EPmpEHiMYAvA2nqz9M0v5Q
It looks like the IV is not correctly encoded using Base64 Url.
On my computer, when I execute the following line of code:
console.log(iv);
console.log(base64url.encode(iv, "base64"));
Then the two lines are identical.
When I modify your code:
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
lnto these lines:
var bufferedIV = new Buffer(iv);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(bufferedIV, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
Then it works fine ; I can load the resulting JWE using my PHP library.
From my understanding, the error comes from the base64url dependency that does not correctly encode the IV.

calculate md5 of image loaded in java webdriver

I want calculate md5 of images that loaded in webdriver in java.
webdriver is Firefox.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;
String script = "var imgElement = document.querySelector('div.mtl:nth-child(2) > div:nth-child(1) > img:nth-child(1))'; *** return md5 of image *** ";
String url = "http://www.facebook.com";
WebDriver webDriver = new FirefoxDriver();
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
Stgin md5 = (String) js.executeScript(script);
in this code, what must replace with :
*** return md5 of image ***
You can use fetch with force-cache to get the content from cache. Then digest the arrayBuffer from the response. Unfortunately, MD5 is too old and the browser doesn't support it anymore. See more details about Crypto here. You can choose SHA-1, SHA-256, SHA-384, and SHA-512. See an example to digest SHA-256 below.
public void getImageSHA256(){
driver.get("https://www.blognone.com/");
WebElement img = driver.findElement(By.cssSelector("img"));
String imgUrl = img.getAttribute("src").trim();
String script = "function hex(buffer) { var hexCodes = []; var view = new DataView(buffer); for (var i = 0; i < view.byteLength; i += 4) { var value = view.getUint32(i); var stringValue = value.toString(16); var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue); } return hexCodes.join(\"\");}" +
"var callback = arguments[arguments.length - 1];" +
"fetch(arguments[0],{cache:'force-cache'}).then((response)=> {" +
"return response.arrayBuffer(); }).then((buffer)=>{" +
" return crypto.subtle.digest('SHA-256', buffer); }).then((hashArray)=>{" +
" callback(hex(hashArray));"+
"});";
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
System.out.println(response);
}
Screenshot below show comparison between SHA-256 from my code and SHA-256 from an online tool.
public void getImageMD5(){
driver.get("https://www.blognone.com/");
WebElement img = driver.findElement(By.cssSelector("img"));
String imgUrl = img.getAttribute("src").trim();
String script = "var callback = arguments[arguments.length - 1];"
+ "function _arrayBufferToBase64( buffer ) {"
+ " var binary = '';"
+ " var bytes = new Uint8Array( buffer );"
+ " var len = bytes.byteLength;"
+ " for (var i = 0; i < len; i++) {"
+ " binary += String.fromCharCode( bytes[ i ] );"
+ " }"
+ " return window.btoa( binary );"
+ "}"
+ " fetch(' " + imgUrl + " ',{cache:'force-cache'})."
+ "then((response)=>{return response.arrayBuffer()})."
+ "then((response)=>{return _arrayBufferToBase64(response)})."
+ "then((response)=>{callback(response)});";
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
byte[] data = Base64.getDecoder().decode((String) response);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(data);
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
String digest = sb.toString();
System.out.println("MD5 of Image : " + digest);
}

Get Text information sort and number them an put ";" after number and after each block

Again some Problems.
I' get some values of a Textfield ,shown like them:
134.45 987.46 -89.10
224.67 127.26 -19.12
764.32 187.96 -78.25
...and so on...
I'm get them with
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text();
}
i need them in
1;134.45;987.46;-89.10< br /><<< yes also the break - it will written in a .TXT file >>>
2;224.67;127.26;-19.12< br />
3;764.32;187.96;-78.25< br />
...and so on...
I couldn't figure it out how to. seems insoluble :(
The hekp from "guest271314" was perfekt. i've built it a Little more dynamic.
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text().replace(/\s+X/, "");
var arr = getNP01TableData.split(/\s+/);
var _arr = [];
var index = 1;
for (var i = 1; i <= (arr.length-1)/3; i++) {
_arr.push( i + ";" + arr[index] + ";" + arr[index + 1] + ";" + arr[index + 2] + "<br />\n");
index = index + 3;
}
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
// ... code to write it back in txt file
}
Thanks a lot # all for your Help
Well, let's look at what you've got: you have a text block, with numbers separated by spaces. That's something we can work with.
The .split(" ") function will separate the numbers and put them in an array; you could do a
getNP01TableData.split(" ") and your result will be:
[" ", "134.45 ", "987.46 ", "-89.10", "
", "224.67 ", "127.26 ", "-19.12
", "764.32 ", "187.96 ", "-78.25" ]
And that definitely looks like something you can work with. Throw that bad boy into a loop:
var text = "";
for (var i = 0; i<arr.length/3; i++) {
text = text + i;
for (j = 0; j<3; j++) {
text=text+";"+arr[3*i + j]
}
text = text+"</br";
}
That might need a little fiddling, but you get the idea. Also, the .trim() function is useful for removing unwanted whitespace.
Try
var text = "134.45 987.46 -89.10 224.67 127.26 -19.12 764.32 187.96 -78.25";
var arr = $.map(text.split(" "), function (value, index) {
return value === "" ? null : [value]
});
var _arr = [];
_arr.push("1;" + arr.slice(0, 3).join(",").replace(/,/g, ";") + "<br />");
_arr.push("2;" + arr.slice(3, 6).join(",").replace(/,/g, ";") + "<br />");
_arr.push("3;" + arr.slice(6, 9).join(",").replace(/,/g, ";") + "<br />");
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
var reader = new FileReader();
reader.addEventListener("loadend", function (e) {
console.log(e.target.result);
});
reader.readAsText(file);
jsfiddle http://jsfiddle.net/guest271314/YpBxA/

Categories